Skip to content

Instantly share code, notes, and snippets.

@accessnash
Created November 22, 2020 17:04
Show Gist options
  • Save accessnash/7b8813882396880fb667a8cdc836a3ab to your computer and use it in GitHub Desktop.
Save accessnash/7b8813882396880fb667a8cdc836a3ab to your computer and use it in GitHub Desktop.
Example of fitting a Gaussian mixture model with EM algorithm
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 17:53:58 2020
@author: Localuser
"""
# Fitting a GMM with EM algorithm
import numpy as np
from sklearn.mixture import GaussianMixture
# generate a sample
X1 = np.random.normal(loc=20, scale=5, size=4000)
X2 = np.random.normal(loc=40, scale=5, size=6000)
X = np.hstack((X1, X2))
# reshape into a table with one column
X = X.reshape((len(X), 1))
# fit model
model = GaussianMixture(n_components=2, init_params='random')
model.fit(X)
# predict latent values
yhat = model.predict(X)
# check latent value for first few points
print(yhat[:100])
# check latent value for last few points
print(yhat[-100:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment