适合高斯函数

时间:2012-07-16 15:02:17

标签: python matplotlib scipy histogram curve-fitting

我有一个直方图(见下文),我试图找到平均值和标准偏差以及符合我的直方图曲线的代码。我认为SciPy或matplotlib中有一些东西可以提供帮助,但我尝试的每个例子都不起作用。

import matplotlib.pyplot as plt
import numpy as np

with open('gau_b_g_s.csv') as f:
    v = np.loadtxt(f, delimiter= ',', dtype="float", skiprows=1, usecols=None)

fig, ax = plt.subplots()

plt.hist(v, bins=500, color='#7F38EC', histtype='step')

plt.title("Gaussian")
plt.axis([-1, 2, 0, 20000])

plt.show()

4 个答案:

答案 0 :(得分:36)

查看this answer以将任意曲线拟合到数据。基本上,您可以使用scipy.optimize.curve_fit来适应您想要的任何数据功能。下面的代码显示了如何将Gaussian拟合到某些随机数据(信用到this SciPy-User邮件列表帖子)。

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

# Define some test data which is close to Gaussian
data = numpy.random.normal(size=10000)

hist, bin_edges = numpy.histogram(data, density=True)
bin_centres = (bin_edges[:-1] + bin_edges[1:])/2

# Define model function to be used to fit to the data above:
def gauss(x, *p):
    A, mu, sigma = p
    return A*numpy.exp(-(x-mu)**2/(2.*sigma**2))

# p0 is the initial guess for the fitting coefficients (A, mu and sigma above)
p0 = [1., 0., 1.]

coeff, var_matrix = curve_fit(gauss, bin_centres, hist, p0=p0)

# Get the fitted curve
hist_fit = gauss(bin_centres, *coeff)

plt.plot(bin_centres, hist, label='Test data')
plt.plot(bin_centres, hist_fit, label='Fitted data')

# Finally, lets get the fitting parameters, i.e. the mean and standard deviation:
print 'Fitted mean = ', coeff[1]
print 'Fitted standard deviation = ', coeff[2]

plt.show()

答案 1 :(得分:13)

您可以尝试sklearn高斯混合模型估计如下:

import numpy as np
import sklearn.mixture

gmm = sklearn.mixture.GMM()

# sample data
a = np.random.randn(1000)

# result
r = gmm.fit(a[:, np.newaxis]) # GMM requires 2D data as of sklearn version 0.16
print("mean : %f, var : %f" % (r.means_[0, 0], r.covars_[0, 0]))

参考:http://scikit-learn.org/stable/modules/mixture.html#mixture

请注意,通过这种方式,您无需使用直方图估算样本分布。

答案 2 :(得分:2)

有点老问题,但对于任何想要绘制适合系列的密度的人来说,你可以试试matplotlib的.plot(kind='kde')。文档here

pandas示例:

mydf.x.plot(kind='kde')

答案 3 :(得分:0)

我不确定您的输入是什么,但可能您的y轴刻度太大(20000),请尝试减少此数字。以下代码适用于我:

import matplotlib.pyplot as plt
import numpy as np

#created my variable
v = np.random.normal(0,1,1000)


fig, ax = plt.subplots()


plt.hist(v, bins=500, normed=1, color='#7F38EC', histtype='step')

#plot
plt.title("Gaussian")
plt.axis([-1, 2, 0, 1]) #changed 20000 to 1

plt.show()

编辑:

如果您想在y轴上实际计算值,可以设置normed=0。并且会摆脱plt.axis([-1, 2, 0, 1])

import matplotlib.pyplot as plt
import numpy as np

#function
v = np.random.normal(0,1,500000)


fig, ax = plt.subplots()

# changed normed=1 to normed=0
plt.hist(v, bins=500, normed=0, color='#7F38EC', histtype='step')

#plot
plt.title("Gaussian")
#plt.axis([-1, 2, 0, 20000]) 

plt.show()