[英]Gaussian fit for Python
我正在尝试为我的数据拟合高斯(这已经是一个粗略的高斯)。 我已经听取了这里的建议并尝试了curve_fit
和leastsq
但我认为我缺少一些更基本的东西(因为我不知道如何使用该命令)。 这是我到目前为止的脚本
import pylab as plb
import matplotlib.pyplot as plt
# Read in data -- first 2 rows are header in this example.
data = plb.loadtxt('part 2.csv', skiprows=2, delimiter=',')
x = data[:,2]
y = data[:,3]
mean = sum(x*y)
sigma = sum(y*(x - mean)**2)
def gauss_function(x, a, x0, sigma):
return a*np.exp(-(x-x0)**2/(2*sigma**2))
popt, pcov = curve_fit(gauss_function, x, y, p0 = [1, mean, sigma])
plt.plot(x, gauss_function(x, *popt), label='fit')
# plot data
plt.plot(x, y,'b')
# Add some axis labels
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()
我从中得到的是一个高斯形状,这是我的原始数据,以及一条水平直线。
另外,我想使用点绘制我的图形,而不是将它们连接起来。 任何输入表示赞赏!
这是更正的代码:
import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])
n = len(x) #the number of data
mean = sum(x*y)/n #note this correction
sigma = sum(y*(x-mean)**2)/n #note this correction
def gaus(x,a,x0,sigma):
return a*exp(-(x-x0)**2/(2*sigma**2))
popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])
plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()
结果:
您需要良好的起始值,以便curve_fit
函数收敛于“良好”值。 我真的不能说为什么你的拟合没有收敛(即使你的平均值的定义很奇怪 - 请在下面查看)但我会给你一个适用于像你这样的非标准化高斯函数的策略。
估计参数应该接近最终值(使用加权算术平均值- 除以所有值的总和):
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
x = np.arange(10)
y = np.array([0, 1, 2, 3, 4, 5, 4, 3, 2, 1])
# weighted arithmetic mean (corrected - check the section below)
mean = sum(x * y) / sum(y)
sigma = np.sqrt(sum(y * (x - mean)**2) / sum(y))
def Gauss(x, a, x0, sigma):
return a * np.exp(-(x - x0)**2 / (2 * sigma**2))
popt,pcov = curve_fit(Gauss, x, y, p0=[max(y), mean, sigma])
plt.plot(x, y, 'b+:', label='data')
plt.plot(x, Gauss(x, *popt), 'r-', label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()
我个人更喜欢使用 numpy。
由于审阅者不喜欢我对 #Developer's code 的编辑,我将解释在什么情况下我会建议改进代码。 开发人员的平均值不符合平均值的正常定义之一。
您的定义返回:
>>> sum(x * y)
125
开发者定义返回:
>>> sum(x * y) / len(x)
12.5 #for Python 3.x
加权算术平均值:
>>> sum(x * y) / sum(y)
5.0
同样,您可以比较标准偏差 ( sigma
) 的定义。 与得到的拟合图进行比较:
在 Python 2.x 中,您还应该使用新的除法来避免出现奇怪的结果或显式转换除法之前的数字:
from __future__ import division
或例如
sum(x * y) * 1. / sum(y)
你得到一条水平直线,因为它没有收敛。
如果在示例中将拟合的第一个参数 (p0) 设为 max(y), 5 而不是 1,则可以获得更好的收敛性。
在花了几个小时试图找到我的错误之后,问题是你的公式:
sigma = sum(y*(x-mean)**2)/n
这个前面的公式是错误的,正确的公式是这个的平方根!;
sqrt(sum(y*(x-mean)**2)/n)
希望这有帮助
还有另一种执行拟合的方法,即使用 'lmfit' 包。 它基本上使用 cuve_fit 但在拟合方面要好得多,并且还提供复杂的拟合。 下面的链接中给出了详细的分步说明。 http://cars9.uchicago.edu/software/python/lmfit/model.html#model.best_fit
sigma = sum(y*(x - mean)**2)
应该是
sigma = np.sqrt(sum(y*(x - mean)**2))
实际上,您无需进行初步猜测。 简单地做
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])
n = len(x) #the number of data
mean = sum(x*y)/n #note this correction
sigma = sum(y*(x-mean)**2)/n #note this correction
def gaus(x,a,x0,sigma):
return a*exp(-(x-x0)**2/(2*sigma**2))
popt,pcov = curve_fit(gaus,x,y)
#popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])
plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()
工作正常。 这更简单,因为进行猜测并非易事。 我有更复杂的数据,并没有设法进行正确的第一次猜测,但只需删除第一次猜测就可以正常工作:)
PS:使用 numpy.exp() 更好,说 scipy 的警告
这个问题也在这里得到了回答: How can I fit a gaussian curve in python?
在 MSeifert 的回答中,还提到了使用 astropy 包的简单高斯建模。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.