Explanation of the Latent Variable Simulator — What the Flag Grouping and the Shadows on the Stick Compute

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.

1. About this page

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.

2. What the simple view really shows

2.1 Scene A: Can a cloud of points be sorted into groups automatically?

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.

Table 1: Words on the screen in Scene A and the corresponding terms and symbols
Words on the screenTermSymbol or formula
Cloud of points (150 points)Unlabeled datax1, …, xN (N = 150, two-dimensional)
Number of groups (flags)Number of clustersK
FlagRepresentative point (mean) of a clusterμk
Color and shape of a point (flag’s group)Assignmentrnk ∈ {0, 1}
Plant the flagsInitial values (K data points chosen at random)Initial μk
Paint with nearest flag colorAssignment (corresponds to the E step)For the nearest representative point kn*, rnk = 1
Move flags to group centersMean update (corresponds to the M step)μk = mean of the points in cluster k
Total distance to flagsObjective function of k-meansJ = Σ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 repeatedNumber of iterations (assignment → mean update counts as one)—
Placement nInitial-value seedn
Grouping is finishedConvergence (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 the analogy fits and where it does not

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).

2.2 Scene B: In which direction does the cloud of points spread out the most?

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).

Table 2: Words on the screen in Scene B and the corresponding terms and symbols
Words on the screenTermSymbol or formula
Cloud of points (100 points)Two-dimensional data (two measurements)xn = (xn1, xn2)T (N = 100)
Center (×)Sample meanx̄
Stick direction (0° = horizontal, 90° = vertical)Direction of length 1u = (cos φ, sin φ)T, angle φ
Shadow (◆)Projection onto the linex̂n = x̄ + znu, zn = uT(xn − x̄)
Shadow spreadProjected varianceuTSu = (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 variancetr 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 directionDirection of the second principal componentv2, shadow spread λ2
Shadows only, in a row (lower strip)The projected values zn placed on one axiszn
Bracket of the shadow spreadWidth of ±2 × standard deviation from the center (a visual guide)±2√(uTSu)
Vertical scale “× 10”Change of unitx2 → 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 the analogy fits and where it does not

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.

3. How it works

3.1 k-means: alternating assignment and mean update

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.

J=∑n=1N∑k=1Krnk‖xn−μk‖2

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.

rnk={1(k=kn*)0(k≠kn*),kn*=argminj‖xn−μj‖2

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.

μk=∑nrnkxn∑nrnk

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.

3.2 The EM algorithm for a Gaussian mixture: making the coloring a probability

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:

p(x)=∑k=1Kπk𝒩(x∣μk,Σk),γnk=πk𝒩(xn∣μk,Σk)∑jπj𝒩(xn∣μj,Σj)Nk=∑nγnk,μk=1Nk∑nγnkxn,πk=NkNΣk=1Nk∑nγnk(xn−μk)(xn−μk)T(using the new μk)lnp(X∣θ)=∑n=1Nln∑k=1Kπk𝒩(xn∣μk,Σk)

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.

3.3 Principal component analysis: the direction that maximizes the projected variance

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.

zn=uT(xn−x¯),1N∑n=1Nzn2=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).

Su=λu,uTSu=λuTu=λ

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

x^n=x¯+znu,1N∑n=1N‖xn−x^n‖2=trS−uTSu

(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).

S=1N∑n=1N(xn−x¯)(xn−x¯)T,Su=λuX=USsvVT,λi=si2N,tni=viT(xn−x¯)x^n=x¯+∑i=1ktnivi,1N∑n=1N‖xn−x^n‖2=∑i>kλiTwo dimensions: u=(cosφ,sinφ)T,uTSu=S11cos2φ+2S12cosφsinφ+S22sin2φ

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.

3.4 Calculation procedure

  1. A and ①: shuffle the data points with the initial-value seed, and take the first K as the initial representative points (means).
  2. k-means in A and ①: assign each point to its nearest representative point and compute J; if the assignments are the same as last time, stop. If they changed, replace each representative point by the mean of the points in its cluster, compute J, and go back to the assignment. A representative point to which no point is assigned stays where it was. In the EM algorithm for a Gaussian mixture in ①, compute the responsibilities instead of the assignments, and πk, μk, and Σk instead of the mean update.
  3. Territories in A: divide the picture into a grid (64 cells across; 48 when the picture is narrower than 520 px), and lightly paint each cell with the color of the representative point nearest to its center (the same calculation as the pale colors of k-means in ①).
  4. B and ②: take the singular value decomposition of the matrix from which the data mean x̄ has been subtracted, and find λi = si2/N and the direction v1 of the first principal component (and its angle).
  5. B and ②: from the stick angle φ, make u = (cos φ, sin φ)T, and compute uTSu and tr S − uTSu. In B, also compute the shadow positions zn = uT(xn − x̄) and draw them on the stick and in the lower strip.

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).

4. How to use the detailed view

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.”

4.1 Procedure and what to observe

  1. With ① at its defaults (data “Overlapping,” K = 2, Gaussian-mixture EM), press “E step.” What to see: the marker shapes and color depths change, and the readout shows the responsibilities γnk of the representative points A, B, and C. The responsibility of point B, which lies between the two clusters, is between 0 and 1. Each row sums to 1.
  2. Then press “M step.” What to see: the means and ellipses move, and the log-likelihood ln p(X | θ) increases (see the plot below and the before and after values in “Putting the current numbers into the formula”). Check πk = Nk/N numerically.
  3. Press “Run to convergence.” What to see: the log-likelihood never decreases from one iteration to the next, increases, and eventually levels off.
  4. Set the method to “k-means,” choose the data “Elongated,” and press “Run to convergence”; then switch to Gaussian-mixture EM and do the same. What to see: the k-means boundary (the edge between the pale colored regions) is the perpendicular bisector of the two means, and it cuts across the elongated clusters. The Gaussian mixture splits along the clusters by using the orientation of the ellipses. The vertical axis of the lower plot is the objective J for k-means and the log-likelihood for EM, which are different quantities.
  5. With the data “Separated” (K = 3), set the k-means initial-value seed to 8 and press “Run to convergence.” What to see: it stops at a local minimum (J ≈ 411.6) in which one component takes charge of two clusters and one cluster is split between two components. With seed 1, J ≈ 83.45 (dependence on the initial values).
  6. Choose the data “Degenerate example,” turn off “Use variance floor,” and press “Run to convergence.” What to see: component 2 shrinks onto the isolated point at the upper right, the log-likelihood keeps rising, and the run stops with a stated reason once the variance falls below the stopping threshold. When you turn “Use variance floor” back on (the run restarts from the beginning with the same seed), it converges to a finite value. The gray dashed line in the lower plot is the previous trajectory.
  7. In ②, choose “2D point cloud” and move the angle φ. Press “Align to principal axis.” What to see: the angle at which uTSu is largest is the angle of the first principal axis, and there uTSu = λ1 and the reconstruction error = λ2.
  8. Set “Scale factor c for the unit of x2” to 10 or 0.1, and then turn on “Standardize.” What to see: merely changing the unit changes the direction of the principal axis. After standardization the eigenvalues are 1 ± r (r is the correlation coefficient) and no longer depend on the scale factor.
  9. In ②, choose “Spectra.” What to see: with 2 components there are two large eigenvalues, and with 3 components there are three; the rest line up at the height of the top of the noise-level band. The loadings differ in shape from the pure-component spectra and also take negative values. When you change “Number of principal components k used for reconstruction,” the mean reconstruction error matches the sum of the discarded eigenvalues.

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 →.

5. Conditions of the calculation

5.1 Data and random-number conditions

5.2 Conditions fixed in the simple view

5.3 Simplifications

5.4 Conditions under which results become unstable

6. Questions for checking

Questions 1 and 2 can be answered with the simple view alone. Questions 3–6 use the detailed view.

  1. In “What if the flags start in bad places?” in Scene A of the simple view, the grouping stopped at 98 / 31 / 21 points. Why does it not split into the 3 clumps, even though repainting and moving the flags change nothing?
    Sample answer

    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.

  2. In Scene B of the simple view, why does the sum of “Shadow spread” and “Lost in the shadows” not change when the direction of the stick changes? What does this tell us about the widest direction?
    Sample answer

    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.

  1. From the default state you pressed “E step” and “M step” once each. Did the log-likelihood increase? What is π1 + π2 after the M step?
    Sample answer

    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.

  2. Why does k-means fail to split the clusters correctly for the data “Elongated”? Why can the Gaussian mixture split them?
    Sample answer

    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.

  3. Why does the log-likelihood keep rising when the variance floor is not used? Does that mean the model has become “good”?
    Sample answer

    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.

  4. In the 2D mode of ②, how does the angle of the first principal axis change when the scale factor c goes from 1 to 10? What happens with standardization?
    Sample answer

    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.

7. Corresponding sections of the text and references

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).