Introduction to Machine Learning · Tuesday, October 27

Unsupervised Learning
Solving Session

PCA and the SVD, Gaussian mixtures and EM, autoencoders, t-SNE and UMAP, hierarchical clustering.

In pairs, signed in, scored live. The teaching assistants run the room today. Answers close at 12:20 pm.

InstructionsRead these carefully, together, before you start

  1. Sign in (top right). One screen per pair is fine: one of you signs in.
  2. Make your team at the top of Problem 1: a team name and your full names. You can use a second laptop by signing in and joining the team with your four-letter code, shown in the team line at the top of every problem.
  3. Each problem: think, type, Check. A right answer earns the part's points, less 1 for every wrong try before it (a part never goes below zero); on a multiple choice a wrong letter costs a third of the part. Each part allows 4 tries.
  4. The slide after a problem explains it. It opens when the problem is done: every part answered, or out of tries. The worked solution, with the numbers, then appears under the problem itself.
  5. Ask the AI tutor about anything you do not understand, on any slide: the next slide explains how.
Time limitAnswers close at 12:20 pm: after that, no problem accepts answers, hints or questions. Each problem shows the time left. A plan: Part 1 by 11:25, Part 2 by 12:00, Parts 3 and 4 by 12:20.
No other AIDo not use ChatGPT, Claude, Gemini or any other AI tool outside these slides. The tutor in the slides is the only AI you may use, and every question to it is recorded.
Fair playWork with your partner, not with the next table. The other slides are yours to use: go back to any of them.

Ask the AI tutorYou are allowed, and expected, to ask it about any concept on any slide

  1. Open the chat with the speech-bubble button at the top right of any slide, or press the A key. The panel is called "Ask about this slide", and the tutor sees the slide you are on.
  2. Ask about ideas, in your own words. For example: "What does \(P(z = j \mid x)\) mean?", "Why is the first principal direction an eigenvector?", "What is a latent variable?"
  3. On a problem, the tutor explains the idea and the method, but it will not give an answer or tell you whether yours is right: that is what Check is for. The "Ask a question" button under a problem works the same way.
What it costsYour team's first question to the tutor is free. Each question after it costs your team 1 point; the panel shows how many you have used. A question with the button under a problem costs 1 point on that problem. Every question is recorded with your team.
When to askWhen a word, a symbol or a step on a slide is not clear to either of you. A point spent on understanding a slide usually earns more than one back on the next problem. You can also take a hint under a problem (1 point), or move on and come back: each problem is scored separately.

Four partsSlides to read and try out, with a problem after most of them

    The full decks, to read alongside: PCA and the SVD (Part 1), Gaussian mixtures and EM (Part 2), autoencoders, t-SNE, UMAP and clustering (Parts 3 and 4). Each opens in a new tab.

    Part 1 of 4

    PCA and the SVD

    How do we find the directions, and how many numbers does a point need?

    The full deck: PCA and the SVD

    A recap of last lecture: PCA in four stepsPrincipal component analysis of a data matrix \(X\) with \(n\) rows (one per example) and \(d\) columns (one per feature)

    1. Center every feature: subtract its mean \(\mu_j\), so every column of \(X\) has mean 0.
    2. Compute the covariance matrix \(\Sigma = \frac{1}{n} X^\top X\) of the centered data. Its eigenvectors \(v_j\) are the principal directions, and each eigenvalue \(\lambda_j\) is the variance of the data along \(v_j\), numbered from the largest: \(\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d\).
    3. Keep \(k\) directions: a point \(x\), in its original units, has \(k\) coordinates \(z = V_k^\top (x - \mu)\) and the reconstruction \(\hat x = \mu + V_k z\). Here \(V_k\) is the \(d \times k\) matrix with the first \(k\) directions as its columns.
    4. Measure what is kept: the share of the variance kept by \(k\) directions is \((\lambda_1 + \dots + \lambda_k) / (\lambda_1 + \dots + \lambda_d)\).

    The next slide is the interactive picture behind steps 2 and 4. Problem 1 comes right after it.

    What's the major axis of variation?Drag in the plot or use the slider to turn the line. Every day drops onto it (green), along the red dashes.

    variance of the projections mean squared distance to the line their sum, at every angle
    \[\|x^{(i)}\|^2 = (\text{length along the line})^2 + (\text{distance to the line})^2\]

    Each point is one day: the temperatures of Beirut and Damascus, centered. Pythagoras holds for every day (for a unit vector \(v\), the length along the line is \(v^\top x\)). Averaged over the days, the left side is fixed, 103.8 °C² (the total variance), so the line with the most variance along it is the line with the smallest mean squared distance to it. Along \(v_1\) that mean squared distance is 1.7 °C²: a typical distance of 1.3 °C, its square root.

    Problem 1: Three questions on the recapMultiple choice: a wrong letter costs a third of the part

    What you are given

    From the previous slideTurn the line and watch the two bars: the green one is the variance of the projections onto the line, the red one the mean squared distance from the points to the line.
    \[\Sigma v = \lambda v, \qquad \lambda = v^\top \Sigma v\]

    For a unit vector \(v\), \(\lambda = v^\top \Sigma v\) is the variance of the data along \(v\).

    To think about for (c)Temperatures near 20 degrees are far from 0. What does \(\frac{1}{n}X^\top X\) contain when the mean was not subtracted first?

    What you are asked

    (a) Which vector is the first principal direction \(v_1\)?
    (b) On the previous slide, as you turn the line, what can you say about the variance of the projections plus the mean squared distance to the line?
    (c) Suppose you forget to center the data, and compute the top eigenvector of \(\frac{1}{n}X^\top X\) anyway. What is the most likely result?

    Problem 1, the reasoningOne right triangle for every point

    (a) the largest eigenvalue\(\lambda = v^\top \Sigma v\) is the variance of the data along the unit vector \(v\). So the eigenvector with the largest eigenvalue keeps the most variance: it is \(v_1\).
    (b) a fixed totalFor a centered point \(x\) and a unit vector \(v\): \(\lVert x\rVert^2 = (v^\top x)^2 + d^2\), where \(d\) is the distance from \(x\) to the line (Pythagoras). Averaged over the data: total variance = variance kept + mean squared distance, at every angle. So the line that keeps the most variance is also the line closest to the data.
    (c) center firstWrite each point as \(x = \mu + (x - \mu)\) and average \(x x^\top\): the cross terms average to zero, so \(\frac{1}{n}X^\top X = \Sigma + \mu\mu^\top\), where \(\mu\mu^\top\) (a column times a row) is a \(d \times d\) matrix. Its only nonzero eigenvalue is \(\lVert\mu\rVert^2\), along the direction of \(\mu\). When the data sit far from the origin, that term dominates, and the top eigenvector points at the mean instead of along the spread. The matrix is still symmetric, so its eigenvectors stay orthogonal and its eigenvalues stay \(\ge 0\).

    The singular value decomposition of \(X\)The same directions \(V\), computed from the data matrix \(X\) directly, without forming the covariance matrix \(\Sigma\). Pick a form; in the truncated form, \(k\) sets how much is kept (highlighted).

    \[X = U\,\Xi\,V^\top = \sum_{j=1}^{d} \sigma_j\, u_j v_j^\top\]

    \(U^\top U = I\) and \(V^\top V = I\): orthonormal columns

    \(\Xi\) (capital xi) holds the singular values \(\sigma_1 \ge \sigma_2 \ge \dots\) on its diagonal. The next slide reads each piece of the formula.

    Reading the SVD, piece by piece\(X = U\,\Xi\,V^\top\) for a centered data matrix \(X\) with \(n\) rows (examples) and \(d\) columns (features)

    \(\Xi\), capital xiA diagonal matrix of the singular values \(\sigma_1 \ge \sigma_2 \ge \dots \ge 0\). Most books call it \(\Sigma\); here \(\Sigma\) is already the covariance matrix, so the singular values get their own letter.
    \(V\)A \(d \times d\) matrix with orthonormal columns \(v_1, \dots, v_d\): the principal directions. numpy returns \(V^\top\) (as Vt), so \(v_1\) is the first row of Vt, Vt[0]. In the code, Xc is the centered \(X\).
    \(Z = XV = U\,\Xi\)Row \(i\) of \(Z\) holds the coordinates of point \(i\) along every direction: the same numbers as \(z = V^\top x\) in the recap, written as a row. Keeping the first \(k\) columns of \(Z\) keeps \(k\) numbers per point.
    \(\sigma_j\, u_j v_j^\top\)A column \(u_j\) (\(n\) numbers) times a row \(v_j^\top\) (\(d\) numbers) is an \(n \times d\) matrix whose rows are all multiples of \(v_j\). The SVD writes \(X\) as a sum of \(d\) such pieces, largest first; a truncation keeps the first \(k\).

    Why the SVD gives the principal componentsPut the SVD into the covariance matrix, one step at a time

    1Use \(X = U\Xi V^\top\) and \(U^\top U = I\): \(\displaystyle \Sigma = \tfrac{1}{n} X^\top X = \tfrac{1}{n} V\,\Xi^\top U^\top U\,\Xi\, V^\top = V \Big(\tfrac{1}{n}\Xi^\top \Xi\Big) V^\top\) 2\(\Xi^\top\Xi\) is diagonal with entries \(\sigma_j^2\): this is the eigendecomposition \(\Sigma = V \Lambda V^\top\) of last lecture, where \(\Lambda\) is the diagonal matrix of the eigenvalues \(\lambda_j\). So each column of \(V\) is an eigenvector of \(\Sigma\): \(\displaystyle \Sigma\, v_j = \frac{\sigma_j^2}{n}\, v_j, \qquad \lambda_j = \frac{\sigma_j^2}{n}\) 3And the numbers kept are the columns of \(U\), scaled: \(\displaystyle Z = X V = U\,\Xi\,V^\top V = U\,\Xi, \qquad z_j^{(i)} = \sigma_j\, u_{ij}\)

    For the weather of 22 cities over 5,844 days, \(\sigma_1 = \) 2366, so \(\lambda_1 = \sigma_1^2/n = \) 957.8 °C², the largest eigenvalue. Forming \(X^\top X\) first loses digits of accuracy on a computer; the SVD works on \(X\) itself, which is why it is the standard route (Brunton and Kutz, 2022).

    Problem 2: Counting the numbers in an SVDFind the shape of each matrix first: every count follows from the shapes

    What you are given

    X500 × 40=U? × ?Ξ40 × 40Vᵀ? × ?
    The dataA centered data matrix \(X\) with \(n = 500\) rows (one per example) and \(d = 40\) columns (one per feature); its rank is 40. Its economy SVD is \(X = U\,\Xi\,V^\top\), where \(U\) keeps one column per singular value.
    A rank-\(k\) truncation keepsthe first \(k\) columns of \(U\), the first \(k\) singular values (stored as \(k\) numbers, not as a \(k \times k\) matrix), and the first \(k\) columns of \(V\).

    What you are asked

    (a) How many rows does \(U\) have?
    (b) In the economy form, how many columns does \(U\) have?
    (c) How many numbers (entries) does \(V\) have in total?
    (d) How many numbers do you need to store for the rank-5 truncation?
    (e) What fraction of the 20,000 entries of \(X\) is your answer to (d)? Give a decimal, such as 0.25 (a percentage also works).

    Problem 2, the reasoningHow much a rank-k approximation stores

    (a) to (c) the shapes\(X\) is \(n \times d\) = 500 by 40. In the economy SVD, \(U\) is 500 by 40 (one row per example, one column per singular value), \(\Xi\) is 40 by 40 and diagonal, and \(V\) is 40 by 40 (one row per feature): 1,600 entries.
    (d) and (e) rank 5\(n k + k + d k\) = 500 × 5 + 5 + 40 × 5 = 2,705 numbers instead of \(n d\) = 20,000: a fraction 0.135, or 13.5%.
    Why this saves spaceThe cost of a rank-\(k\) approximation grows like \(k(n + d)\), not \(n d\). For the 20,000 digits of the next slides, 256 pixels each, 30 components need 30 × (20,000 + 256) + 30 = 607,710 numbers: a fraction 0.12, or 12%, of the 5,120,000 pixels.

    Truncation in code, and why it is the best rank-\(k\) approximationCode: the error of the rank-\(k\) reconstruction is the sum of the squared singular values it dropped

    import numpy as np, pandas as pd
    df = pd.read_csv('levant_era5_daily_mean_temp_2010_2025.csv')
    Xc = df.drop(columns='date').to_numpy(); Xc = Xc - Xc.mean(axis=0)   # 5844 by 22, centred
    U, s, Vt = np.linalg.svd(Xc, full_matrices=False)   # economy: U is 5844 by 22, s has 22 values, Vt is 22 by 22
    for k in [1, 2, 3, 22]:
        Xk = (U[:, :k] * s[:k]) @ Vt[:k]                # k columns of U, k singular values, k rows of Vt
        print(k, round(((Xc - Xk)**2).sum()), round((s[k:]**2).sum()))   # the two numbers agree
    

    Eckart and Young (1936): among all matrices of rank \(k\), \(X_k = U_k \Xi_k V_k^\top\) is the closest to \(X\) in squared error, and the error left is \(\|X - X_k\|_F^2 = \sum_{j > k} \sigma_j^2\), where \(\|\cdot\|_F^2\) (F for Frobenius) is the sum of the squares of all entries. The PCA reconstruction with \(k\) components is exactly \(X_k\); dividing by \(n\) turns the dropped \(\sigma_j^2\) into the dropped eigenvalues. In the code, U[:, :k] * s[:k] multiplies column \(j\) of \(U\) by \(\sigma_j\): it is \(U_k \Xi_k\) without building the diagonal matrix. The three forms, in the shape of \(U\): full \(n \times n\), economy \(n \times d\) (full_matrices=False), truncated \(n \times k\).

    The SVD of a dataset of digitsEach row of \(X\) is one 16 by 16 picture of a digit, read as 256 numbers

    \(n \times d\)
    \(x^{(1)\top}\)\(x^{(2)\top}\)\(x^{(3)\top}\)\(\vdots\)
    \(X\)
    \(=\)
    \(n \times d\)
    \(u_1\)\(u_2\)\(\cdots\)
    \(U\)
    \(d \times d\)
    \(\sigma_1\)\(\sigma_2\)\(\ddots\)
    \(\Xi\)
    \(d \times d\)
    \(v_1^\top\)\(v_2^\top\)\(\vdots\)
    \(V^\top\)
    the first two rows of \(V^\top\), drawn as pictures: eigen-digits

    Here \(n\) = 20,000 digits and \(d\) = 256 pixels, each from 0 (black) to 1 (white). The economy SVD has \(U\) of \(n \times d\) and \(\Xi\), \(V^\top\) of \(d \times d\). Each direction \(v_j\) has 256 entries, one per pixel, so it can be drawn as a 16 by 16 picture: an eigen-digit. These are MNIST digits (LeCun and colleagues, 1998), shrunk to 16 by 16 pixels.

    Eigen-digitsThe mean digit and the first 15 directions, red where a direction adds ink and blue where it removes it. Click one.

    Pixels are all in the same unit, so the digits are centered but not divided by their standard deviation; 14 border pixels are black on every digit, have no spread, and could not be divided by it anyway. The first direction keeps 11.3% of the variance, far less than the 95.5% of a day of weather (last lecture): a digit has more independent parts than a day.

    How many components is a digit?With your neighbour: guess the smallest \(k\) at which the rebuilt digit is readable. Then check, on several digits.

    the digit, 256 numbers

    variance kept, all digitsread correctly by a 3-nearest-neighbour classifierthis digit's rms pixel error (root mean square)

    Here each \(v_j\) is an eigen-digit, a picture of 256 numbers, and \(z_j = v_j^\top (x - \mu)\) is one number: how much of eigen-digit \(j\) this digit contains.

    \(\hat x = \mu + \sum_{j=1}^k z_j v_j\): the mean digit plus \(k\) eigen-digits, each weighted by this digit's own score: the reconstruction of the recap, with \(d = 256\). These 20 digits were held out from the reader that judges the rebuilt digits; the eigen-digits themselves were found from all 20,000.

    Two numbers per digit, as a map1,500 held-out digits placed by \(z_1\) and \(z_2\), coloured by what they are. PCA never saw the labels. Pick a digit.

    Zeros gather at one end of \(z_1\) (their mean is +2.0) and ones at the other (−2.0); the other eight digits overlap in the middle, every mean within 0.4 of zero. Two numbers are enough to see some structure and too few to separate ten digits.

    PCA keeps the directions of largest spread, which is not the same as the directions that separate classes. Methods that bend the map, such as t-SNE and UMAP, come with autoencoders.

    Problem 3: What the eigen-digits sayAbout the last four slides: the digits

    What you are given

    The digitsEach digit is a 16 by 16 picture, so \(d = 256\). The first principal direction keeps 11.3% of the variance of the digits. For a day of Levant weather (22 cities, last lecture), the first direction kept 95.5%.
    The map of the previous slideEach digit is placed by its first two coordinates \((z_1, z_2)\). Zeros gather at one end and ones at the other; the other eight digits overlap in the middle.

    What you are asked

    (a) How many numbers does one eigen-digit \(v_j\) contain?
    (b) What does 11.3% for the digits, against 95.5% for the weather, tell you?
    (c) Why do the other eight digits overlap on the map?

    Problem 3, the reasoningSpread is not meaning

    (a) 256An eigen-digit is a direction in the space of pictures: one weight per pixel. That is why it can be drawn as a picture.
    (b) variance spread over many directionsThe 22 cities rise and fall together (a warm day is warm everywhere), so one direction holds almost all of the variance. The strokes of a digit vary in many independent ways, so 51 components are needed to keep 90% of its variance.
    (c) PCA never sees the labelsPCA keeps the directions of largest spread. The first one happens to separate 0 from 1 (their mean values of \(z_1\) are +2.0 and −2.0); the other eight digits differ in ways the top two directions do not capture. Separating classes is a different goal, the one supervised methods optimize.

    Problem 4: Variance from the singular valuesPart 1, together: PCA and the SVD by numbers (1 of 2)

    What you are given

    400σ1 = 20100σ2 = 10100σ3 = 1025σ4 = 525σ5 = 5bar heights: the squares σ²
    The dataA centered matrix \(X\) with \(n = 100\) rows and \(d = 5\) columns. Its singular values are \(\sigma = (20, 10, 10, 5, 5)\).
    Facts you may useThe variance along \(v_j\) is \(\lambda_j = \sigma_j^2 / n\). The share of the variance kept by \(k\) components is \((\sigma_1^2 + \dots + \sigma_k^2) / (\sigma_1^2 + \dots + \sigma_5^2)\).

    What you are asked

    (a) What is \(\lambda_1\), the variance of the data along \(v_1\)?
    (b) What share of the total variance does the first component keep (\(k = 1\))? Give a decimal, such as 0.25.
    (c) What is the smallest number of components \(k\) that keeps at least 90% of the variance?

    Problem 4, the reasoningEvery answer comes from the squared singular values

    Square first\(\sigma^2\) = (400, 100, 100, 25, 25), and their total is 650.
    (a) the variance along \(v_1\)\(\lambda_1 = \sigma_1^2 / n\) = 400 / 100 = 4.
    (b) and (c) sharesShares of variance are shares of \(\sigma_j^2\): the \(n\) cancels. One component keeps 400 / 650 = 0.615. Two keep 500 / 650 = 0.769; three keep 600 / 650 = 0.923. So \(k = 3\) is the first to reach 90%.

    Problem 5: What a rank-2 approximation losesPart 1, together: PCA and the SVD by numbers (2 of 2)

    What you are given

    400σ1 = 20100σ2 = 10100σ3 = 1025σ4 = 525σ5 = 5bar heights: the squares σ²
    The dataA centered matrix \(X\) with \(n = 100\) rows and \(d = 5\) columns. Its singular values are \(\sigma = (20, 10, 10, 5, 5)\).
    Facts you may useThe best rank-\(k\) approximation \(X_k\) keeps the first \(k\) terms \(\sigma_j u_j v_j^\top\); its squared error \(\lVert X - X_k \rVert^2\), summed over all entries, is the sum of the dropped \(\sigma_j^2\). \(V\) is orthonormal, so a squared distance is the sum of the squared coordinates.

    What you are asked

    (a) What is \(\lVert X - X_2 \rVert^2\), the squared error of the best rank-2 approximation, summed over all entries of \(X\)?
    (b) One centered point \(x\) has coordinates \(z = V^\top x = (3, -1, 2, 0, 1)\). What is the squared distance between \(x\) and its reconstruction from \(k = 2\) components?

    Problem 5, the reasoningWhat the dropped terms cost

    (a) the whole matrix (Eckart and Young)Keeping \(k = 2\) drops the terms \(j\) = 3, 4 and 5, so the squared error is their \(\sigma_j^2\): 100 + 25 + 25 = 150.
    (b) one pointKeeping \(k = 2\) drops this point's coordinates \(z_3, z_4, z_5\): 2² + 0² + 1² = 5. Added up over every point, these squared distances give (a).

    Part 2 of 4

    Gaussian mixtures

    What if every point belongs to every cluster, a little?

    The full deck: Gaussian mixtures and EM

    K-means against a mixtureIn teams: predict which one puts more birds with their species, then check

    method
    colour

    Both see only the standardized bill length and depth, k = 3. K-means' circles are the round, equal clusters it assumes; the mixture's ellipses are fitted, one shape per cluster.

    Over all birds, longer bills are shallower (correlation −0.24); inside each species they are deeper (+0.39, +0.65, +0.64). That is what tilts the three clouds.

    Problem 6: Where k-means goes wrongBefore any formula: what you see on the previous slide

    What you are given

    The previous slideK-means and a Gaussian mixture, both with \(k = 3\) clusters, see only two numbers per penguin: the standardized bill length and bill depth. K-means puts 25 of the 342 penguins in a cluster that is mostly another species; the mixture makes fewer such mistakes. (The mixture is fitted by EM, the expectation-maximization algorithm of the next slides.)
    To think aboutK-means gives each point to the nearest center. For two centers, the points closer to one center than to the other lie on one side of a straight line. So k-means uses the same distance in every direction. Which clusters does that suit: round ones of the same size, or tilted, stretched ones? Which kind are the species on the previous slide?

    What you are asked

    (a) What is the main cause of k-means' 25 mistakes?
    (b) A penguin sits almost exactly between two cluster centers, a little closer to one of them. What does k-means say about it?

    Modeling data as a Mixture of GaussiansEach group is a Gaussian with its own centre and its own shape

    Dataset

    \(x_1\)\(x_2\)
    -0.5-0.4
    0.60.1
    -0.70.8
    ……

    How to find \(\mu_1, \mu_2, \Sigma_1, \Sigma_2\)?

    Modeling data as a Mixture of GaussiansOne measurement first: the flipper lengths of the 342 penguins

    Dataset

    \(x\)
    181
    186
    195
    193
    …

    Assume:

    • Data is modeled by a mixture of Gaussians: \(\mathcal{N}(\mu_j, \sigma_j^2)\)
    • We know how many Gaussians we need (here 2)
    Find \(\mu_1, \mu_2, \sigma_1, \sigma_2\)

    Observations \(x^{(i)} \in \mathbb{R}\). Each dot is a bird; flippers are measured in whole millimetres, so birds stack. The curves are the two Gaussians EM finds, \(\mu = 191, 216\) mm and \(\sigma = 6.5, 7.3\) mm: Adelie and Chinstrap together, then Gentoo.

    Gaussian Mixture ModelIntuition: if one were to 'create' the data

    \(\phi_1 =\) 0.30 \(\xrightarrow{\text{sample}} \mathcal{N}(\mu_1, \sigma_1^2) \xrightarrow{} x^{(i)}\)

    \(\phi_2 =\) 0.70 \(\xrightarrow{\text{sample}} \mathcal{N}(\mu_2, \sigma_2^2) \xrightarrow{} x^{(i)}\)

    With \(\mu_1 = 1\), \(\sigma_1 = 1.3\), \(\mu_2 = 3\), \(\sigma_2 = 1.6\). First choose a cluster with probability \(\phi_j\), then draw \(x\) from its Gaussian.

    Each bar shows the samples from one cluster (cluster 1 in teal, cluster 2 in red), under that cluster's dashed curve; the white curve is their sum, the density of the data. In real data the colors are gone: we see only the total, and EM's job is to guess the colors back.

    Problem 7: A mixture as a recipeConditional probability, in the order the data are made

    What you are given

    Step 1: choose a clusterThe cluster \(z\) of a new point (in this part, \(z\) is a cluster, no longer the PCA coordinates of Part 1) is drawn at random: \(z = 1\) with probability \(\phi_1 = 0.3\), and \(z = 2\) with probability \(\phi_2 = 0.7\). With \(k\) clusters this is a multinomial draw: one of \(k\) outcomes, outcome \(j\) with probability \(\phi_j\), and \(\phi_1 + \dots + \phi_k = 1\).
    Step 2: draw the point from that clusterIf \(z = 1\), \(x\) is drawn from the Gaussian with mean \(\mu_1 = 1\) and standard deviation \(\sigma_1 = 1.3\); if \(z = 2\), from the Gaussian with \(\mu_2 = 3\) and \(\sigma_2 = 1.6\). In symbols, \(p(x \mid z = j) = \mathcal{N}(x; \mu_j, \sigma_j^2)\): the density of \(x\), given that its cluster is \(j\).

    What you are asked

    (a) What is \(P(z = 2)\), the probability that a new point comes from cluster 2?
    (b) You draw 200 points this way. How many do you expect to come from cluster 1?
    (c) Which expression is \(p(x \mid z = 1)\)?
    (d) Which expression is \(p(x)\), the density of the data, whatever the cluster?

    Gaussian Mixture ModelThe joint distribution of a point and its hidden cluster

    Observations: \(x^{(i)} \in \mathbb{R}\). Number of clusters: \(k > 0\).
    The hidden cluster of point \(i\): \(z^{(i)} \in \{1, \dots, k\}\).

    $$\begin{aligned} P(x^{(i)}, z^{(i)}) &= P(x^{(i)} \mid z^{(i)})\, P(z^{(i)}) \\ P(z^{(i)}) &= \text{Multinomial}(\phi) \\ P(x^{(i)} \mid z^{(i)} = j) &= \mathcal{N}(\mu_j, \sigma_j^2) \end{aligned}$$

    The parameters are \(\phi \in \mathbb{R}^k\) with \(\sum_{j=1}^k \phi_j = 1\) (how common each cluster is), and for each cluster a mean and a variance. In \(d\) dimensions \(\mu_j \in \mathbb{R}^d\) and \(\sigma_j^2\) becomes a covariance matrix \(\Sigma_j \in \mathbb{R}^{d \times d}\).

    This is the model of Gaussian discriminant analysis (GDA), from the classification lectures, with one difference: there \(z\) was the species, written in the data. Here it is hidden.

    Modeling data as a Mixture of GaussiansGiven \(x^{(1)}, \ldots, x^{(n)}\) and \(k > 0\), the number of clusters. Drag \(x\) along the axis

    Soft assignment: find \(P(z^{(i)} = j \mid x^{(i)})\)

    the probability that point \(i\) belongs to cluster \(j\), once we have seen the point \(x^{(i)}\)

    \(z^{(i)}\), the cluster of point \(i\), is never observed: it is a latent (hidden) variable

    K-means gave each point one cluster, \(c^{(i)}\). A mixture gives each a probability for every cluster. A bird with a 204 mm flipper is about as likely to be in either.

    Problem 8: Soft assignment is Bayes' ruleThe soft assignment is a conditional probability: turn the condition around with Bayes' rule

    What you are given

    -3-2-1012345cluster 1, μ = 0cluster 2, μ = 2x = 1x = 1.5
    The clustersBoth have standard deviation \(\sigma = 1\); cluster 1 is centered at \(\mu_1 = 0\) and cluster 2 at \(\mu_2 = 2\).
    The formula\(w_1 = P(z = 1 \mid x) = \dfrac{\phi_1\, \mathcal{N}(x; 0, 1)}{\phi_1\, \mathcal{N}(x; 0, 1) + \phi_2\, \mathcal{N}(x; 2, 1)}\), with \(\mathcal{N}(x; \mu, 1) = \dfrac{e^{-(x - \mu)^2 / 2}}{\sqrt{2\pi}}\).

    What you are asked

    (a) In words, what does \(w_1 = P(z = 1 \mid x)\) measure?
    (b) With \(\phi = (0.5, 0.5)\), compute \(w_1\) at \(x = 1\).
    (c) With \(\phi = (0.5, 0.5)\), compute \(w_1\) at \(x = 1.5\). Give at least two decimals.
    (d) With \(\phi = (0.8, 0.2)\), compute \(w_1\) at \(x = 1\).
    (e) With \(\phi = (0.8, 0.2)\), compute \(w_1\) at \(x = 1.5\). Give at least two decimals.

    The E-step, one step at a time (1 of 2)The soft assignment \(w_j^{(i)}\) of point \(i\) to cluster \(j\), derived with Bayes' rule

    Step 1: what we want\[w_j^{(i)} \;=\; P(z^{(i)} = j \mid x^{(i)})\] The probability that point \(i\) came from cluster \(j\), now that we have seen the point. The bar \(\mid\) reads "given": first the event we ask about, then what we know. This \(w_j^{(i)}\) is the soft assignment, also called the responsibility of cluster \(j\) for point \(i\).
    Step 2: a conditional probability is a joint probability divided by a marginal one\[P(z^{(i)} = j \mid x^{(i)}) \;=\; \frac{P(z^{(i)} = j,\ x^{(i)})}{P(x^{(i)})}\] Top: the probability that the model chooses cluster \(j\) and makes this point. Bottom: the probability that it makes this point at all, through any cluster (called the marginal probability of the point). The ratio is the share of the ways to make \(x^{(i)}\) that go through cluster \(j\).

    The E-step, one step at a time (2 of 2)Write the top and the bottom with the parameters of the mixture

    Step 3: the top, the way the model makes a point\[P(z^{(i)} = j,\ x^{(i)}) \;=\; P(z^{(i)} = j)\; p(x^{(i)} \mid z^{(i)} = j) \;=\; \phi_j\; \mathcal{N}(x^{(i)}; \mu_j, \sigma_j^2)\] First the cluster, with probability \(\phi_j\); then the point, from that cluster's Gaussian.
    Step 4: the bottom adds every way to make the point\[P(x^{(i)}) \;=\; \sum_{s=1}^{k} \phi_s\; \mathcal{N}(x^{(i)}; \mu_s, \sigma_s^2)\] The point came from one of the \(k\) clusters, so its probability is the sum of the \(k\) ways.
    The E-step\[w_j^{(i)} \;=\; \frac{\phi_j\, \mathcal{N}(x^{(i)}; \mu_j, \sigma_j^2)}{\sum_{s=1}^{k} \phi_s\, \mathcal{N}(x^{(i)}; \mu_s, \sigma_s^2)}\] Every piece is a parameter we already have, so the E-step is a little arithmetic per point and cluster: what you did in the last problem. It is Bayes' rule, the same rule that turned GDA (Gaussian discriminant analysis) into a classifier.

    Expectation Step · one birdThe formula with numbers, for the fitted mixture. Click any bird

    The penguin highlighted in the k-means lecture, a Chinstrap, was 1.09 standard deviations from the Gentoo center and 1.11 from the Chinstrap one, so k-means gave it to the Gentoo. The Chinstrap Gaussian is tilted towards it, and its responsibility is 0.97.

    Problem 9: One penguin, by the formulaThe E-step with numbers, for three components

    What you are given

    One penguinA fitted mixture with three components. For one penguin \(x\) (not the one of the previous slide), each component \(j\) gives the product \(\phi_j\, \mathcal{N}(x; \mu_j, \Sigma_j)\): how common the component is, times the density of its Gaussian at this bird.
    component \(j\)123
    \(\phi_j\, \mathcal{N}(x; \mu_j, \Sigma_j)\)0.0040.0120.002
    \[w_j = \frac{\phi_j\, \mathcal{N}(x; \mu_j, \Sigma_j)}{\sum_{s=1}^{3} \phi_s\, \mathcal{N}(x; \mu_s, \Sigma_s)}\]

    What you are asked

    (a) What is this penguin's responsibility \(w_2\) for component 2? Give at least two decimals.
    (b) What is \(w_1\)?
    (c) What is \(w_1 + w_2 + w_3\)?
    (d) If every one of the three products were ten times larger, what would happen to \(w_2\)?

    Expectation-Maximization (EM) AlgorithmTwo guesses, each easy when the other is known

    E-Step: Guess \(z^{(i)}\) given \(\phi, \mu, \sigma\). Compute \(P(z^{(i)} \mid x^{(i)}; \phi, \mu, \sigma)\)

    M-Step: Estimate \(\phi, \mu, \sigma\) using Maximum Likelihood Estimation

    Maximization StepIf \(z^{(i)}\) were known: Gaussian Discriminant Analysis, each Gaussian fitted to its own birds

    $$\begin{aligned} \phi_j &= \frac{1}{n} \sum_{i=1}^n 1\{z^{(i)} = j\} \\[4pt] \mu_j &= \frac{\sum_{i=1}^n 1\{z^{(i)} = j\}\, x^{(i)}}{\sum_{i=1}^n 1\{z^{(i)} = j\}} \\[4pt] \Sigma_j &= \frac{\sum_{i=1}^n 1\{z^{(i)} = j\}\, (x^{(i)} - \mu_j)(x^{(i)} - \mu_j)^T}{\sum_{i=1}^n 1\{z^{(i)} = j\}} \end{aligned}$$

    This is Gaussian discriminant analysis (GDA), from the classification lectures. When every bird's species \(z^{(i)}\) is known, each Gaussian is fitted to its own birds. The indicator \(1\{z^{(i)} = j\}\) is 1 if bird \(i\) is in cluster \(j\) and 0 otherwise, so each sum runs over the birds of cluster \(j\) only. Inside each species longer bills are deeper, which tilts the ellipses.

    Maximization StepEM does not know \(z^{(i)}\): it uses GDA's formulas with the soft assignments in place of the indicators

    $$\begin{aligned} \phi_j &= \frac{1}{n} \sum_{i=1}^n w_j^{(i)} \\[4pt] \mu_j &= \frac{\sum_{i=1}^n w_j^{(i)} x^{(i)}}{\sum_{i=1}^n w_j^{(i)}} \\[4pt] \Sigma_j &= \frac{\sum_{i=1}^n w_j^{(i)} (x^{(i)} - \mu_j)(x^{(i)} - \mu_j)^T}{\sum_{i=1}^n w_j^{(i)}} \end{aligned}$$
    assignments

    Compare with GDA on the previous slide: the formulas are the same, with the responsibility \(w_j^{(i)}\) where GDA had the indicator \(1\{z^{(i)} = j\}\). In GDA each bird counts fully in one cluster (weight 1) and not at all in the others (weight 0); here it counts with weight \(w_j^{(i)}\) in every cluster. Found without the species, EM's ellipses come out close to the species' own.

    Problem 10: The M-step by handEach point counts in every cluster, with its responsibility as its weight

    What you are given

    point \(i\)1234
    \(x^{(i)}\)0145
    \(w_1^{(i)}\), cluster 10.90.80.20.1
    \(w_2^{(i)} = 1 - w_1^{(i)}\)0.10.20.80.9
    The M-step formulas (previous slides)\(\phi_1 = \frac{1}{n}\sum_i w_1^{(i)}\), \(\;\mu_1 = \dfrac{\sum_i w_1^{(i)} x^{(i)}}{\sum_i w_1^{(i)}}\), \(\;\sigma_1^2 = \dfrac{\sum_i w_1^{(i)} (x^{(i)} - \mu_1)^2}{\sum_i w_1^{(i)}}\), and the same for cluster 2 with \(w_2\).

    What you are asked

    (a) The E-step has just given these four points their responsibilities (left). Compute the new \(\phi_1\).
    (b) Compute the new mean \(\mu_1\) of cluster 1.
    (c) Compute the new mean \(\mu_2\) of cluster 2.
    (d) For comparison: if each point went entirely to the cluster with its larger responsibility (a hard assignment, as in k-means), what would \(\mu_1\) be?
    (e) Compute the new variance \(\sigma_1^2\) of cluster 1, around your \(\mu_1\) from (b). Divide by the sum of the responsibilities, as in the formula.

    EM Algorithm SummaryStart from a guess of \(\phi, \mu, \Sigma\), then repeat until the log-likelihood \(\ell\) (how probable the data are under the mixture) stops rising

    E-Step: Estimate \(w_j^{(i)}\)
    $$w_j^{(i)} = \dfrac{\overbrace{\colorbox{#1e6b2c}{$P(x^{(i)} \mid z^{(i)} = j)$}}^{\mathcal{N}(\mu_j,\, \Sigma_j)}\ \overbrace{\colorbox{#6b1650}{$P(z^{(i)} = j)$}}^{\phi_j}}{\sum_{s=1}^k \underbrace{\colorbox{#1e6b2c}{$P(x^{(i)} \mid z^{(i)} = s)$}}_{\mathcal{N}(\mu_s,\, \Sigma_s)}\ \underbrace{\colorbox{#6b1650}{$P(z^{(i)} = s)$}}_{\phi_s}}$$
    Iterate
    M-Step: Estimate \(\phi, \mu, \Sigma\)
    $$\phi_j = \frac{1}{n} \sum_{i=1}^n w_j^{(i)}$$ $$\mu_j = \frac{\sum_{i=1}^n w_j^{(i)} x^{(i)}}{\sum_{i=1}^n w_j^{(i)}}$$ $$\Sigma_j = \frac{\sum_{i=1}^n w_j^{(i)} (x^{(i)} - \mu_j)(x^{(i)} - \mu_j)^T}{\sum_{i=1}^n w_j^{(i)}}$$

    EM on the penguinsOne half-step per click. Watch the colours change in the E-step and the ellipses in the M-step

    start

    From this start \(\ell\) climbs from −1069 to −822.0 (dashed) in 46 iterations, never falling; from k-means' clusters it takes 39.

    Problem 11: EM in motionFirst run EM from several starts on the previous slide

    What you are given

    Try this firstOn the previous slide, press Run to the end, then Another start, a few times. Watch the curve of \(\ell\) on the right, and the value where it ends.
    \[\ell(\phi, \mu, \Sigma) = \sum_{i=1}^n \log \sum_{j=1}^k \phi_j\, \mathcal{N}(x^{(i)}; \mu_j, \Sigma_j)\]

    \(\ell\) is the log-likelihood: how probable the data are under the current mixture. Higher is better.

    What you are asked

    (a) What does the log-likelihood \(\ell\) do over the iterations of EM?
    (b) Two different starts end at different values of \(\ell\). Why?
    (c) You ran EM ten times, from ten different starts. Which run should you keep?

    K-means is EM with round clusters that shrinkFix every \(\Sigma_j = \sigma^2 I\) and every \(\phi_j = 1/k\), start where k-means started, and shrink \(\sigma\)

    \(\sigma\)

    With equal round Gaussians the E-step compares only distances:

    $$w_j^{(i)} = \frac{e^{-\lVert x^{(i)} - \mu_j \rVert^2 / 2\sigma^2}}{\sum_s e^{-\lVert x^{(i)} - \mu_s \rVert^2 / 2\sigma^2}}$$

    As \(\sigma\) shrinks the nearest center takes all the weight: \(w\) becomes \(1\{c^{(i)} = j\}\) (1 if k-means puts point \(i\) in cluster \(j\), 0 otherwise) and the M-step is k-means' update. From \(\sigma = 0.2\) down, every bird is assigned as k-means does.

    Problem 12: K-means as a limit, and the price of a mixtureWhat k-means assumed, and what a mixture costs

    What you are given

    The previous slideFix every covariance to \(\sigma^2 I\) (round clusters of the same size) and every \(\phi_j\) to \(1/k\). Then the responsibility of cluster \(j\) for point \(i\) is \[w_j^{(i)} = \frac{e^{-\lVert x^{(i)} - \mu_j \rVert^2 / 2\sigma^2}}{\sum_s e^{-\lVert x^{(i)} - \mu_s \rVert^2 / 2\sigma^2}}\] The factors \(\phi_j\) and \(1/(\sigma\sqrt{2\pi})^d\) are the same for every cluster, so they cancel.
    The parameters of a mixture\(k\) weights \(\phi_j\) that add up to 1, \(k\) means \(\mu_j\) of \(d\) numbers each, and \(k\) covariance matrices \(\Sigma_j\), each \(d \times d\) and symmetric. Count only the free numbers: since the weights add up to 1, only \(k - 1\) of them are free, and a symmetric \(d \times d\) matrix has \(d(d+1)/2\) free entries.

    What you are asked

    (a) As \(\sigma\) shrinks to 0, what do a point's responsibilities become?
    (b) What can a mixture with its own full covariance per component fit, that k-means cannot?
    (c) How many parameters does a mixture of \(k = 3\) full Gaussians in \(d = 2\) dimensions have?

    Soft assignments on the penguinsA colour mixed from the three components is a bird EM is unsure about. Click one

    colour

    The mixture misplaces 12 birds, k-means 25. It also says where it might be wrong: 25 birds have no responsibility above 0.9, and 7 of the 12 mistakes are among them. K-means' \(c^{(i)}\) is equally confident about every bird.

    Part 3 of 4

    Nonlinear dimensionality reduction

    What if the data lie near a curved surface, not a flat one?

    The full deck: autoencoders, t-SNE and UMAP

    PCA's answer: thirty numbersHeld-out digits rebuilt from \(k\) components, then read by a 3-nearest-neighbour classifier

    \[\hat x = \mu + \sum_{j=1}^{k} z_j\, v_j, \qquad z_j = v_j^\top (x - \mu)\]

    The PCA slides rebuilt each digit from the mean digit plus \(k\) eigen-digits. To judge them, a reader (a 3-nearest-neighbour classifier: it names a digit by the majority label of the 3 closest training digits) reads the rebuilt pictures. A reader that recognises 96.6% of the real held-out digits recognises 34% of them rebuilt from 2 numbers, 82% from 10, and 95% from 30, where the components keep 81% of the variance.

    The split: 16,000 digits to fit, and every fifth digit (4,000 in all) held out to test.

    The digits lie on a curved surfaceBlend two digits of the same kind pixel by pixel. Pick a pair, then slide from one to the other.

    digit A

    halfway

    digit B

    The picture halfway, \((1-t)\,x_A + t\,x_B\), is a point on the straight line between two digits in the space of 256 pixels. It is two faint strokes, not a digit: the straight line leaves the set of digits.

    PCA represents every digit as a point of a flat sheet through the mean, \(\mu + z_1 v_1 + \dots + z_k v_k\). If the digits lie near a curved surface, a flat sheet has to be wide (many \(k\)) to pass close to all of it.

    That the data lie near a surface of far fewer dimensions than the space, curved rather than flat, is called the manifold hypothesis. Moving a stroke a little, thickening it, slanting it: each is one direction along the surface, and none is a straight line in pixels.

    Neural networks: autoencodersAn encoder squeezes \(x\) into a low-dimensional latent representation \(z\); a decoder draws \(x\) back from it

    \[z = f_\phi(x) \in \mathbb{R}^k, \qquad \hat x = g_\theta(z)\]\[\mathcal{L} = \frac{1}{n}\sum_{i=1}^n \big\lVert x^{(i)} - g_\theta\big(f_\phi(x^{(i)})\big) \big\rVert^2\]

    The target is the input itself, so no labels are needed. The simplest version is one layer each: the encoder is a matrix \(\mathbf{W}_1\) followed by an activation function, the decoder a matrix \(\mathbf{W}_2\) followed by an activation. Here each is a small network (its weights are the \(\phi\) and \(\theta\) of the formula above), as in the architectures deck.

    This deck's network: 256 pixels, then 256 and 128 units with ReLU, then \(k\) numbers; the decoder mirrors it and ends in a sigmoid, so pixels stay between 0 and 1. For \(k = 2\) it has 198,146 weights, trained for 60 passes over the 16,000 training digits. The error is reported per pixel: \(\mathcal{L}\) divided by 256.

    Problem 13: An autoencoderAn encoder, a bottleneck, a decoder

    What you are given

    256x6416z64256x̂encoderdecoder
    The networkEncoder: Linear(256, 64), ReLU, Linear(64, 16). Decoder: Linear(16, 64), ReLU, Linear(64, 256). It is trained to make its output \(\hat x\) close to its input \(x\), measured by the squared error.
    CountingLinear(n_in, n_out) has \(n_{out} \times n_{in}\) weights and \(n_{out}\) biases.

    What you are asked

    (a) How many weights and biases does the encoder have in total?
    (b) How many numbers describe one digit in the code \(z\)?
    (c) What is the training target for a digit \(x\)?
    (d) Remove both ReLUs, so that the network is linear, and train it to the smallest possible squared error. What can you say about its reconstructions?

    Without activations, the autoencoder finds PCA's answerA linear autoencoder (no ReLU or other activation) trained by gradient descent, against PCA

    \[\hat x = \mu + W_2 W_1 (x - \mu), \qquad W_1 \in \mathbb{R}^{k \times d},\ W_2 \in \mathbb{R}^{d \times k}\]

    Its error falls to PCA's and stops there. The best rank-\(k\) map is the truncated SVD (Eckart and Young), and a linear network can do no better (Baldi and Hornik, 1989).

    Same plane, different axes: the columns are not the eigen-digits and come in no order of variance. Replacing \(W_1\) by \(A W_1\) and \(W_2\) by \(W_2 A^{-1}\), for any invertible \(A\), gives the same output.

    The same digit from \(k\) numbers, two waysPick a held-out digit, move \(k\). PCA's flat sheet against the network's bent one.

    the digit

    PCA

    autoencoder

    all 4,000 held-out digitsPCAautoencoder
    error per pixel
    read correctly

    At every \(k\) the network loses less: at \(k = 2\) its error is 34% below PCA's, at \(k = 8\) 56% below. These are the 20 held-out digits of the PCA slides: the first two of each kind.

    t-Distributed Stochastic Neighbor Embedding (t-SNE)Represents high-dimensional data in a lower-dimensional space while preserving the relationships between data points

    The similarity between two data points \(x_i\) and \(x_j\) is a conditional probability

    \[P(x_j \mid x_i) = \frac{\exp\!\big(-\lVert x_i - x_j\rVert^2 / 2\sigma_i^2\big)}{\sum_{k \ne i} \exp\!\big(-\lVert x_i - x_k\rVert^2 / 2\sigma_i^2\big)}\]

    Then a joint distribution is created by the mean, \(P(x_i, x_j) = \big[P(x_i \mid x_j) + P(x_j \mid x_i)\big] / 2n\). Each \(\sigma_i\) is set so that point \(i\) has about as many effective neighbours as the perplexity.

    The "distance" between them is minimised by gradient descent

    \[\mathrm{KL}(P \,\Vert\, Q) = \sum_{i \ne j} P_{ij} \log \frac{P_{ij}}{Q_{ij}}\]

    In two dimensions, the joint distribution of the map points \(y_i\) is

    \[Q(x_i, x_j) = \frac{\big(1 + \lVert y_i - y_j\rVert^2\big)^{-1}}{\sum_{k \ne l} \big(1 + \lVert y_k - y_l\rVert^2\big)^{-1}}\]

    which is a Student's t-distribution with one degree of freedom. Its heavy tails let moderately distant points sit far apart on the map, which opens gaps between groups.

    The Kullback-Leibler divergence is often used to measure how far one distribution is from another. It is large when close pairs (large \(P_{ij}\)) are placed far apart, and nearly indifferent to where far pairs go (van der Maaten and Hinton, 2008).

    UMAPUniform manifold approximation and projection: a graph of neighbours, laid out in two dimensions. Change the number of neighbours.

    5 nearest map neighbours share the labeltrustworthiness (10 neighbours)
    1. For each point, connect its \(m\) nearest neighbours with weights that fall off with distance, scaled so every point has the same total.
    2. Symmetrise: two points are linked if either chose the other, \(w_{ij} + w_{ji} - w_{ij} w_{ji}\).
    3. Place points in two dimensions so that linked points sit close and unlinked points apart, minimising a cross-entropy between the two graphs.

    UMAP keeps neighbours about as well as t-SNE, runs faster, and with more neighbours keeps more of the large-scale arrangement (McInnes, Healy and Melville, 2018). Like t-SNE it gives a map, not a way to draw a digit.

    Problem 14: Maps drawn from a graphBoth methods start from a graph of neighbours

    What you are given

    t-SNEFor each point \(i\), a probability \(P(x_j \mid x_i)\) for every other point \(j\), large for points near \(i\). The width \(\sigma_i\) is chosen so that point \(i\) has about as many effective neighbours as a number you set, the perplexity (often 30).
    UMAPEach point is linked to its \(m\) nearest neighbours, with weights that fall off with distance.
    Then, for bothThe points are placed in two dimensions so that linked (similar) points sit close together.

    What you are asked

    (a) What do t-SNE and UMAP both compute first?
    (b) UMAP links each of 2,000 digits to its \(m = 15\) nearest neighbours. How many links is that, before symmetrizing? Count one link for each digit and each of its 15 neighbours, so two digits that pick each other count twice.
    (c) Two clusters lie far apart on a t-SNE or UMAP map. What can you conclude?

    Where the maps misleadHow tightly each digit's points sit, relative to the average digit: in the 256 pixels, and on the t-SNE map

    • Sizes. In pixels the ones are the tightest digit (spread 0.74 of the average); on the t-SNE map they spread 0.93, and the tightest digit there is 0. t-SNE and UMAP even out the density of each cluster, so the size of a cluster says nothing.
    • Distances. No map keeps pixel distances well: the rank correlation is 0.52 for PCA, 0.41 for t-SNE and 0.42 for UMAP. The gap between two clusters is not their distance.
    • Drawing. t-SNE and UMAP give each digit a place but no way back to a picture, and t-SNE has no way to place a new digit without running again. Of these maps, only the autoencoder's comes with a decoder trained to draw.

    Wattenberg, Viégas and Johnson, How to use t-SNE effectively (Distill, 2016), shows each of these on small examples you can change.

    Part 4 of 4

    Hierarchical clustering

    Can one method cluster at every scale at once?

    The full deck: hierarchical clustering, in the autoencoders deck

    Hierarchical clustering: the dendrogramThirty penguins (the first ten of each species), standardized bills. Drag the red line.

    Merge the two closest clusters, again and again. A cut at any height is a clustering: the number of clusters is read off the tree, not chosen first.

    Agglomerative and divisiveTwo directions through the same tree

    Agglomerative: bottom up

    1. Start with \(n\) clusters, one point each.
    2. Merge the two clusters that are closest. How "close" is measured between two clusters is the linkage: Problem 15 defines two kinds, and the slide after it shows more.
    3. Record the height of the merge; repeat until one cluster is left.

    Divisive: top down

    Start with one cluster and split it, for example by 2-means, then split each part, and so on. Divisive methods see the whole data at the first split but are rarely used: there are far more ways to split a cluster than to merge two.

    A hierarchy is a description at every scale at once: cats and dogs at the top; cats with big ears or calm behaviour, dogs small or big below. Read from the top, the tree is divisive; built from the leaves, agglomerative. Biologists' trees of species are a familiar example.

    Ward's method, and other ways to join clustersAll 342 penguins, the tree cut at three clusters. Choose how the distance between two clusters is measured.

    \(A\) and \(B\) are the two clusters being compared: \(|A|\) is the number of points in \(A\), \(\mu_A\) is the mean of its points, and \(a\), \(b\) stand for points of \(A\) and \(B\). Single linkage uses the closest pair, complete the farthest pair, average the mean distance over all pairs, and Ward the merge that raises the k-means distortion \(J\) the least.

    Ward merges the pair that raises the k-means distortion \(J\), the sum of squared distances to the cluster means, the least. At three clusters its \(J\) is 201.6, above k-means' 186.9: a greedy merge is never undone. Single linkage chains: one bird close to the next joins clusters through a bridge, and all but two birds end in one cluster. For comparison, k-means puts 317 of 342 birds with their species and the Gaussian mixture 330.

    What to take away

    1. PCA is the SVD of the centered data. \(\lambda_j = \sigma_j^2 / n\), and dropping the term \(j\) costs \(\sigma_j^2\) of squared error.
    2. A Gaussian mixture is a recipe: choose a cluster with probability \(\phi_j\), then a point from its Gaussian. Clustering guesses the cluster back: \(w_j = P(z = j \mid x)\), by Bayes' rule.
    3. EM alternates the E-step (the responsibilities) and the M-step (GDA's formulas, weighted by the responsibilities). The log-likelihood never decreases, and k-means is its limit with round clusters that shrink.
    4. Autoencoders bend PCA's flat sheet; t-SNE and UMAP draw a graph of neighbours in two dimensions, keeping who is near whom, not how far.
    5. Hierarchical clustering records every merge in a tree; the linkage decides what "close" means between two clusters.

    The full decks, for reference: PCA and the SVD, Gaussian mixtures and EM, autoencoders, maps and clustering.