python多高斯拟合(参数估计)

2024-06-16 08:26:58 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的data。你知道吗

我正在尝试使用scipy和曲线拟合对数据进行高斯拟合,以下是我的代码:

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

df=pd.read_csv("dene2.dat", sep=" ")

x=df.x
y=df.y

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

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('Intensity (Counts)')

plt.show()

拟合高斯图也不符合预期,你能帮我吗?你知道吗


Tags: fromimportdfdataasnppltscipy
1条回答
网友
1楼 · 发布于 2024-06-16 08:26:58

可以使用两个高斯数的叠加来获得更好的拟合。你知道吗

def gaus(x,a,x0,sigma, b, x1, sigma1):
    return a*exp(-(x-x0)**2/(2*sigma**2)) + b*exp(-(x-x1)**2/(2*sigma1**2))

popt,pcov = curve_fit(gaus,x,y,p0=[1.6, 380, 10, 1.5, 690, 10])

这里1.6, 380, 10, 1.5, 690, 10是数据中第一个和第二个清晰峰值的高度、平均值和宽度的近似初始猜测。你知道吗

你可以试着用三个高斯来得到更好的拟合。Here是一个类似的帖子。你知道吗

enter image description here

相关问题 更多 >