Loading editor...

This extension is required for this article. Load it here if you haven't yet.

This example demonstrates a Gaussian Mixture Model (GMM) visualization. We'll create three normal distributions with different means, combine them with weights, and plot the resulting mixture distribution.

First, let's set up the canvas with appropriate scale and colors:

  • : unit = \scalar 150
  • : \hide p0
  • : gray = \text 666
  • : white = \text fff

Define the Gaussian mixture components

We'll create three normal distributions with different means, all having the same variance, and different weights:

  • : x = \scalar 0
  • : mus = \array 0 -2 1
  • : sigmas = \array 0.6 0.6 0.6
  • : weights = \array 0.7 0.2 0.1

The means are at positions 0, -2, and 1. The weights indicate that the first distribution (at 0) contributes 70% to the mixture, the second (at -2) contributes 20%, and the third (at 1) contributes 10%.


Plot individual PDF curves

Let's calculate and plot each normal distribution's probability density function (PDF) at the current x value:

  • : densities = \prob-normal-pdf x mus sigmas
  • : \plot x densities

This creates three plots (plot1, plot2, plot3) showing the individual Gaussian curves. Let's color them gray:

  • : plots = \array plot1 plot2 plot3
  • : \set-stroke plots gray

Calculate and plot the weighted mixture

Now we'll combine the three distributions using their weights to get the mixture density:

  • : weighted-densities = \mul densities weights
  • : y = \reduce-sum weighted-densities

The weighted sum gives us the contribution of each distribution at point x, and reducing the sum gives us the final mixture density value y.

  • : \plot x y

This creates plot3, which shows the combined Gaussian mixture distribution.

Visualize the mapping

  • : \point x 0
  • : \point x y
  • : \line p1 p2
  • : \set-stroke line0 white

This creates a vertical line from the x-axis to the mixture curve, showing the density value at the current x.


Draw the tangent line

We can also draw the tangent line to the mixture curve at the current point:

  • : \tangent plot3 x 1
  • : \hide p3 p4
  • : \set-stroke line1 white

The tangent line shows the slope of the mixture distribution at the current x value.

Change the x value

Try changing x to see how the mapping and tangent update:

  • : x = \scalar -1