Lesson 7 of 9
Gaussian Mixture Models (GMM) & Soft Probabilistic Clustering via Expectation-Maximization
Gaussian Mixture Models (GMM) are probabilistic generative models that assume data is generated from a mixture of K Gaussian distributions with unknown parameters: P(x) = sum(pi_k * N(x | mu_k, Sigma_k)). Unlike K-Means (which performs hard assignment to spherical clusters), GMMs assign soft posterior probabilities P(cluster_k | x) and can fit elliptical, rotated clusters with arbitrary covariance structures (full, tied, diagonal, spherical) via the Expectation-Maximization (EM) algorithm.
GMM Soft Clustering & Covariance Type Benchmark
import numpy as np
import pandas as pd
from sklearn.mixture import GaussianMixture
from sklearn.datasets import make_blobs
# Generate elliptical, correlated clusters
np.random.seed(42)
X, _ = make_blobs(n_samples=500, centers=3, n_features=2, random_state=42)
# Stretch and rotate data to induce non-spherical covariance
transformation = [[0.6, -0.6], [-0.4, 0.8]]
X_elliptical = np.dot(X, transformation)
# Fit Gaussian Mixture Model with Full Covariance
# covariance_type='full': each cluster has its own unconstrained covariance matrix
gmm = GaussianMixture(n_components=3, covariance_type='full', random_state=42)
gmm.fit(X_elliptical)
# SOFT CLUSTERING: Compute posterior probability matrix
soft_probabilities = gmm.predict_proba(X_elliptical)
hard_clusters = gmm.predict(X_elliptical)
print("=== GAUSSIAN MIXTURE MODEL PROBABILISTIC ASSIGNMENTS ===")
print(f"EM Algorithm Converged : {gmm.converged_} in {gmm.n_iter_} iterations")
print(f"BIC Score (Model Selection): {gmm.bic(X_elliptical):.1f} (lower is better)")
print(f"AIC Score (Model Selection): {gmm.aic(X_elliptical):.1f}")
print("\nSample Soft Probability Distributions (First 3 Samples):")
for idx, probs in enumerate(soft_probabilities[:3]):
print(f"Sample #{idx}: Cluster Probabilities = {probs.round(3)} -> Assigned: Cluster {hard_clusters[idx]}")Pro Tip: Model Selection with BIC and AIC
You can find the optimal number of components K and covariance structure in a GMM by minimizing the Bayesian Information Criterion (BIC): `BIC = -2 ln(L) + k ln(n)`. BIC penalizes model complexity heavily, preventing overfitting.
MlGaussianMixtureModels Visual Representation
Hands-On Challenge: Anomaly Detection via GMM Density Thresholding
Use `gmm.score_samples(X)` to compute the log-likelihood of each sample under the fitted mixture model. Flag points with log-likelihood in the lowest 1st percentile as anomalies.
Quick Quiz & Key Concept Checks
Common Pitfall: Sensitivity to Initialization in GMM
The EM algorithm is guaranteed to converge to a local optimum, which may not be the global maximum likelihood. Run GMM with `n_init=10` to initialize from multiple K-Means seeds.