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 p0gray = \text 666white = \text fffWe'll create three normal distributions with different means, all having the same variance, and different weights:
x = \scalar 0mus = \array 0 -2 1sigmas = \array 0.6 0.6 0.6weights = \array 0.7 0.2 0.1The 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%.
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 densitiesThis creates three plots (plot1, plot2, plot3) showing the individual Gaussian curves. Let's color them gray:
plots = \array plot1 plot2 plot3\set-stroke plots grayNow we'll combine the three distributions using their weights to get the mixture density:
weighted-densities = \mul densities weightsy = \reduce-sum weighted-densitiesThe 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 yThis creates plot3, which shows the combined Gaussian mixture distribution.
\point x 0\point x y\line p1 p2\set-stroke line0 whiteThis creates a vertical line from the x-axis to the mixture curve, showing the density value at the current x.
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 whiteThe tangent line shows the slope of the mixture distribution at the current x value.
Try changing x to see how the mapping and tangent update:
x = \scalar -1