簡體   English   中英

在python sklearn中使用高斯混合為1D數組

[英]Using Gaussian Mixture for 1D array in python sklearn

我想使用高斯混合模型返回下面的圖像,除了適當的高斯。

我正在嘗試使用python sklearn.mixture.GaussianMixture但我失敗了。 我可以將每個峰視為任何給定x值的直方圖的高度。 我的問題是:我是否必須找到一種方法將此圖形轉換為直方圖並刪除負值,或者是否有辦法將GMM直接應用於此數組以生成紅色和綠色高斯?

在此輸入圖像描述

使用高斯曲線擬合曲線以通過一組點並使用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()

更新如何調整多個高斯的代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM