将高斯和洛伦兹拟合到python中的数据

时间:2017-04-19 14:36:41

标签: python curve-fitting gaussian

我已经将一组数据加载到python并且认为我已经适合高斯和洛伦兹形状,但是我需要它来打印每个参数的值以及相关的错误,并且我没有'我知道怎么做。

我是编程的新手,所以任何帮助都将不胜感激!

这是我的代码:

import numpy as np                                                
import matplotlib.pyplot as plt                                    
import pylab as p                                                  
from scipy.optimize import curve_fit, leastsq                      
import math
from scipy.stats import norm

E,I = np.loadtxt('resonance_data.txt', unpack = True)

# Function to be fitted
def gauss(E, I0, E0, sigma):
    n = len(E)
    mean = sum(E*I)/sum(I)
    sigma = (np.sqrt(sum((E - mean)**2)/sum(I)))
    I0 = max(I)
    E0 = 31
    return I0* np.exp(-((E-E0)/sigma)**2)

sigmaerror = sigma - 28.01177

print sigmaerror

def lorentz(E,I0,E0,gamma):
    I0 = max(I)
    E0 = 31
    return I0*((gamma**2)/(((E-E0)**2)+gamma**2))

# Initialization parameters
init_vals = [45., 31., 33.]

best_vals, covar = curve_fit(gauss,E,I,p0=init_vals)
print best_vals

print curve_fit(gauss, E, I, p0=[max(I), mean, sigma])
print curve_fit(lorentz, E, I, p0=[max(I), mean, sigma])

plt.plot(E,I,'b+:',label='data')

popt,pcov = curve_fit(gauss,E,I,p0=[max(I), mean, sigma])
plt.plot(E,gauss(E,*popt),'r-',label='Gaussian')

popt,pcov = curve_fit(lorentz,E,I,p0=[max(I),mean,sigma])
plt.plot(E,lorentz(E,*popt), 'g', label='Lorentz')

plt.legend()
plt.title('Energy vs Intensity')
plt.xlabel('Energy')
plt.ylabel('Intensity')
plt.show()
print 'sigma =',sigma, 'error =', sigmaerror
print 'E0 = 34.22349966'
print 'I0 = 44.84743332'

1 个答案:

答案 0 :(得分:1)

只需打印poptpcov

print(popt)
print(pcov)

它们按照您向模型提供的顺序包含参数和协方差。