Show Sidebar Hide Sidebar

Gaussian Mixture Model Selection in Scikit-learn

This example shows that model selection can be performed with Gaussian Mixture Models using information-theoretic criteria (BIC). Model selection concerns both the covariance type and the number of components in the model. In that case, AIC also provides the right result (not shown to save time), but BIC is better suited if the problem is to identify the right model. Unlike Bayesian procedures, such inferences are prior-free.

In that case, the model with 2 components and full covariance (which corresponds to the true generative model) is selected.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version

In [1]:
import sklearn
sklearn.__version__
Out[1]:
'0.18.1'

Imports

In [2]:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly import tools

import numpy as np
import itertools
import math

from scipy import linalg
from sklearn import mixture

Calculations

In [3]:
# Number of samples per component
n_samples = 500

# Generate random sample, two components
np.random.seed(0)
C = np.array([[0., -0.1], [1.7, .4]])
X = np.r_[np.dot(np.random.randn(n_samples, 2), C),
          .7 * np.random.randn(n_samples, 2) + np.array([-6, 3])]

lowest_bic = np.infty
bic = []
n_components_range = range(1, 7)
cv_types = ['spherical', 'tied', 'diag', 'full']
for cv_type in cv_types:
    for n_components in n_components_range:
        # Fit a Gaussian mixture with EM
        gmm = mixture.GaussianMixture(n_components=n_components,
                                      covariance_type=cv_type)
        gmm.fit(X)
        bic.append(gmm.bic(X))
        if bic[-1] < lowest_bic:
            lowest_bic = bic[-1]
            best_gmm = gmm

bic = np.array(bic)
color_iter = itertools.cycle(['navy', 'turquoise', 'cornflowerblue',
                              'darkorange'])
clf = best_gmm

Plot Results

In [4]:
fig = tools.make_subplots(rows=2, cols=1,
                          print_grid=False, 
                          subplot_titles=('BIC score per model',
                                          'Selected GMM: full model, 2 components'))

Plot the BIC scores

In [5]:
for i, (cv_type, color) in enumerate(zip(cv_types, color_iter)):
    xpos = np.array(n_components_range) + .2 * (i - 2)
    trace = go.Bar(x=xpos, y=bic[i * len(n_components_range):
                                  (i + 1) * len(n_components_range)],
                   marker=dict(color=color, line=dict(color='black' , width=1)),
                   name=cv_type)
    fig.append_trace(trace, 1, 1)
    
fig['layout']['yaxis1'].update(range=[bic.min() * 1.01 - .01 * bic.max(), bic.max()],
                               zeroline=False, showgrid=False)

xpos = np.mod(bic.argmin(), len(n_components_range)) + .65 +\
    .2 * np.floor(bic.argmin() / len(n_components_range))
    
fig['layout'].update(annotations=[dict(x=xpos, y=bic.min(),
                                  text='*', yref='yaxis1', xref='xaxis1')],
                     hovermode='closest', height=800)

Plot the winner

In [6]:
Y_ = clf.predict(X)

for i, (mean, cov, color) in enumerate(zip(clf.means_, clf.covariances_,
                                           color_iter)):
    v, w = linalg.eigh(cov)
    if not np.any(Y_ == i):
        continue
    trace = go.Scatter(x=X[Y_ == i, 0], y=X[Y_ == i, 1],
                       mode='markers',
                       showlegend=False,
                       marker=dict(color=color, 
                                   line=dict(color='black' , width=1)))
    fig.append_trace(trace, 2, 1)

    # Plot an ellipse to show the Gaussian component
    v = 2. * np.sqrt(2.) * np.sqrt(v)
    a =  v[1]
    b =  v[0]
    x_origin = mean[0]
    y_origin = mean[1]
    x_ = [ ]
    y_ = [ ]

    for t in range(0,361,10):
        x = a*(math.cos(math.radians(t))) + x_origin
        x_.append(x)
        y = b*(math.sin(math.radians(t))) + y_origin
        y_.append(y)

    elle = go.Scatter(x=x_ , y=y_, mode='lines',
                      showlegend=False,
                      line=dict(color=color, width=2))
    fig.append_trace(elle, 2, 1)
    
fig['layout']['yaxis2'].update(zeroline=False, showgrid=False)
fig['layout']['xaxis2'].update(zeroline=False, showgrid=False)
In [7]:
py.iplot(fig)
Out[7]:
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.