This page explains what the motion of “planting flags and sorting points into groups” and “the spread of the shadows on a stick” seen in the simulator correspond to in the language of machine learning, and with what formulas they are calculated, in the order words → formulas → calculation procedure. The procedure, the conditions of the calculation, and the questions for checking for the detailed view are also collected here.
▶ Open the simulator (simple view)▶ Open the detailed view
The Latent Variable Simulator is a tool for seeing how to extract the “unseen variables” behind data from data that carry no correct labels (name tags). It covers k-means and the EM algorithm for a Gaussian mixture from Chapter 17 (clustering, mixture distributions, and the EM algorithm), and principal component analysis (PCA) from Chapter 18 (continuous latent variables). The latent variable in Chapter 17 is a discrete variable, “which component (cluster) a point came from,” and the latent variable in Chapter 18 is a continuous variable, “low-dimensional coordinates.”
The simulator has two views.
Scene A does the same calculation as the method “k-means” in ① of the detailed view, and Scene B the same as the “2D point cloud” in ② of the detailed view. We recommend reading in this order: try the simple view, check what it really shows in Section 2, read the formulas in Section 3, and operate the detailed view with the procedure in Section 4.
The motion of Scene A is k-means itself (Section 17.2 of the text). k-means splits N points xn into K groups (clusters). The representative point μk of each cluster is a “flag,” and which cluster a point is put in is “the color and shape of the point.” It alternately repeats “Paint with nearest flag color” (assignment) and “Move flags to group centers” (mean update), and stops when repainting no longer changes the color of any point.
| Words on the screen | Term | Symbol or formula |
|---|---|---|
| Cloud of points (150 points) | Unlabeled data | x1, …, xN (N = 150, two-dimensional) |
| Number of groups (flags) | Number of clusters | K |
| Flag | Representative point (mean) of a cluster | μk |
| Color and shape of a point (flag’s group) | Assignment | rnk ∈ {0, 1} |
| Plant the flags | Initial values (K data points chosen at random) | Initial μk |
| Paint with nearest flag color | Assignment (corresponds to the E step) | For the nearest representative point kn*, rnk = 1 |
| Move flags to group centers | Mean update (corresponds to the M step) | μk = mean of the points in cluster k |
| Total distance to flags | Objective function of k-means | J = ΣnΣk rnk‖xn − μk‖2 |
| Pale color (area nearest to that flag; territory) | Region in which the nearest representative point is the same (the edge between two flags is the perpendicular bisector of the two means) | — |
| Rounds repeated | Number of iterations (assignment → mean update counts as one) | — |
| Placement n | Initial-value seed | n |
| Grouping is finished | Convergence (the assignments no longer change) | — |
“Total distance to flags” adds up, over all points, the square of the distance from each point to its own flag; this value is J. Neither the assignment nor the mean update increases J (Theorem 17.1 of the text), so each time you press the button this number either gets smaller or stays the same. However, there is no guarantee that the place where it stops is the minimum of J (a local optimum).
Numbers in “Try it” (data seed 20261113, 150 points):
Where it fits: the position of a flag is the representative point μk, and the color of a point is the assignment rnk; they are calculated one step at a time with the same function as the method “k-means” in ① of the detailed view (makeRun in latent.model.js). The data “Round clumps” and “Long clumps” are the same as “Separated” and “Elongated” in the detailed view, and placement n gives the same initial values as setting the initial-value seed in the detailed view to n.
Where it does not fit: a real flag is a marker that a person puts down, but the flags here are mean positions determined by calculation. The “distance” is not the distance itself but the sum of squared distances. Also, k-means does not know the “true clumps.” We can say in “Try it” whether the result matches the clumps only because this cloud of points is synthetic data for teaching purposes, generated from chosen clumps. “Near” is measured by the distance when the vertical and horizontal scales of the picture are equal (the Euclidean distance). Changing how the scales are chosen also changes nearness (for the same reason as in the third “Try it” of Scene B).
▶ Simulator (simple view) A: Can a cloud of points be sorted into groups automatically?
Scene B is two-dimensional principal component analysis (PCA) (Section 18.2 of the text). The line through the middle of the cloud (the sample mean x̄) in direction u is the “stick,” and the foot of the perpendicular dropped from each point to that line is its “shadow.” If you search for the direction in which the scatter (variance) of the shadow positions zn is largest, it turns out to be the eigenvector of the covariance matrix S for its largest eigenvalue λ1 (the direction of the first principal component).
| Words on the screen | Term | Symbol or formula |
|---|---|---|
| Cloud of points (100 points) | Two-dimensional data (two measurements) | xn = (xn1, xn2)T (N = 100) |
| Center (×) | Sample mean | x̄ |
| Stick direction (0° = horizontal, 90° = vertical) | Direction of length 1 | u = (cos φ, sin φ)T, angle φ |
| Shadow (◆) | Projection onto the line | x̂n = x̄ + znu, zn = uT(xn − x̄) |
| Shadow spread | Projected variance | uTSu = (1/N)Σn zn2 |
| Lost in the shadows (gray lines joining points and shadows) | Reconstruction error | (1/N)Σn‖xn − x̂n‖2 = tr S − uTSu |
| The two always add up to … (the same in every direction) | Total variance | tr S = λ1 + λ2 |
| Widest direction (green dash-dot line) | Direction of the first principal component (first principal axis) | v1, with shadow spread λ1 |
| Direction at a right angle to the widest direction | Direction of the second principal component | v2, shadow spread λ2 |
| Shadows only, in a row (lower strip) | The projected values zn placed on one axis | zn |
| Bracket of the shadow spread | Width of ±2 × standard deviation from the center (a visual guide) | ±2√(uTSu) |
| Vertical scale “× 10” | Change of unit | x2 → c x2, c = 10 |
The shadow position zn is written tn in the detailed view, but it is the same as zn in Section 18.2.2 of the text. The mean of the shadow positions is 0, so the shadow spread (variance) is the mean of zn2. The line joining a shadow and its point is at a right angle to the stick, so by the Pythagorean theorem, “shadow spread + amount lost in the shadows = total variance” holds in every direction (Section 3.3). Therefore the direction in which the shadows are widest is also the direction that loses the least when points become shadows.
“Search automatically” turns the stick through one full turn (180°) from its current direction, showing the shadow spread, and stops at the widest direction. The direction where it stops is not a value measured while turning; it is the direction of the first principal component found by the PCA calculation (the singular value decomposition of the centered data matrix).
Numbers in “Try it” (data seed 20261113, 100 points):
Where it fits: a shadow is the foot of the perpendicular dropped from each point to the stick (orthogonal projection), the same as the “Projection onto direction u” in ② of the detailed view. The shadow spread and the amount lost are calculated with the same function as in the detailed view (projStats in latent.model.js). The data are the same as the default of the “2D point cloud” in ② of the detailed view (100 points, seed 20261113), and “× 10” is the same transformation as the scale factor c = 10.
Where it does not fit: a real shadow can also stretch at a slant, depending on the direction of the light. The shadows here are only those cast by light shining at a right angle to the stick. Also, the shadow spread is the variance of the shadow positions (the mean of the squares), not the width of the bracket in the picture (±2 × standard deviation) itself.
▶ Simulator (simple view) B: In which direction does the cloud of points spread out the most?
To split data without correct answers into “similar” groups, we must decide what counts as “similar” (here, the Euclidean distance) and what to optimize. k-means minimizes the sum J of the squared distances from each point to the representative point of its own cluster. Optimizing the assignments rnk and the representative points μk at the same time is difficult, so it alternately fixes one and optimizes the other (Section 17.2.1 of the text).
k-means: rnk ∈ {0, 1} indicates whether point n is assigned to component k.
E (assignment): assign each point to the component with the nearest mean. M (update): set μk to the mean of the points assigned to it. Neither half step increases J. The algorithm has converged when the assignments no longer change.
In the assignment (the half step corresponding to E), μk is fixed and each point is put in the cluster of its nearest representative point.
In the mean update (the half step corresponding to M), rnk is fixed and each representative point is set to the mean of the points in its cluster.
In the assignment half step, the term for each point is “the squared distance to the chosen representative point,” and choosing the nearest representative point makes that term smallest. In the mean-update half step, the sum of squares for each cluster is smallest at the mean. Neither increases J, and the number of possible assignments is finite, so the assignments stop changing after a finite number of steps (Theorem 17.1 of the text). However, the place where it stops is “a point where neither changing the assignments nor moving the means lowers J,” which is not necessarily the minimum of J (a local optimum; Section 17.2.4 of the text, Section 17.8). “What if the flags start in bad places?” in Scene A of the simple view is an example of this.
Because points are split by the nearest representative point, the edge between the territories of two representative points is the perpendicular bisector of the two means. k-means is the limit of a Gaussian mixture in which all components have the same covariance matrix εI and ε → 0, and it implicitly assumes that every cluster is a sphere of the same size (Section 17.9 of the text). This is why it cuts across elongated clusters.
In a Gaussian mixture model, we consider an unseen variable (latent variable) that tells which component each point came from, and use Bayes’ theorem to find the probability that component k takes charge of point n (the responsibility), γnk. The responsibility turns the 0-or-1 assignment of k-means into a continuous value from 0 to 1. With the method “Gaussian-mixture EM” in ① of the detailed view, it appears as the color depth of the points.
The EM algorithm for the Gaussian mixture:
The E step computes the responsibilities γnk, and the M step computes πk, μk, and Σk. The responsibilities and the log-likelihood are computed with a log-sum-exp of the values ln πk + ln 𝒩 to avoid overflow. ln 𝒩 is obtained from the Cholesky decomposition of the 2×2 covariance matrix, and no inverse matrix is formed. The log-likelihood never decreases from one iteration to the next (the ELBO and KL decomposition in Section 17.7 of the text).
Variance floor: when “Use variance floor” is on, the eigenvalues of Σk obtained in the M step (call them λ) are replaced by max(λ, c) (the eigenvectors are unchanged). With the mean held fixed, this is the covariance matrix that maximizes the likelihood under the constraint “eigenvalues ≥ c,” so the log-likelihood does not decrease in this case either. When it is off, an update whose smallest eigenvalue falls below 10−10 is not accepted; the run stops and the reason is displayed.
The direction in which a point cloud spreads out the most is the direction of maximum projected variance (Section 18.2 of the text). If we choose a direction u of length 1 and let zn be the length of the projection of the deviation from the mean onto this direction, then the mean of zn is 0, and, using the covariance matrix S, its variance can be written as uTSu.
Under the condition uTu = 1, we maximize uTSu with the method of Lagrange multipliers; the optimal u is then an eigenvector of S, and the projected variance there is the eigenvalue itself (Section 18.2.3 of the text).
The variance is largest for the eigenvector v1 with the largest eigenvalue, and the maximum is λ1. The second principal component is the direction v2 (variance λ2) with the largest projected variance among the directions orthogonal to v1 (Section 18.2.4 of the text). In two dimensions, v2 is the direction at a right angle to v1, where the projected variance is smallest.
The point on the line in direction u nearest to the point xn (the shadow) is x̂n = x̄ + znu, and the residual xn − x̂n is orthogonal to u. Averaging the Pythagorean theorem over all points gives
(Section 18.2.5 of the text). Because tr S does not depend on u, minimizing the reconstruction error is the same as maximizing the projected variance.
PCA: take the singular value decomposition of the matrix X (N rows, D columns) from which the data mean x̄ has been subtracted. Variance is defined with 1/N (the eigenvalues differ by a factor of N/(N − 1) from the convention of dividing by N − 1).
All eigenvalues and loadings are computed from the SVD (one-sided Jacobi method). The covariance matrix S is formed only to show uTSu on the two-dimensional screen.
The calculation in the simple view calls the same functions as the detailed view (makeData, initParams, makeRun, kmeansAssign, makePCA2D, transform2D, pca, cov2, projStats, and axisAngle in latent.model.js). The only calculations added for the simple view are the summary when run to the end, the territory grid, the breakdown by clump, the shadow positions, the amount to turn the stick through one full turn, and the rounding of numbers (latent.easy.js).
The detailed view has two tabs: ① (k-means and EM) and ② (PCA). ① has a scatter plot, the trajectory of the log-likelihood (or J), and the “Putting the current numbers into the formula” box on the left, and the controls, readout, and three representative points on the right. In ②, the buttons at the top switch between “2D point cloud” and “Spectra.”
▶ Simulator (detailed view) ①: k-means and EM▶ Simulator (detailed view) ②: PCA
With the keyboard, Tab moves to buttons and sliders, Enter (or Space) presses a button, and the arrow keys move a slider. The tabs can be switched with ← and →.
Questions 1 and 2 can be answered with the simple view alone. Questions 3–6 use the detailed view.
Each of the two steps only minimizes with the other side held fixed. The flag in charge of two clumps sits between them, and the nearest flag for each point does not change. Moving one flag all at once to a distant clump would lower the total distance to the flags (J) a lot, but such a large move does not arise from either of the two steps. This is a local optimum. In practice, you start over with different placements and take the result with the smallest total distance.
The line dropped from each point to its shadow is at a right angle to the stick, so the squared distance between the point and the center is the sum of the square of the shadow position and the squared distance between the point and its shadow (the Pythagorean theorem). Averaged over all points, the left-hand side is the total variance tr S, which does not depend on the direction (here 1.79), so the amount lost decreases by exactly as much as the shadow spread increases. Therefore the direction in which the shadows are widest (36°) is also the direction that loses the least when points become shadows.
The log-likelihood increases from −483.67 to −410.19 (default data of 150 points, data seed 20261113, initial-value seed 1). Since πk = Nk/N and the responsibilities of each point sum to 1, ΣkNk = N, and therefore π1 + π2 = 1.
k-means assigns each point to the nearest mean (in Euclidean distance), so the boundary is the perpendicular bisector (a straight line) of the two means, and it implicitly assumes that every component is a round cluster of the same size. For an elongated cluster, a far-away point along the cluster’s direction ends up closer to the mean of the neighboring cluster. The Gaussian mixture measures the Mahalanobis distance with the covariance matrix of each component, so it can represent the orientation and elongation of a cluster.
If you place a mean at a single point xn and let the variance σ2 approach 0, the density at that point, 𝒩(xn | xn, σ2I) = 1/(2πσ2), grows without bound, while the other points are explained by another component, so the log-likelihood has no upper limit. This does not represent the structure of the data; it is a pathological solution of maximum likelihood estimation. It is prevented by a variance floor, regularization, or MAP estimation. The smaller the floor c, the larger the log-likelihood at convergence.
For the default data (100 points, seed 20261113), the angle is about 36.0° for c = 1, about 85.0° for c = 10 (nearly the direction of x2), and about 3.2° for c = 0.1 (nearly the direction of x1). This is because the variance of x2 is multiplied by c2 and dominates the total variance. Standardization turns the analysis into PCA of the correlation matrix; in two dimensions the principal axis is always 45° or 135°, the eigenvalues are 1 ± r (here r = 0.697, so 1.697 and 0.303), and they do not depend on the scale factor c. Because the result depends on the choice of units, consider standardization for quantities whose units are not comparable.
References (from the ends of Chapters 17 and 18):
Back to the Latent Variable Simulator | Machine Learning — From Probability to GPT (Contents) | Equations are typeset with the browser’s built-in MathML (no external library).