Search code examples
pythongaussianmixture-model

How to construct and plot uni-variate Gaussian Mixture using its parameters in Python


I want to construct and 1D plot a uni-variate Gaussian Mixture with say three components in Python where I already have its parameters including mu,sigma,mix coefficients.

What I am after has an equivalent in MATLAB i.e. gmdistribution(mu,sigma,p)

I think the code should look sth like this:

from numpy import *
from matplotlib.pylab import *
from sklearn import mixture

gmm = mixture.GMM(n_components=3)
gmm.means_ = np.array([[-1], [0], [3]])
gmm.covars_ = np.array([[1.5], [1], [0.5]]) ** 2
gmm.weights_ = np.array([0.3, 0.5, 0.2])
fig = plt.figure(figsize=(5, 1.7))

ax = fig.add_subplot(131)
#ax.plot(gmm, '-k') 

Wondering how to do it...

Cheers


Solution

  • Assuming the Gaussian's are independent, and you want to plot the pdf, you can just combine the underlying Gaussian pdfs weighted by the probabilities:

    import numpy as np
    import scipy.stats as ss
    import matplotlib.pyplot as plt
    
    means = -1., 0., 3.
    stdevs = 1.5, 1., 0.5
    weights = 0.3, 0.5, 0.2
    
    x = np.arange(-5., 5., 0.01)
    
    pdfs = [p * ss.norm.pdf(x, mu, sd) for mu, sd, p in zip(means, stdevs, weights)]
    
    density = np.sum(np.array(pdfs), axis=0)
    plt.plot(x, density)
    

    That this is correct requires a little elementary probability theory.