python - 用curve_fit拟合函数,但拟合曲线错误
问题描述
def gaus(x,a,x0,sigma):
return a*np.exp(-(x-x0)**2/(2*sigma**2))
times, amplitudes = openFile("../datafiles/number_of_counts.txt")
mean = sum(np.array(times)*np.array(amplitudes))/sum(amplitudes)
sigma = np.sqrt(sum(np.array(amplitudes)*(np.array(times)-mean)**2)/sum(amplitudes))
params,pcov = curve_fit(gaus,times, amplitudes,p0=[max(amplitudes),mean,sigma])
plt.plot(times, amplitudes)
plt.plot(times ,gaus(np.array(times),params[0],params[1],params[2]),'r', label="fitted curve")
plt.ylabel("Coincidents")
plt.title("Coincident plot")
plt.legend()
plt.show()
我的高斯拟合不能正常工作,但看起来像一条柔软的曲线,而不是为了拟合尖峰,我认为我的脚本中有一些超级愚蠢的错误,但不确定是什么。有谁能看出来?
解决方案
您的数据具有大约 3750 的恒定偏移量,但您的gaus
模型函数无法解释这一点,因此您正在拟合偏移量为 0 的正态分布。
它还需要一个参数:
def gaus(x, a, x0, sigma, c):
return a * np.exp(-(x - x0)**2 / (2 * sigma**2)) + c
然后:
offset_guess = 3750 # maybe calculate it from the data as well
params, pcov = curve_fit(
gaus, times, amplitudes,
p0=[max(amplitudes), mean, sigma, offset_guess])
plt.plot(times, gaus(np.array(times), params[0], params[1], params[2], params[3]), ...)
结果:
>>> print(params)
[1545.00193331 -20.45639132 -43.28484495 3792.41050636]
推荐阅读
- reactjs - 从 React 播放视频
- android - Mapbox 未在 Android 模拟器上显示真实位置
- python - 有没有办法在 python 3.7 中手动清除 ram?
- java - WebSocket 找不到实现类错误
- haskell - 如何在 Haskell 中“扩展”类
- html - 显示滑动背景图片
- security - HPE Security Fortify Assessment is not showing " List of HPE Security Fortify SSC issues " in jenkins after uploading .fpr report on ssc portal
- php - 在 WooCommerce 管理订单列表中批量操作添加自定义取消订单状态
- c++ - 如何获取大约 100000 位长度的大量输入
- javascript - 如何过滤嵌套数组对象?