首页 文章

将高斯拟合到一组x,y数据

提问于
浏览 1430 次
1

首先这是一个我已经设置的赋值所以我只是在指针之后,我只能使用以下库,NumPy,SciPy和MatPlotLib .

我们给出了一个txt文件,其中包含用于共振实验的x和y数据,并且必须适合高斯和洛伦兹拟合 . 我正在研究高斯拟合,并尝试按照前一个问题中的代码作为我自己的代码的基础 . (Gaussian fit for Python

from numpy import *
from matplotlib import *
import matplotlib.pyplot as plt  ##Import Libraries
import pylab
from scipy.optimize import curve_fit

####################################

energy,intensity=numpy.loadtxt('resonance_data.txt',unpack=True)
print energy
print intensity  ##Load in text file and print the arrays




#####################################

n = size(energy)
mean = 30.7
sigma = 10
intensity0 = 45

def gaus(energy,intensity0,energy0,sigma):
       return intensity0*exp(-(energy-energy0)**2/(sigma**2))

popt,pcov = curve_fit(gaus,energy,intensity,p0=[45,mean,sigma])



plt.plot(energy,intensity,'o')
plt.xlabel('Energy/eV')
plt.ylabel('Intensity')
plt.title('Plot of Intensity against Energy')  ##Plot raw data along with axis labels         and title
plt.plot(energy,gaus(energy,*popt))
plt.show()

返回以下图表

enter image description here

如果我保留mean和sigma的表达式,就像发布的url一样,曲线拟合是一条水平线,所以我猜测问题在于曲线拟合不融合或什么的 .

我有点像初学者,所以任何指针都有帮助:)

谢谢

更新:我已经设法改善高斯拟合并使Lorentzian工作,甚至(我认为)设法计算每种情况下残差的总和 .

干杯啦!

再次感谢你们

1 回答

  • 0

    看起来你的数据偏向左边,为什么高斯?不是Boltzmann,Log-Normal还是其他什么?

    其中大部分已在 scipy.stats 中实施 . 有关lorentzian和 scipy.stats.normal 高斯,请参阅 scipy.stats.cauchy . 一个例子:

    import scipy.stats as ss
    A=ss.norm.rvs(0, 5, size=(100)) #Generate a random variable of 100 elements, with expected mean=0, std=5
    ss.norm.fit_loc_scale(A) #fit both the mean and std
    (-0.13053732553697531, 5.163322485150271) #your number will vary.
    

    而且我认为你不需要 intensity0 参数,它只是 1/sigma/srqt(2*pi) ,因为密度函数必须总和为1 .

相关问题