gaussian函数?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (135)

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

你可以使用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

用户回答回答于

你可以使用scipy.optimize.curve_fit用来适应你想要的任何功能。下面的代码显示了如何将高斯函数拟合到一些随机数据

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()

所属标签

可能回答问题的人

  • 人生的旅途

    10 粉丝484 提问5 回答
  • 天使的炫翼

    17 粉丝531 提问5 回答
  • 不吃貓的鱼oo

    4 粉丝466 提问4 回答
  • 找虫虫

    0 粉丝0 提问4 回答

扫码关注云+社区

领取腾讯云代金券