繁体   English   中英

高斯曲线拟合python

[英]Gaussian curve fitting python

我在用高斯函数拟合某个日期时遇到问题。 我尝试以多种不同的方式做到这一点,但都没有奏效。 我需要一些想法。 附上数据(第 2 列和第 3 列)。


import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from numpy import asarray as ar,exp



x = ar(range(19))
y = ar(0, 0, 0, 0, 0, 0, 0.01955, 1.163025, 19.7159833333333, 81.3119708333334,80.0329166666667,19.3835833333333, 0.03378, 0, 0, 0, 0, 0, 0)

#y = ar(007, 0.04, .175, .628, 1.89, 4.78,10.034,17.542, 25.589, 31.1, 31.544, 26.65, 18.74, 11.01, 5.39, 2.209, 0.74, 0.215. 0.049)


n = len(x)                          
mean = sum(x*y)/n                   
sigma = sum(y*(x-mean)**2)/n        

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.scatter(x,y, color='blue')
plt.plot(x,y,label='data', marker='', color='blue', linestyle='-', linewidth=2)
plt.scatter(x,gaus(y,*popt), color='red')
plt.plot(x,gaus(y,*popt),label='fit', marker='', color='Red', linestyle='--', linewidth=2)

print(len(x))
print(mean,sigma)

plt.legend()

plt.xlabel('No of Resets', fontsize=20)
plt.ylabel('Frequency', fontsize=20)

plt.legend(loc='upper right')
plt.title('Gaussian Fit', fontsize=20)

plt.show()

我同意@ddejohn。

但是,您错误地计算了平均值和标准差。 您可以对积分使用以下近似值

import numpy as np
mean = (x*(y/y.sum())).sum()
sigma = np.sqrt(((y/y.sum())*(x-mean)**2).sum())

这些应该用作您注释行中拟合的初始猜测,您还可以在其中添加a0 = y.max()作为幅度。

popt,pcov = curve_fit(gaus,x,y,p0=[a0,mean,sigma])

然后像@ddejohn 所说的那样绘制可能有更多的样本点

xx = np.linspace(x[0], x[-1], 100)
plt.plot(xx,gaus(xx,*popt),label='fit', marker='', color='Red', linestyle='--', linewidth=2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM