from sklearn.mixture import GaussianMixture
GMM = GaussianMixture(n_components = 2, init_params = 'random')
GMM.fit(X)
print('Converged:', GMM.converged_) # check if the model has converged
Y = np.array([[105.0]])
prediction = GMM.predict_proba(Y)
print('Probability each Gaussian (state) in the model given each sample p = {}'.format(prediction))
print()
yhat = GMM.predict(X)
print(yhat[:100])
print(yhat[-100:])
from sklearn.datasets.samples_generator import make_blobs
from scipy.stats import multivariate_normal
X, Y = make_blobs(cluster_std=1.0, random_state=123, n_samples=12000, centers=3)
X = np.dot(X, np.random.RandomState(0).randn(2,2))
x, y = np.meshgrid(np.sort(X[:,0]), np.sort(X[:,1]))
XY = np.array([x.flatten(), y.flatten()]).T
GMM = GaussianMixture(n_components=3).fit(X) # instantiate and fit the model
print('Converged:', GMM.converged_) # check if the model has converged
means = GMM.means_
covariances = GMM.covariances_
Y = np.array([[0.5], [0.5]])
prediction = GMM.predict_proba(Y.T)
print('Probability each Gaussian (state) in the model given each sample p = {}'.format(prediction))
fig = plt.figure(figsize = (12,12), dpi = 100)
ax0 = fig.add_subplot(111)
ax0.scatter(X[:,0], X[:,1])
ax0.scatter(Y[0,:], Y[1,:], c = 'orange', zorder = 10, s = 100)
for m,c in zip(means,covariances):
multi_normal = multivariate_normal(mean = m, cov = c)
ax0.contour(np.sort(X[:,0]), np.sort(X[:,1]), multi_normal.pdf(XY).reshape(len(X), len(X)), colors='black', alpha=0.3)
ax0.scatter(m[0], m[1], c = 'grey', zorder = 10, s = 100)
plt.show()
fig.savefig('2d.jpeg')