我有一个直方图(见下文),我正在尝试找出均值和标准差以及将曲线拟合到直方图的代码。我认为在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()
发布于 2012-07-16 23:42:02
看看将任意曲线拟合到数据的this answer。基本上,您可以使用scipy.optimize.curve_fit
来适应您的数据所需的任何函数。下面的代码展示了如何将高斯函数拟合到一些随机数据(归功于this SciPy-用户邮件列表帖子)。
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-16 23:35:32
您可以尝试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
请注意,通过这种方式,您不需要使用直方图来估计样本分布。
发布于 2015-09-29 00:37:33
这是一个古老的问题,但是对于任何想要绘制适合于一系列的密度的人来说,你可以尝试matplotlib的.plot(kind='kde')
。Docs here。
以熊猫为例:
mydf.x.plot(kind='kde')
https://stackoverflow.com/questions/11507028
复制相似问题