<jupyter_start><jupyter_text>Plot the confidence ellipsoids of a mixture of two Gaussians obtained with Expectation Maximisation (GaussianMixture class) and Variational Inference (`BayesianGaussianMixture` class models with a Dirichlet process prior).Both models have access to five components with which to fit the data. Note that the Expectation Maximisation model will necessarily use all five components while the Variational Inference model will effectively only use as many as are needed for a good fit. Here we can see that the Expectation Maximisation model splits some components arbitrarily, because it is trying to fit too many components, while the Dirichlet Process model adapts it number of state automatically.This example doesn’t show it, as we’re in a low-dimensional space, but another advantage of the Dirichlet process model is that it can fit full covariance matrices effectively even when there are less examples per cluster than there are dimensions in the data, due to regularization properties of the inference algorithm.  New to Plotly?Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).You can set up Plotly to work in [online](https://plot.ly/python/getting-started/initialization-for-online-plotting) or [offline](https://plot.ly/python/getting-started/initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plot.ly/python/getting-started/start-plotting-online).We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!  Version<jupyter_code>import sklearn
sklearn.__version__<jupyter_output><empty_output><jupyter_text>Imports<jupyter_code>import plotly.plotly as py
import plotly.graph_objs as go

import itertools
import numpy as np
from scipy import linalg
import math

from sklearn import mixture<jupyter_output><empty_output><jupyter_text>Calculations<jupyter_code>color_iter = itertools.cycle(['navy', 'cyan', 'cornflowerblue', 'gold',
                              'orange'])

def plot_results(X, Y_, means, covariances,  title):
    data = []
    for i, (mean, covar, color) in enumerate(zip(
            means, covariances, color_iter)):
        
        v, w = linalg.eigh(covar)
        v = 2. * np.sqrt(2.) * np.sqrt(v)
        u = w[0] / linalg.norm(w[0])
        # as the DP will not use every component it has access to
        # unless it needs it, we shouldn't plot the redundant
        # components.
        if not np.any(Y_ == i):
            continue
        trace = go.Scatter(x=X[Y_ == i, 0], y=X[Y_ == i, 1], 
                           mode='markers',
                           marker=dict(color=color))
        data.append(trace)
        # Plot an ellipse to show the Gaussian component
        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))
        data.append(elle)
       
    layout = go.Layout(title=title, showlegend=False,
                       xaxis=dict(zeroline=False, showgrid=False),
                       yaxis=dict(zeroline=False, showgrid=False),)
    fig = go.Figure(data=data, layout=layout)
    
    return fig
# 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])]<jupyter_output><empty_output><jupyter_text>Gaussian Mixture<jupyter_code># Fit a Gaussian mixture with EM using five components
gmm = mixture.GaussianMixture(n_components=5, covariance_type='full').fit(X)
fig = plot_results(X, gmm.predict(X), gmm.means_, gmm.covariances_,
                   'Gaussian Mixture')
py.iplot(fig)<jupyter_output><empty_output><jupyter_text>Bayesian Gaussian Mixture with a Dirichlet process prior<jupyter_code># Fit a Dirichlet process Gaussian mixture using five components
dpgmm = mixture.BayesianGaussianMixture(n_components=5,
                                        covariance_type='full').fit(X)
fig = plot_results(X, dpgmm.predict(X), dpgmm.means_, dpgmm.covariances_,
                  'Bayesian Gaussian Mixture with a Dirichlet process prior')

py.iplot(fig)
from IPython.display import display, HTML

display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))

! pip install git+https://github.com/plotly/publisher.git --upgrade
import publisher
publisher.publish(
    'Gaussian Mixture Model Ellipsoids.ipynb', 'scikit-learn/plot-gmm/', 'Gaussian Mixture Model Ellipsoids | plotly',
    ' ',
    title = 'Gaussian Mixture Model Ellipsoids | plotly',
    name = 'Gaussian Mixture Model Ellipsoids',
    has_thumbnail='true', thumbnail='thumbnail/gmm.jpg', 
    language='scikit-learn', page_type='example_index',
    display_as='gaussian_mixture', order=2,
    ipynb= '~Diksha_Gabha/3369')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10966379158598838, 'fraction_numerical': 0.010033444816053512, 'mean_word_length': 3.350689127105666, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 7, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '251198', 'license': 'CC-BY-3.0', 'n_tokens_mistral': 1823, 'n_tokens_neox': 1707, 'n_words': 473, 'path': '_posts/scikit/gaussian-mixture-model-ellipsoid/Gaussian Mixture Model Ellipsoids.ipynb', 'repo_name': 'bmb804/documentation', 'size': '5681'}