Gaussian Mixture Model Ellipsoids in Scikit-learn

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.

color_iter=itertools.cycle(['navy','cyan','cornflowerblue','gold','orange'])defplot_results(X,Y_,means,covariances,title):data=[]fori,(mean,covar,color)inenumerate(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.ifnotnp.any(Y_==i):continuetrace=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 componenta=v[1]b=v[0]x_origin=mean[0]y_origin=mean[1]x_=[]y_=[]fortinrange(0,361,10):x=a*(math.cos(math.radians(t)))+x_originx_.append(x)y=b*(math.sin(math.radians(t)))+y_originy_.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)returnfig

In [4]:

# Number of samples per componentn_samples=500# Generate random sample, two componentsnp.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])]

# Fit a Gaussian mixture with EM using five componentsgmm=mixture.GaussianMixture(n_components=5,covariance_type='full').fit(X)fig=plot_results(X,gmm.predict(X),gmm.means_,gmm.covariances_,'Gaussian Mixture')