Reading history

Gaussian Mixture Models in Python: Soft Clustering with scikit-learn

6 min read 0 views

Learn Gaussian mixture models in Python: soft clustering with GaussianMixture, comparison with K-Means, choosing components with BIC, and flagging unusual values.

K-Means gives each point to exactly one cluster and assumes clusters are round blobs of similar size. Real groups are often stretched, tilted or overlapping. A Gaussian Mixture Model (GMM) describes the data as a blend of bell-shaped groups, each with its own shape and size. It also gives soft answers: the probability that a point belongs to each group.

In this lesson you will learn

  • How a Gaussian mixture differs from K-Means
  • Fitting GaussianMixture and reading means, weights and probabilities
  • Choosing the number of groups with BIC
  • Using a fitted mixture to flag unusual values

You should know K-Means clustering. DBSCAN and hierarchical clustering are useful to compare.

The Idea

Imagine the data was made by first picking a group at random and then drawing a point from that group’s bell curve. Each group, called a component, has three things:

  • a mean: its centre,
  • a covariance: its spread, which can be stretched and tilted in any direction,
  • a weight: the share of all points that come from it.

The model learns all three with an algorithm called expectation-maximization (EM). It alternates between two steps: work out each point’s probability of belonging to each group, then update each group’s mean, spread and weight from those probabilities. It repeats until the numbers stop changing.

GMM Versus K-Means on Stretched Data

Here there are two groups of shoppers: a tight round group and a long, tilted group.

import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture

# Two groups of shoppers: a tight round group and a long stretched group
rng = np.random.default_rng(5)
a = rng.normal([2, 2], [0.4, 0.4], size=(150, 2))
b = rng.multivariate_normal([5, 4], [[3.0, 2.6], [2.6, 3.0]], size=150)
X = np.vstack([a, b])
truth = np.array([0] * 150 + [1] * 150)

def agreement(labels):
    same = (labels == truth).mean()
    return max(same, 1 - same)          # cluster numbers may be swapped

km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
gm = GaussianMixture(n_components=2, covariance_type="full", random_state=0).fit(X)
print("K-Means agreement with truth:", round(agreement(km.labels_), 3))
print("GMM agreement with truth    :", round(agreement(gm.predict(X)), 3))

points = np.array([[2.0, 2.0], [2.8, 2.5], [7.0, 6.0]])
print("Component means:", gm.means_.round(2).tolist())
print("Membership probabilities:")
print(gm.predict_proba(points).round(3))
print("Mixing weights:", gm.weights_.round(3))

Output

K-Means agreement with truth: 0.843
GMM agreement with truth    : 0.957
Component means: [[5.11, 4.08], [1.97, 1.97]]
Membership probabilities:
[[0.015 0.985]
 [0.496 0.504]
 [1.    0.   ]]
Mixing weights: [0.491 0.509]
  • K-Means matches the true groups for 84.3% of points. It cuts the space with a straight line halfway between two centres, so it slices off the end of the stretched group nearest the round one.
  • The GMM matches 95.7%, because covariance_type="full" lets each component take its own tilted oval shape.
  • The component numbers are arbitrary. Here component 0 is the stretched group (mean near 5, 4) and component 1 is the round group (mean near 2, 2).
  • predict_proba gives soft memberships. The point (2, 2) is 98.5% round group. The point (2.8, 2.5) sits between the groups, at almost 50/50, and K-Means would hide that doubt. The point (7, 6) clearly belongs to the stretched group.
  • The weights show the groups are about equal in size, matching the 150 + 150 points we created.

How Many Components? Use BIC

A mixture with more components always fits the training data better, so you cannot pick the number by fit alone. The Bayesian Information Criterion (BIC) rewards good fit but adds a penalty for every extra parameter. Lower BIC is better.

import numpy as np
from sklearn.mixture import GaussianMixture

# Daily water use (litres) from three kinds of homes, mixed together
rng = np.random.default_rng(8)
use = np.concatenate([rng.normal(120, 15, 300),     # small flats
                      rng.normal(260, 30, 200),     # family homes
                      rng.normal(480, 40, 100)])    # large houses
X = use.reshape(-1, 1)

print(" k      BIC")
for k in range(1, 6):
    gm = GaussianMixture(n_components=k, random_state=0).fit(X)
    print(f"{k:2} {gm.bic(X):8.1f}")

best = GaussianMixture(n_components=3, random_state=0).fit(X)
order = best.means_.ravel().argsort()
print("Means  :", best.means_.ravel()[order].round(1))
print("Spreads:", np.sqrt(best.covariances_.ravel()[order]).round(1))
print("Weights:", best.weights_[order].round(3))

# Unusual days: very low likelihood under the fitted mixture
scores = best.score_samples(np.array([[125], [370], [900]]))
print("Log-likelihood of 125, 370, 900 litres:", scores.round(2))

Output

 k      BIC
 1   7569.8
 2   7284.8
 3   6694.8
 4   6716.3
 5   6733.1
Means  : [120.  260.8 477.6]
Spreads: [15.6 29.1 39.4]
Weights: [0.5   0.333 0.167]
Log-likelihood of 125, 370, 900 litres: [ -4.36  -9.8  -63.88]
  • BIC falls sharply up to 3 components and then rises again. Three is the best choice, and it matches the three kinds of homes we mixed together.
  • The fitted means (120, 261, 478 litres), spreads and weights (50%, 33%, 17%) are close to the values used to create the data.
  • score_samples returns the log-likelihood: how plausible a value is under the fitted mixture. 125 litres is very typical (−4.36). 370 litres falls in the gap between two groups (−9.8). 900 litres is extremely unlikely (−63.88), so it is a strong candidate for a leak or a meter error.

Covariance Types

covariance_typeShape of each componentWhen to use
"full" (default)Any tilted oval, different for each componentMost flexible; needs enough data
"tied"All components share one oval shapeGroups look alike but sit in different places
"diag"Ovals lined up with the axesMany features; faster and more stable
"spherical"Circles, each with its own sizeClosest to K-Means

Common Mistakes

  1. Forgetting to scale features when they use very different units, unless you use "full" covariance, which can adapt to them.
  2. Trusting a single run. EM can settle on a poor answer. Set n_init=5 or more to try several starts and keep the best.
  3. Choosing the number of components by eye when BIC can guide you.
  4. Reading component numbers as meaningful. Component 0 in one run may be component 2 in the next. Identify groups by their means.

Practice Exercises

Exercise 1. In gmm2.py, list the water-use values among 100, 200, 300, 400 and 600 litres whose most likely component is the family-home group.

Show answer
vals = np.array([[100], [200], [300], [400], [600]])
family = order[1]                       # middle mean = family homes
print(vals[best.predict(vals) == family].ravel())
# [200 300]

Exercise 2. Flag the 1% least likely days in X from gmm2.py as unusual.

Show answer
s = best.score_samples(X)
cut = np.percentile(s, 1)
print("Unusual days:", X[s < cut].ravel().round())

Frequently Asked Questions

Is a GMM always better than K-Means?

No. K-Means is faster and simpler, and works well when groups are round and similar in size. A GMM is worth it when groups are stretched or overlapping, or when you need membership probabilities.

What is the difference between BIC and AIC?

Both balance fit against complexity. BIC’s penalty grows with the number of rows, so it favours fewer components on large datasets. AIC’s penalty is smaller and can pick more components. GaussianMixture has both bic() and aic().

Can a GMM generate new data?

Yes. gm.sample(100) draws 100 new points from the fitted mixture, which is handy for testing or simulation.

Summary

  • A GMM models data as a weighted blend of bell-shaped groups.
  • It gives soft memberships with predict_proba.
  • covariance_type="full" handles stretched, tilted groups.
  • Pick the number of components with the lowest BIC.
  • score_samples flags values that fit no group well.

Next: Build a Recommender System in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *