27

我有一个直方图(见下文),我试图找到平均值和标准偏差以及适合我的直方图曲线的代码。我认为 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

4 回答 4

44

看看这个答案,以将任意曲线拟合到数据中。基本上你可以使用scipy.optimize.curve_fit你想要的任何函数来适应你的数据。下面的代码显示了如何将高斯拟合到一些随机数据(归功于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()
于 2012-07-16T15:42:02.027 回答
16

您可以尝试 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

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

于 2012-07-16T15:35:31.823 回答
2

有点老问题,但对于任何只想绘制适合系列的密度的人,您可以尝试 matplotlib 的.plot(kind='kde'). 文档在这里

熊猫的例子:

mydf.x.plot(kind='kde')
于 2015-09-28T16:37:32.517 回答
1

我不确定您的输入是什么,但可能您的 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()
于 2012-07-16T15:29:15.990 回答