首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >拟合高斯函数

拟合高斯函数
EN

Stack Overflow用户
提问于 2012-07-16 23:02:17
回答 4查看 81.4K关注 0票数 27

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

代码语言:javascript
复制
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()
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-07-16 23:42:02

看看将任意曲线拟合到数据的this answer。基本上,您可以使用scipy.optimize.curve_fit来适应您的数据所需的任何函数。下面的代码展示了如何将高斯函数拟合到一些随机数据(归功于this SciPy-用户邮件列表帖子)。

代码语言:javascript
复制
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()
票数 44
EN

Stack Overflow用户

发布于 2012-07-16 23:35:32

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

代码语言:javascript
复制
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

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

票数 16
EN

Stack Overflow用户

发布于 2015-09-29 00:37:33

这是一个古老的问题,但是对于任何想要绘制适合于一系列的密度的人来说,你可以尝试matplotlib的.plot(kind='kde')。Docs here

以熊猫为例:

代码语言:javascript
复制
mydf.x.plot(kind='kde')
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11507028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档