首页 > 解决方案 > Python中的高斯拟合

问题描述

我正在尝试用高斯拟合来拟合一些数据。该数据来自横向流动图像。拟合线(红色)不包括数据。请检查我的代码。在代码中 x 只是索引。y 实际上是真实数据。

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit



y = np.array([2.22097081, 2.24776432, 2.35519896, 2.43780396, 2.49708355,
       2.54224971, 2.58350984, 2.62965057, 2.68644093, 2.75454015,
       2.82912617, 2.90423835, 2.97921199, 3.05864617, 3.14649922,
       3.2430853 , 3.3471892 , 3.45919857, 3.58109399, 3.71275641,
       3.84604379, 3.94884214, 3.94108998, 3.72148453, 3.28407665,
       2.7651018 ])

x = np.linspace(1,np.mean(y),len(y))


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

def gaus(x,a,x0,sigma):
    return a*np.exp(-(x-x0)**2/(2*sigma**2))/(sigma*np.sqrt(2*np.pi))

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

plt.figure()
plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.xlabel('Index')
plt.ylabel('Row Mean')

在此处输入图像描述

标签: pythongaussianscipy-optimize

解决方案


推荐阅读