在python sklearn中对一维数组使用高斯混合

use*_*551 6 python gaussian scikit-learn mixture

我想使用高斯混合模型来返回如下图所示的内容,除了正确的高斯分布。

我正在尝试使用 pythonsklearn.mixture.GaussianMixture但我失败了。我可以将每个峰值视为任何给定 x 值的直方图的高度。我的问题是:我是否必须找到一种方法将这个图转换为直方图并删除负值,或者有没有办法将 GMM 直接应用于这个数组以产生红色和绿色高斯?

在此处输入图片说明

Gab*_*l M 5

使用高斯曲线拟合曲线以通过一组点与使用 GMM 对某些数据的概率分布进行建模之间存在差异。

当您使用 GMM 时,您正在做的是后者,它不会起作用。

  • 如果您仅使用 Y 轴上的变量应用 GMM,您将得到 Y 的高斯分布,但不考虑 X 变量。
  • 如果您使用 2 个变量应用 GMM,您将获得对您的问题没有任何帮助的二维高斯。

现在,如果您想要的是拟合高斯曲线。试试这个问题的答案。

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:
# Adapt it to as many gaussians you may want
# by copying the function with different A2,mu2,sigma2 parameters
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()
Run Code Online (Sandbox Code Playgroud)

关于如何为多个高斯调整代码的更新:

def gauss2(x, *p):
    A1, mu1, sigma1, A2, mu2, sigma2 = p
    return A1*numpy.exp(-(x-mu1)**2/(2.*sigma1**2)) + A2*numpy.exp(-(x-mu2)**2/(2.*sigma2**2))

# p0 is the initial guess for the fitting coefficients initialize them differently so the optimization algorithm works better
p0 = [1., -1., 1.,1., -1., 1.]

#optimize and in the end you will have 6 coeff (3 for each gaussian)
coeff, var_matrix = curve_fit(gauss, X_data, y_data, p0=p0)

#you can plot each gaussian separately using 
pg1 = coeff[0:3]
pg2 = coeff[3:]

g1 = gauss(X_data, *pg1)
g2 = gauss(X_data, *pg2)

plt.plot(X_data, y_data, label='Data')
plt.plot(X_data, g1, label='Gaussian1')
plt.plot(X_data, g2, label='Gaussian2')
Run Code Online (Sandbox Code Playgroud)