{
  "id": "unsupervised-learning",
  "module": "math-ml",
  "level": 2,
  "minutes": 35,
  "audiences": [
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "Unsupervised Learning: k-means, Gaussian Mixtures and EM, PCA, t-SNE and UMAP",
      "description": "Unsupervised learning for machine learning practitioners: k-means and k-means++, DBSCAN density clustering, Gaussian mixture models and the EM algorithm, principal component analysis (PCA), t-SNE and UMAP visualisation, evaluation with silhouette, ARI and BIC, and clustering embedding vectors in practice. Based on original papers and the official scikit-learn documentation, with runnable scikit-learn and NumPy examples.",
      "updated": "2026-11-12",
      "takeaways": [
        "Unsupervised learning has inputs X but no labels y. Its goal is to find structure: clustering groups similar samples, dimensionality reduction summarises high-dimensional data with a few coordinates, and density estimation models the probability distribution of the data.",
        "k-means alternates between assigning each point to its nearest centre and moving each centre to the mean of its points. Neither step increases the within-cluster sum of squares (inertia), but only a local optimum is guaranteed. k-means++ picks initial centres with probability proportional to squared distance, and Arthur and Vassilvitskii (2007) proved its expected result is within a Θ(log k) factor of optimal.",
        "A Gaussian mixture model gives each point a probability of belonging to each cluster (soft assignment) and is fitted by maximum likelihood with EM: the E-step computes posterior responsibilities under the current parameters, the M-step re-estimates means, covariances and mixing weights weighted by those responsibilities, and the log-likelihood never decreases (Dempster et al., 1977).",
        "PCA finds the orthogonal directions of greatest variance and can be computed directly from the SVD of the centred data; it is linear, invertible and interpretable. t-SNE and UMAP are non-linear methods that preserve local neighbourhoods and suit visualisation, but cluster sizes and between-cluster distances on their plots cannot be read literally.",
        "Without labels, cluster quality must be judged from several kinds of evidence: internal indices such as silhouette and BIC, ARI when some labels exist, and manual inspection of each cluster. Different indices can suggest different values of k."
      ],
      "faq": [
        {
          "q": "How do I choose k for k-means?",
          "a": "Common practice is to compute the silhouette score or the inertia curve (the 'elbow') over a range of k, compare BIC when using Gaussian mixtures, and then weigh the result against the intended use and manual spot checks. In this lesson's handwritten-digits example the silhouette score at k=12 is slightly higher than at k=10 (0.185 vs 0.183), while the Gaussian mixture BIC is lowest at 10 components. Indices do not always agree, and k ultimately depends on the purpose."
        },
        {
          "q": "Which data suit k-means, DBSCAN and Gaussian mixtures?",
          "a": "k-means assumes roughly spherical clusters of similar size and is fast, which makes it a good baseline. DBSCAN (Ester et al., 1996) links samples by density, finds clusters of arbitrary shape and labels sparse points as noise, but is sensitive to eps and struggles when densities differ widely. Gaussian mixtures allow elliptical clusters and give soft assignment probabilities, at the cost of more parameters and more sensitivity to initialisation. The scikit-learn clustering guide has an overview table comparing the methods by geometry, scalability and parameters."
        },
        {
          "q": "If two clusters are far apart on a t-SNE plot, are they very different?",
          "a": "Not necessarily. The interactive Distill article by Wattenberg et al. (2016) uses synthetic data to show that cluster sizes on a t-SNE plot mean nothing, that distances between clusters may mean nothing, that random noise can look structured, and that results change markedly with perplexity. Before interpreting a plot, try several perplexities and random seeds and cross-check with PCA or distances in the original space."
        },
        {
          "q": "How is PCA related to autoencoders?",
          "a": "PCA is linear dimensionality reduction: encoding projects onto the top k principal components and decoding projects back, giving the smallest squared reconstruction error among all k-dimensional linear projections. An autoencoder uses neural networks for the encoder and decoder and can learn non-linear low-dimensional representations; Hinton and Salakhutdinov (2006) showed in Science that deep autoencoders can reduce dimensionality much better than PCA."
        },
        {
          "q": "Are these classical methods still relevant in the era of large models?",
          "a": "Yes. Text and image embeddings are themselves high-dimensional data, and a common workflow is embed, reduce, cluster, then name the clusters by hand. BERTopic (Grootendorst, 2022), for example, creates document embeddings with a pre-trained model, reduces them with UMAP, clusters them with HDBSCAN and extracts topic words for each cluster with a class-based TF-IDF. The same methods are used to inspect training-data distributions, find duplicates and analyse the types of questions users ask."
        }
      ],
      "sources": [
        {
          "title": "scikit-learn User Guide: 2.3 Clustering (method overview and clustering performance evaluation)",
          "url": "https://scikit-learn.org/stable/modules/clustering.html"
        },
        {
          "title": "scikit-learn User Guide: 2.1 Gaussian mixture models",
          "url": "https://scikit-learn.org/stable/modules/mixture.html"
        },
        {
          "title": "scikit-learn User Guide: 2.5 Decomposing signals in components (PCA and more)",
          "url": "https://scikit-learn.org/stable/modules/decomposition.html"
        },
        {
          "title": "scikit-learn User Guide: 2.2 Manifold learning (t-SNE and more)",
          "url": "https://scikit-learn.org/stable/modules/manifold.html"
        },
        {
          "title": "scikit-learn API: sklearn.cluster.KMeans",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html"
        },
        {
          "title": "UMAP documentation (umap-learn)",
          "url": "https://umap-learn.readthedocs.io/en/latest/"
        },
        {
          "title": "Wattenberg, Viégas, Johnson (2016), How to Use t-SNE Effectively, Distill",
          "url": "https://distill.pub/2016/misread-tsne/"
        },
        {
          "title": "Deisenroth, Faisal, Ong: Mathematics for Machine Learning (free official edition; Ch. 10 PCA, Ch. 11 Gaussian mixture models)",
          "url": "https://mml-book.github.io/"
        },
        {
          "title": "Lloyd (1982), Least Squares Quantization in PCM, IEEE Transactions on Information Theory",
          "url": "https://doi.org/10.1109/TIT.1982.1056489"
        },
        {
          "title": "Arthur, Vassilvitskii (2007), k-means++: The Advantages of Careful Seeding (author PDF)",
          "url": "https://theory.stanford.edu/~sergei/papers/kMeansPP-soda.pdf"
        },
        {
          "title": "Ester, Kriegel, Sander, Xu (1996), A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise, KDD-96",
          "url": "https://cdn.aaai.org/KDD/1996/KDD96-037.pdf"
        },
        {
          "title": "Dempster, Laird, Rubin (1977), Maximum Likelihood from Incomplete Data via the EM Algorithm",
          "url": "https://doi.org/10.1111/j.2517-6161.1977.tb01600.x"
        },
        {
          "title": "Pearson (1901), On Lines and Planes of Closest Fit to Systems of Points in Space",
          "url": "https://doi.org/10.1080/14786440109462720"
        },
        {
          "title": "Hotelling (1933), Analysis of a Complex of Statistical Variables into Principal Components",
          "url": "https://doi.org/10.1037/h0071325"
        },
        {
          "title": "van der Maaten, Hinton (2008), Visualizing Data using t-SNE, JMLR 9",
          "url": "https://www.jmlr.org/papers/v9/vandermaaten08a.html"
        },
        {
          "title": "McInnes, Healy, Melville (2018), UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction",
          "url": "https://arxiv.org/abs/1802.03426"
        },
        {
          "title": "Rousseeuw (1987), Silhouettes: A Graphical Aid to the Interpretation and Validation of Cluster Analysis",
          "url": "https://doi.org/10.1016/0377-0427(87)90125-7"
        },
        {
          "title": "Hubert, Arabie (1985), Comparing Partitions, Journal of Classification",
          "url": "https://link.springer.com/article/10.1007/BF01908075"
        },
        {
          "title": "Kobak, Berens (2019), The Art of Using t-SNE for Single-Cell Transcriptomics, Nature Communications",
          "url": "https://doi.org/10.1038/s41467-019-13056-x"
        },
        {
          "title": "Hinton, Salakhutdinov (2006), Reducing the Dimensionality of Data with Neural Networks, Science",
          "url": "https://doi.org/10.1126/science.1127647"
        },
        {
          "title": "Grootendorst (2022), BERTopic: Neural Topic Modeling with a Class-based TF-IDF Procedure",
          "url": "https://arxiv.org/abs/2203.05794"
        }
      ],
      "url": "https://aimap.page/en/learn/math-ml/unsupervised-learning/",
      "markdown": "**Summary**: Supervised learning maps inputs to outputs from labelled examples. Unsupervised learning has only inputs and asks different questions: what natural groups exist in the data, can it be described with fewer dimensions, and what distribution does it follow? This lesson moves from k-means to density-based clustering, Gaussian mixtures and EM, PCA, t-SNE and UMAP, and finally cluster evaluation. Every number quoted comes from the runnable example at the end.\n\nThis lesson belongs to the [Unsupervised Learning](/learn/unit/u23-unsupervised) unit. The prerequisites are [Overfitting, Generalisation and Data Splits](/learn/generalization) and [Linear Algebra](/learn/linear-algebra); the EM section uses maximum likelihood from [Probability, Statistics and Information Theory](/learn/probability-information). Continue with [Neural Networks and Backpropagation](/learn/neural-networks) and [Tokens and Embeddings](/learn/tokens-embeddings). Related algorithm cards: [k-means](/learn/algorithms/kmeans), [DBSCAN](/learn/algorithms/dbscan), [EM](/learn/algorithms/em), [PCA](/learn/algorithms/pca), [t-SNE](/learn/algorithms/tsne), [UMAP](/learn/algorithms/umap) and [autoencoders](/learn/algorithms/autoencoder).\n\n## What unsupervised learning is for\n\n| Task | Output | Typical methods | Example in work with large models |\n|---|---|---|---|\n| Clustering | A cluster id per sample (or a probability per cluster) | k-means, DBSCAN, Gaussian mixtures | Grouping user questions by topic; finding duplicate or anomalous training samples |\n| Dimensionality reduction | Low-dimensional coordinates per sample | PCA, t-SNE, UMAP, autoencoders | Plotting 768-dimensional or larger embeddings in 2-D; compressing features |\n| Density estimation | A probability distribution p(x) | Gaussian mixtures, kernel density estimation | Anomaly detection: very improbable samples may be outliers |\n\nThere is no ground truth to compare against, so the last section of this lesson is devoted to evaluating results.\n\n## k-means and k-means++\n\nk-means splits n points into k groups so that the sum of squared distances from each point to its cluster centre is as small as possible. This quantity is called the inertia, or within-cluster sum of squares:\n\n```text\nObjective  J = Σᵢ ‖xᵢ − μ_c(i)‖²     c(i) is the cluster of point i, μ_c the centre of cluster c\nSteps      1. Assign: give each point to its nearest centre\n           2. Update: move each centre to the mean of its points\n           repeat 1–2 until assignments stop changing\n```\n\nThis iteration is usually called Lloyd's algorithm (Lloyd, formally published in 1982). Neither step increases J, so the algorithm always converges, but only to a local optimum: Arthur and Vassilvitskii (2007) note at the start of their paper that solving the objective exactly is NP-hard, even with just two clusters.\n\nInitialisation therefore matters. **k-means++** picks the first centre uniformly from the data, then samples each new centre with probability proportional to its squared distance to the nearest centre already chosen, so points far from existing centres are more likely to be picked. The authors prove that the expected objective is within a Θ(log k) factor of optimal. On the handwritten-digits data (1,797 samples, 64 dimensions), running 20 random seeds with a single initialisation each gives a mean inertia of 1,189,680 and a worst case of 1,240,658 for random initialisation, against 1,178,526 and 1,218,629 for k-means++.\n\nscikit-learn's `KMeans` uses k-means++ by default. Since version 1.4 `n_init` defaults to `'auto'`, which runs k-means++ once and random initialisation 10 times, keeping the result with the lowest inertia.\n\nk-means implicitly assumes clusters that are roughly convex and similar in size, and features on comparable scales. Features are usually standardised first; text embeddings are often L2-normalised so that Euclidean distance is monotonically related to cosine similarity.\n\n## DBSCAN: density-based clustering\n\nDBSCAN, proposed by Ester et al. (1996), does not need the number of clusters in advance. Instead it defines density with two parameters, a radius eps and a minimum count min_samples:\n\n- **Core point**: has at least min_samples points within eps;\n- **Border point**: not a core point, but within eps of a core point;\n- **Noise point**: neither, labelled −1.\n\nCore points that are density-reachable from one another, together with their border points, form a cluster, so clusters can take any shape. The example compares methods on two interleaving half-moons (500 points): k-means with k=2 reaches an adjusted Rand index (ARI, see the last section) of only 0.257, because it can only split the plane with a straight boundary, while DBSCAN (eps=0.2, min_samples=5) reaches 1.000, finding exactly 2 clusters with no noise points. DBSCAN is sensitive to eps and struggles when clusters have very different densities; HDBSCAN extends it to a hierarchical version that handles varying densities, and scikit-learn has provided `HDBSCAN` since version 1.3.\n\n## Gaussian mixture models and EM\n\nk-means gives each point one definite cluster (hard assignment). A **Gaussian mixture model** (GMM) assumes the data were generated by K Gaussian distributions mixed with weights π₁…π_K:\n\n```text\np(x) = Σₖ πₖ · N(x | μₖ, Σₖ)          Σₖ πₖ = 1\n```\n\nThe posterior probability that point i came from component k is called its responsibility rᵢₖ; this is soft assignment. The parameters θ = {πₖ, μₖ, Σₖ} are estimated by maximum likelihood, but which component produced each point is an unobserved latent variable, which makes direct maximisation hard. The **EM algorithm**, formalised by Dempster, Laird and Rubin (1977), alternates two steps:\n\n```text\nE-step   rᵢₖ = πₖ · N(xᵢ | μₖ, Σₖ) / Σⱼ πⱼ · N(xᵢ | μⱼ, Σⱼ)       responsibilities under current parameters\nM-step   Nₖ = Σᵢ rᵢₖ\n         πₖ = Nₖ / n\n         μₖ = Σᵢ rᵢₖ · xᵢ / Nₖ\n         Σₖ = Σᵢ rᵢₖ · (xᵢ − μₖ)(xᵢ − μₖ)ᵀ / Nₖ                   parameters weighted by responsibilities\n```\n\nThe paper proves that no iteration decreases the log-likelihood of the observed data, though, as with k-means, only convergence to a local optimum is guaranteed. The example implements one-dimensional two-component EM in NumPy on data drawn from N(−2, 0.8²) and N(3, 1.2²) in a 3:7 ratio. After 50 iterations the log-likelihood rises from −3604.4 to −2034.5 without ever decreasing, and the estimates are π = (0.303, 0.697), μ = (−2.02, 2.955) and σ = (0.815, 1.117).\n\nk-means can be viewed as a special case of a GMM: when all components share a spherical covariance that shrinks towards zero, responsibilities become 0 or 1, the E-step becomes \"assign to the nearest centre\" and the M-step becomes \"take the mean\".\n\nThe number of GMM components can be chosen with **BIC** (Bayesian information criterion), which adds a penalty growing with the number of parameters to the negative log-likelihood; lower is better. The example first reduces the digits to 20 dimensions with PCA and then fits full-covariance GMMs. Across 6, 8, 10, 12, 14 and 16 components, BIC is lowest at 10 (213,941), and that GMM reaches an ARI of 0.842 against the true digit labels, higher than the 0.666 of k-means on the raw 64 dimensions.\n\n## Principal component analysis (PCA)\n\nPCA looks for orthogonal directions such that the data have maximum variance along the first, maximum remaining variance along the second subject to being orthogonal to the first, and so on. The idea goes back to Pearson's (1901) lines and planes of closest fit and Hotelling's (1933) principal components.\n\n```text\n1. Centre:  X̃ = X − mean\n2. SVD:     X̃ = U · S · Vᵀ\n3. Principal directions = first k columns of V; variance of component j = sⱼ² / (n − 1)\n4. Reduced coordinates = X̃ · V_k; explained-variance ratio = sⱼ² / Σ s²\n```\n\nThere are two equivalent views of PCA: maximising the variance of the projection, or minimising the squared error of reconstructing the data from the projection. The latter is an application of the Eckart–Young theorem from the [Linear Algebra](/learn/linear-algebra) lesson. In the example, the first 2 principal components of the digits explain only 28.5% of the variance and 21 components are needed to reach 90%, so a 2-D PCA plot discards a great deal of information.\n\nPCA is used for initial reduction before visualisation (t-SNE and UMAP are often run on a few dozen PCA components), for denoising and compression, and for removing linear correlation between features. It captures only linear structure and is sensitive to feature scales, so features are usually standardised first.\n\n## t-SNE and UMAP: non-linear visualisation\n\n**t-SNE** (van der Maaten and Hinton, 2008) turns pairwise similarities in the high-dimensional space into probabilities and then finds 2-D or 3-D coordinates that minimise the KL divergence between the low- and high-dimensional similarity distributions. It uses a heavy-tailed Student-t distribution in the low-dimensional space to ease the \"crowding problem\" that arises when many high-dimensional points are squeezed into few dimensions. Its main parameter, perplexity, roughly corresponds to the effective number of neighbours each point considers; the original paper gives typical values between 5 and 50.\n\n**UMAP** (McInnes et al., 2018) builds a neighbourhood graph from manifold assumptions and fuzzy topology and then optimises a low-dimensional layout. The authors state in the abstract that it is competitive with t-SNE for visualisation quality, arguably preserves more of the global structure, and runs faster; unlike t-SNE, UMAP can `transform` new samples. Its main parameters are `n_neighbors` (larger values emphasise global structure) and `min_dist` (how tightly points may be packed in the embedding).\n\nBoth preserve local neighbourhoods well. The example measures trustworthiness (k=5; whether neighbours in the embedding are also neighbours in the original space, maximum 1) for 2-D embeddings of the digits: PCA 0.830, t-SNE 0.995 and UMAP 0.990.\n\nRead such plots with care. The following points all come from synthetic-data experiments in the Distill article \"How to Use t-SNE Effectively\" (Wattenberg et al., 2016):\n\n1. **Hyperparameters matter**: the same data can take very different shapes at different perplexities, so compare several settings.\n2. **Cluster sizes mean nothing**: t-SNE expands dense clusters and contracts sparse ones.\n3. **Distances between clusters might not mean anything**: two far-apart clusters are not necessarily more different than two close ones.\n4. **Random noise can look structured**: small clumps do not prove the data contain such groups.\n\nKobak and Berens (2019) summarise ways to improve the global structure of t-SNE for single-cell data, including PCA initialisation; scikit-learn's `TSNE` has defaulted to `init=\"pca\"` since version 1.2. Use visualisations to form hypotheses, and confirm clustering conclusions in the original or PCA space.\n\n## Evaluating clusters\n\n| Index | Needs true labels? | Meaning | Source |\n|---|---|---|---|\n| Inertia (within-cluster sum of squares) | No | Smaller is more compact, but it always falls as k grows, so only the \"elbow\" is informative | k-means objective |\n| Silhouette score | No | Per point s = (b − a) / max(a, b), where a is the mean distance to points in the same cluster and b the mean distance to the nearest other cluster; ranges from −1 to 1, higher is better | Rousseeuw (1987) |\n| BIC | No (needs a probabilistic model) | Log-likelihood minus a penalty on the number of parameters, used to compare GMM sizes; lower is better | scikit-learn Gaussian mixture guide |\n| Adjusted Rand index (ARI) | Yes | Agreement between two partitions corrected for chance; about 0 for random labelling and 1 for perfect agreement | Hubert and Arabie (1985) |\n\nIn the example, silhouette scores on the digits for k = 5, 8, 10, 12 and 15 are 0.138, 0.178, 0.183, 0.185 and 0.174: the maximum is at k=12 rather than at the true number of classes, 10, and all values are modest. Internal indices reflect only geometric compactness and separation, which need not match the categories people care about. In practice ARI is available only when some labels exist, and the final judgement usually also requires sampling each cluster and naming it.\n\n## Runnable example\n\nThe code below was run on scikit-learn 1.9, NumPy 2.5 and umap-learn 0.6, and its output matches the numbers above (t-SNE and UMAP results may vary slightly across versions and thread counts).\n\n```python\nimport numpy as np\nfrom sklearn.datasets import load_digits, make_moons\nfrom sklearn.cluster import KMeans, DBSCAN\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE, trustworthiness\nfrom sklearn.metrics import adjusted_rand_score as ari, silhouette_score\n\nX, y = load_digits(return_X_y=True)          # 1,797 8×8 handwritten digits, 64 dimensions\n\n# 1) Random vs k-means++ initialisation: 20 seeds, one initialisation each\nfor init in (\"random\", \"k-means++\"):\n    inert = [KMeans(10, init=init, n_init=1, random_state=s).fit(X).inertia_ for s in range(20)]\n    print(f\"{init:10s} inertia mean {np.mean(inert):.0f}  worst {np.max(inert):.0f}\")\nkm = KMeans(10, n_init=10, random_state=0).fit(X)\nprint(f\"k-means ARI = {ari(y, km.labels_):.3f}\")\n\n# 2) Silhouette scores\nfor k in (5, 8, 10, 12, 15):\n    lab = KMeans(k, n_init=10, random_state=0).fit_predict(X)\n    print(f\"k={k:2d} silhouette {silhouette_score(X, lab):.3f}\")\n\n# 3) PCA explained variance\ncum = np.cumsum(PCA().fit(X).explained_variance_ratio_)\nprint(f\"first 2 components {cum[1]:.3f}; {np.searchsorted(cum, 0.90) + 1} needed for 90%\")\n\n# 4) Gaussian mixtures + BIC (after reducing to 20 dimensions)\nZ = PCA(20, random_state=0).fit_transform(X)\nfor n in (6, 8, 10, 12, 14, 16):\n    print(n, round(GaussianMixture(n, covariance_type=\"full\", random_state=0).fit(Z).bic(Z)))\ng = GaussianMixture(10, covariance_type=\"full\", random_state=0).fit(Z)\nprint(f\"GMM(10) ARI = {ari(y, g.predict(Z)):.3f}\")\n\n# 5) Non-convex clusters: k-means vs DBSCAN\nM, ym = make_moons(500, noise=0.05, random_state=0)\nprint(\"k-means ARI\", round(ari(ym, KMeans(2, n_init=10, random_state=0).fit_predict(M)), 3))\nprint(\"DBSCAN  ARI\", round(ari(ym, DBSCAN(eps=0.2, min_samples=5).fit_predict(M)), 3))\n\n# 6) Neighbourhood preservation of 2-D embeddings\nP2 = PCA(2, random_state=0).fit_transform(X)\nT2 = TSNE(2, perplexity=30, random_state=0).fit_transform(X)\nprint(f\"trustworthiness PCA {trustworthiness(X, P2, n_neighbors=5):.3f}  t-SNE {trustworthiness(X, T2, n_neighbors=5):.3f}\")\n# UMAP: import umap; umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=0).fit_transform(X)\n\n# 7) EM by hand: 1-D two-component Gaussian mixture\nrng = np.random.default_rng(0)\nx = np.concatenate([rng.normal(-2, 0.8, 300), rng.normal(3, 1.2, 700)])\npi, mu, var = np.array([0.5, 0.5]), np.array([-1.0, 1.0]), np.array([1.0, 1.0])\nll = []\nfor _ in range(50):\n    p = pi * np.exp(-(x[:, None] - mu) ** 2 / (2 * var)) / np.sqrt(2 * np.pi * var)\n    ll.append(np.log(p.sum(1)).sum())\n    r = p / p.sum(1, keepdims=True)                       # E-step: responsibilities\n    nk = r.sum(0); pi = nk / len(x)                       # M-step: weighted updates\n    mu = (r * x[:, None]).sum(0) / nk\n    var = (r * (x[:, None] - mu) ** 2).sum(0) / nk\nprint(f\"log-likelihood {ll[0]:.1f} → {ll[-1]:.1f}, non-decreasing {bool(np.all(np.diff(ll) >= -1e-9))}\")\nprint(\"π\", pi.round(3), \"μ\", mu.round(3), \"σ\", np.sqrt(var).round(3))\n```\n\nKey outputs: random initialisation inertia mean 1,189,680 and worst 1,240,658, k-means++ mean 1,178,526 and worst 1,218,629; k-means ARI 0.666; silhouette 0.138 / 0.178 / 0.183 / 0.185 / 0.174; the first 2 components explain 28.5% of the variance and 21 are needed for 90%; BIC is lowest at 10 components (213,941) and the GMM ARI is 0.842; on the half-moons k-means ARI is 0.257 and DBSCAN ARI 1.000; trustworthiness is 0.830 for PCA, 0.995 for t-SNE and 0.990 for UMAP; the EM log-likelihood goes from −3604.4 to −2034.5.\n\n## Hands-on practice\n\n1. **Unit project**: take 1,000 sentences, embed them with any open sentence-embedding model and L2-normalise the vectors; cluster them with k-means, plot them in 2-D with UMAP, read 10 sentences from each cluster and name it, then check whether the names still make sense for other values of k.\n2. In the [scikit-learn example gallery](https://scikit-learn.org/stable/auto_examples/index.html), find the clustering comparison example, compare k-means, DBSCAN and Gaussian mixtures on the same data, and vary DBSCAN's eps to see how the number of clusters changes.\n3. Run the PCA and Gaussian mixture notebooks in the [Mathematics for Machine Learning companion repository](https://github.com/mml-book/mml-book.github.io) and derive the EM M-step yourself using the formulas above.\n4. In the [interactive Distill t-SNE article](https://distill.pub/2016/misread-tsne/), set perplexity to 2, 30 and 100 and record how the plot of the same data changes.\n\n## Suggested order\n\nStart with the method overview and the \"Clustering performance evaluation\" section of the [scikit-learn clustering guide](https://scikit-learn.org/stable/modules/clustering.html) to get the big picture. For the mathematics, read chapters 10 (PCA) and 11 (Gaussian mixtures and EM) of [Mathematics for Machine Learning](https://mml-book.github.io/). For visualisation, read the [Distill t-SNE article](https://distill.pub/2016/misread-tsne/) and then the parameter and clustering sections of the [UMAP documentation](https://umap-learn.readthedocs.io/en/latest/). Then move on to [Neural Networks and Backpropagation](/learn/neural-networks), where autoencoders extend this lesson's dimensionality reduction to non-linear mappings."
    },
    "zh-hans": {
      "title": "无监督学习：k-means、高斯混合与 EM、PCA、t-SNE 与 UMAP",
      "description": "面向机器学习的无监督学习：k-means 与 k-means++、DBSCAN 密度聚类、高斯混合模型与 EM 算法、主成分分析（PCA）、t-SNE 与 UMAP 可视化，以及轮廓系数、ARI、BIC 等评估方法和嵌入向量聚类的实际用法。依据原始论文与 scikit-learn 官方文档，附可运行的 scikit-learn 与 NumPy 示例。",
      "updated": "2026-11-12",
      "takeaways": [
        "无监督学习只有输入 X、没有标签 y，目标是发现数据中的结构：聚类把相似样本分到一组，降维用少数几个坐标概括高维数据，密度估计给出数据的概率分布。",
        "k-means 交替执行“把每个点分给最近的中心”和“把中心移到所属点的均值”，每一步都不会增加簇内平方和（惯量），但只保证收敛到局部最优。k-means++ 按距离平方加权选初始中心，Arthur 与 Vassilvitskii（2007）证明其期望结果与最优解相差 Θ(log k) 倍以内。",
        "高斯混合模型给每个点属于各簇的概率（软分配），用 EM 算法求最大似然：E 步按当前参数计算后验“责任度”，M 步按责任度加权更新均值、协方差和混合权重，对数似然每轮单调不减（Dempster 等，1977）。",
        "PCA 找出方差最大的正交方向，可由中心化数据的 SVD 直接得到，是线性、可逆、可解释的降维；t-SNE 与 UMAP 是非线性方法，擅长保留局部邻域，适合可视化，但图上簇的大小和簇间距离不能直接解读。",
        "没有标签时，聚类质量要组合多种证据判断：轮廓系数、BIC 等内部指标，有部分标签时的 ARI，以及人工查看每个簇的样本。指标之间可能给出不同的 k。"
      ],
      "faq": [
        {
          "q": "k-means 的 k 怎么选？",
          "a": "常用做法是对多个 k 计算轮廓系数或惯量曲线（“肘部法”），用高斯混合时比较 BIC，再结合业务含义与人工抽查。本课示例在手写数字数据上，轮廓系数在 k=12 时略高于 k=10（0.185 对 0.183），而高斯混合的 BIC 在 10 个成分时最低；不同指标给出的答案不一定一致，k 最终取决于用途。"
        },
        {
          "q": "k-means、DBSCAN、高斯混合各适合什么数据？",
          "a": "k-means 假设簇大致呈球形、大小相近，速度快，适合作为基线；DBSCAN（Ester 等，1996）按密度连接样本，能发现任意形状的簇并把稀疏点标为噪声，但对 eps 敏感，难以处理密度差异大的数据；高斯混合允许椭圆形簇并给出软分配概率，代价是参数更多、更依赖初始化。scikit-learn 聚类文档有一张按簇形状、规模和参数对比各算法的总表。"
        },
        {
          "q": "t-SNE 图里两个簇离得很远，说明它们差别很大吗？",
          "a": "不一定。Distill 上 Wattenberg 等（2016）的交互文章用合成数据演示：t-SNE 图中簇的大小没有意义，簇间距离也可能没有意义，随机噪声有时会呈现出看似有结构的图案，结果还随 perplexity 明显变化。解读前应尝试多个 perplexity 和随机种子，并用 PCA 或原空间距离复核。"
        },
        {
          "q": "PCA 和自编码器是什么关系？",
          "a": "PCA 是线性降维：编码是投影到前 k 个主成分，解码是投影回原空间，在所有 k 维线性投影中重建平方误差最小。自编码器用神经网络做编码和解码，可以学习非线性的低维表示；Hinton 与 Salakhutdinov（2006）在 Science 上展示了深层自编码器在降维上优于 PCA 的例子。"
        },
        {
          "q": "大模型时代还需要学这些经典方法吗？",
          "a": "需要。文本或图像的嵌入向量本身就是高维数据，常见流程是“嵌入 → 降维 → 聚类 → 人工命名”。例如 BERTopic（Grootendorst，2022）先用预训练模型生成文档嵌入，用 UMAP 降维，再用 HDBSCAN 聚类，最后用基于类的 TF-IDF 为每个簇提取主题词。检查训练数据分布、发现重复样本、分析用户问题类型都会用到同样的方法。"
        }
      ],
      "sources": [
        {
          "title": "scikit-learn 用户指南：2.3 Clustering（含各算法对比与聚类评估指标）",
          "url": "https://scikit-learn.org/stable/modules/clustering.html"
        },
        {
          "title": "scikit-learn 用户指南：2.1 Gaussian mixture models",
          "url": "https://scikit-learn.org/stable/modules/mixture.html"
        },
        {
          "title": "scikit-learn 用户指南：2.5 Decomposing signals in components（PCA 等）",
          "url": "https://scikit-learn.org/stable/modules/decomposition.html"
        },
        {
          "title": "scikit-learn 用户指南：2.2 Manifold learning（t-SNE 等）",
          "url": "https://scikit-learn.org/stable/modules/manifold.html"
        },
        {
          "title": "scikit-learn API 文档：sklearn.cluster.KMeans",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html"
        },
        {
          "title": "UMAP 官方文档（umap-learn）",
          "url": "https://umap-learn.readthedocs.io/en/latest/"
        },
        {
          "title": "Wattenberg、Viégas、Johnson（2016），How to Use t-SNE Effectively，Distill",
          "url": "https://distill.pub/2016/misread-tsne/"
        },
        {
          "title": "Deisenroth、Faisal、Ong：Mathematics for Machine Learning（官方免费版，第 10 章 PCA、第 11 章高斯混合模型）",
          "url": "https://mml-book.github.io/"
        },
        {
          "title": "Lloyd（1982），Least Squares Quantization in PCM，IEEE Transactions on Information Theory",
          "url": "https://doi.org/10.1109/TIT.1982.1056489"
        },
        {
          "title": "Arthur、Vassilvitskii（2007），k-means++: The Advantages of Careful Seeding（作者公开 PDF）",
          "url": "https://theory.stanford.edu/~sergei/papers/kMeansPP-soda.pdf"
        },
        {
          "title": "Ester、Kriegel、Sander、Xu（1996），A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise，KDD-96",
          "url": "https://cdn.aaai.org/KDD/1996/KDD96-037.pdf"
        },
        {
          "title": "Dempster、Laird、Rubin（1977），Maximum Likelihood from Incomplete Data via the EM Algorithm",
          "url": "https://doi.org/10.1111/j.2517-6161.1977.tb01600.x"
        },
        {
          "title": "Pearson（1901），On Lines and Planes of Closest Fit to Systems of Points in Space",
          "url": "https://doi.org/10.1080/14786440109462720"
        },
        {
          "title": "Hotelling（1933），Analysis of a Complex of Statistical Variables into Principal Components",
          "url": "https://doi.org/10.1037/h0071325"
        },
        {
          "title": "van der Maaten、Hinton（2008），Visualizing Data using t-SNE，JMLR 9",
          "url": "https://www.jmlr.org/papers/v9/vandermaaten08a.html"
        },
        {
          "title": "McInnes、Healy、Melville（2018），UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction",
          "url": "https://arxiv.org/abs/1802.03426"
        },
        {
          "title": "Rousseeuw（1987），Silhouettes: A Graphical Aid to the Interpretation and Validation of Cluster Analysis",
          "url": "https://doi.org/10.1016/0377-0427(87)90125-7"
        },
        {
          "title": "Hubert、Arabie（1985），Comparing Partitions，Journal of Classification",
          "url": "https://link.springer.com/article/10.1007/BF01908075"
        },
        {
          "title": "Kobak、Berens（2019），The Art of Using t-SNE for Single-Cell Transcriptomics，Nature Communications",
          "url": "https://doi.org/10.1038/s41467-019-13056-x"
        },
        {
          "title": "Hinton、Salakhutdinov（2006），Reducing the Dimensionality of Data with Neural Networks，Science",
          "url": "https://doi.org/10.1126/science.1127647"
        },
        {
          "title": "Grootendorst（2022），BERTopic: Neural Topic Modeling with a Class-based TF-IDF Procedure",
          "url": "https://arxiv.org/abs/2203.05794"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/math-ml/unsupervised-learning/",
      "markdown": "**概要**：监督学习从带标签的样本学习输入到输出的映射；无监督学习只有输入，要回答的是“数据里有哪些自然的分组”“能否用更少的维度描述它”“数据服从什么分布”。本课按“k-means → 密度聚类 → 高斯混合与 EM → PCA → t-SNE 与 UMAP → 聚类评估”的顺序展开，所有数字均来自文末可运行示例。\n\n本课属于[无监督学习：聚类、降维与 EM](/learn/unit/u23-unsupervised)单元，前置为[过拟合、泛化与数据划分](/learn/generalization)与[线性代数](/learn/linear-algebra)，EM 一节会用到[概率、统计与信息论](/learn/probability-information)中的最大似然。后续可接[神经网络与反向传播](/learn/neural-networks)和 [Token 与 Embedding](/learn/tokens-embeddings)。相关算法卡：[K 均值聚类](/learn/algorithms/kmeans)、[DBSCAN](/learn/algorithms/dbscan)、[EM 算法](/learn/algorithms/em)、[主成分分析](/learn/algorithms/pca)、[t-SNE](/learn/algorithms/tsne)、[UMAP](/learn/algorithms/umap)、[自编码器](/learn/algorithms/autoencoder)。\n\n## 无监督学习解决什么问题\n\n| 任务 | 输出 | 典型方法 | 在大模型工作中的例子 |\n|---|---|---|---|\n| 聚类 | 每个样本的簇编号（或属于各簇的概率） | k-means、DBSCAN、高斯混合 | 把用户提问按主题分组，发现训练数据中的重复或异常样本 |\n| 降维 | 每个样本的低维坐标 | PCA、t-SNE、UMAP、自编码器 | 把 768 维或更高维的嵌入画成二维图，压缩特征 |\n| 密度估计 | 数据的概率分布 p(x) | 高斯混合、核密度估计 | 异常检测：概率很低的样本可能是离群点 |\n\n无监督方法没有“正确答案”可对照，因此本课最后一节专门讨论如何评估结果。\n\n## k-means 与 k-means++\n\nk-means 把 n 个点分成 k 组，目标是让每个点到所属簇中心的平方距离之和最小，这个量称为惯量（inertia）或簇内平方和：\n\n```text\n目标   J = Σᵢ ‖xᵢ − μ_c(i)‖²        c(i) 是点 i 所属的簇，μ_c 是簇 c 的中心\n步骤   1. 分配：每个点分给距离最近的中心\n       2. 更新：每个中心移到其所属点的均值\n       重复 1–2，直到分配不再变化\n```\n\n这一迭代通常称为 Lloyd 算法（Lloyd，1982 年正式发表）。两步都不会增加 J，所以算法一定收敛，但只能保证局部最优：Arthur 与 Vassilvitskii（2007）在论文开头指出，精确求解这个目标是 NP 困难的，即使只有两个簇。\n\n初始化因此很重要。**k-means++** 的做法是：第一个中心随机选一个样本，之后每个新中心按“到已选中心最近距离的平方”成比例地抽样，离现有中心越远的点越容易被选中。作者证明这样得到的期望目标值与最优解相差 Θ(log k) 倍以内。本课示例在手写数字数据（1797 个样本、64 维）上各跑 20 个随机种子、每次只初始化一次：随机初始化的惯量均值 1,189,680、最差 1,240,658；k-means++ 的均值 1,178,526、最差 1,218,629。\n\nscikit-learn 的 `KMeans` 默认使用 k-means++；自 1.4 版起 `n_init` 默认为 `'auto'`，此时 k-means++ 只运行 1 次，随机初始化运行 10 次，取惯量最小的结果。\n\nk-means 的隐含假设是簇大致呈凸形、大小相近，且所有特征的尺度可比。实际使用前通常要标准化特征；对文本嵌入则常先做 L2 归一化，使欧氏距离与余弦相似度单调对应。\n\n## DBSCAN：按密度聚类\n\nEster 等（1996）提出的 DBSCAN 不需要预先指定簇数，而是用两个参数定义“稠密”：半径 eps 与最少点数 min_samples。\n\n- **核心点**：eps 邻域内至少有 min_samples 个点；\n- **边界点**：不是核心点，但落在某个核心点的邻域内；\n- **噪声点**：既不是核心点也不在任何核心点邻域内，标签为 −1。\n\n彼此密度可达的核心点及其边界点构成一个簇，因此簇可以是任意形状。示例用两个交错的半月形（500 个点）对比：k-means（k=2）的调整兰德指数（ARI，见最后一节）只有 0.257，因为它只能用一条直线把平面一分为二；DBSCAN（eps=0.2、min_samples=5）的 ARI 为 1.000，恰好找到 2 个簇且没有噪声点。DBSCAN 的局限是对 eps 敏感，且难以同时处理密度差别很大的簇；HDBSCAN 把它扩展为层次化版本以应对不同密度，scikit-learn 自 1.3 版起提供 `HDBSCAN`。\n\n## 高斯混合模型与 EM 算法\n\nk-means 给每个点一个确定的簇（硬分配）。**高斯混合模型**（GMM）假设数据由 K 个高斯分布按权重 π₁…π_K 混合生成：\n\n```text\np(x) = Σₖ πₖ · N(x | μₖ, Σₖ)          Σₖ πₖ = 1\n```\n\n每个点属于第 k 个成分的后验概率称为“责任度” rᵢₖ，这是软分配。参数 θ = {πₖ, μₖ, Σₖ} 用最大似然估计，但“每个点来自哪个成分”是未观测的隐变量，直接求解困难。Dempster、Laird 与 Rubin（1977）系统化的 **EM 算法**交替执行两步：\n\n```text\nE 步   rᵢₖ = πₖ · N(xᵢ | μₖ, Σₖ) / Σⱼ πⱼ · N(xᵢ | μⱼ, Σⱼ)       按当前参数计算责任度\nM 步   Nₖ = Σᵢ rᵢₖ\n       πₖ = Nₖ / n\n       μₖ = Σᵢ rᵢₖ · xᵢ / Nₖ\n       Σₖ = Σᵢ rᵢₖ · (xᵢ − μₖ)(xᵢ − μₖ)ᵀ / Nₖ                   按责任度加权更新参数\n```\n\n论文证明每一轮迭代都不会降低观测数据的对数似然，但与 k-means 一样只保证收敛到局部极值。示例用 NumPy 手写一维两成分 EM：数据由 N(−2, 0.8²) 与 N(3, 1.2²) 按 3:7 混合生成，50 轮后对数似然从 −3604.4 升到 −2034.5，全程单调不减，估计结果为 π = (0.303, 0.697)、μ = (−2.02, 2.955)、σ = (0.815, 1.117)。\n\nk-means 可以看作 GMM 的特例：当所有成分共用一个趋近于 0 的球形协方差时，责任度退化为 0 或 1，E 步变成“分给最近中心”，M 步变成“取均值”。\n\nGMM 的成分数可以用 **BIC**（贝叶斯信息准则）选择，它在负对数似然上加一项随参数个数增长的惩罚，值越低越好。示例先用 PCA 把手写数字降到 20 维，再拟合全协方差 GMM：成分数取 6、8、10、12、14、16 时，BIC 在 10 时最低（213,941），这个 GMM 与真实数字标签的 ARI 为 0.842，高于直接在 64 维上做 k-means 的 0.666。\n\n## 主成分分析（PCA）\n\nPCA 寻找一组正交方向，使数据在第一个方向上的方差最大，第二个方向在与第一个正交的前提下方差最大，依此类推。这一思想可追溯到 Pearson（1901）的“最佳拟合直线与平面”和 Hotelling（1933）的主成分分析。\n\n```text\n1. 中心化：X̃ = X − 均值\n2. SVD：X̃ = U · S · Vᵀ\n3. 主成分方向 = V 的前 k 列；第 j 个成分的方差 = sⱼ² / (n − 1)\n4. 降维坐标 = X̃ · V_k；解释方差比 = sⱼ² / Σ s²\n```\n\nPCA 有两种等价的理解：最大化投影后的方差，或最小化投影回原空间后的重建平方误差。后者正是[线性代数](/learn/linear-algebra)一课中 Eckart–Young 定理的应用。示例中手写数字的前 2 个主成分只解释 28.5% 的方差，要达到 90% 需要 21 个主成分，说明二维 PCA 图会丢失大量信息。\n\nPCA 的用途包括：可视化前的初步降维（t-SNE 与 UMAP 常先用 PCA 降到几十维）、去噪与压缩、去除特征间的线性相关。它的局限是只能捕捉线性结构，且对特征尺度敏感，使用前通常要标准化。\n\n## t-SNE 与 UMAP：非线性可视化\n\n**t-SNE**（van der Maaten 与 Hinton，2008）把高维空间中点对的相似度转成概率，再在二维或三维中寻找一组坐标，使低维相似度分布与高维分布的 KL 散度最小。它在低维空间使用重尾的 Student-t 分布，以缓解高维点挤到低维时的“拥挤问题”。最重要的参数 perplexity 大致对应每个点考虑的有效近邻数，原论文给出的典型取值为 5–50。\n\n**UMAP**（McInnes 等，2018）基于流形假设与模糊拓扑构造近邻图，再优化低维布局。作者在摘要中称其可视化质量与 t-SNE 相当，可以说保留了更多全局结构，并且运行更快；与 t-SNE 不同，UMAP 可以对新样本调用 `transform`。主要参数是 `n_neighbors`（越大越关注全局结构）和 `min_dist`（控制低维中点的最小间距）。\n\n两者都擅长保留局部邻域。示例用可信度（trustworthiness，k=5，衡量低维近邻在高维中是否也是近邻，最大为 1）比较手写数字的二维嵌入：PCA 0.830，t-SNE 0.995，UMAP 0.990。\n\n解读这类图时必须注意以下几点，均来自 Distill 文章《How to Use t-SNE Effectively》（Wattenberg 等，2016）的合成数据实验：\n\n1. **超参数影响很大**：同一份数据在不同 perplexity 下可能呈现完全不同的形状，应比较多组设置。\n2. **簇的大小没有意义**：t-SNE 会把稠密簇拉开、稀疏簇压紧。\n3. **簇间距离不一定有意义**：相距很远的两个簇不一定比相距较近的两个簇差别更大。\n4. **随机噪声也可能呈现结构**：看到“小团块”不代表数据真有这些分组。\n\nKobak 与 Berens（2019）针对单细胞数据总结了改进 t-SNE 全局结构的做法，其中包括用 PCA 初始化；scikit-learn 的 `TSNE` 自 1.2 版起默认 `init=\"pca\"`。可视化只用于形成假设，聚类结论应在原空间或 PCA 空间中复核。\n\n## 聚类结果怎样评估\n\n| 指标 | 是否需要真实标签 | 含义 | 来源 |\n|---|---|---|---|\n| 惯量（簇内平方和） | 否 | 越小越紧凑，但随 k 增大必然下降，只能看“肘部” | k-means 目标函数 |\n| 轮廓系数 | 否 | 每个点 s = (b − a) / max(a, b)，a 为到同簇点的平均距离，b 为到最近其他簇的平均距离；取值 −1 到 1，越大越好 | Rousseeuw（1987） |\n| BIC | 否（需概率模型） | 对数似然减去参数个数惩罚，用于比较 GMM 成分数，越低越好 | scikit-learn 高斯混合文档 |\n| 调整兰德指数（ARI） | 是 | 衡量两种划分的一致程度并校正随机一致；随机划分约为 0，完全一致为 1 | Hubert 与 Arabie（1985） |\n\n示例中，在手写数字上对 k = 5、8、10、12、15 计算轮廓系数，得到 0.138、0.178、0.183、0.185、0.174：最高值出现在 k=12 而不是真实类别数 10，且各值都不高。这说明内部指标只反映几何上的紧凑与分离，不一定对应人关心的类别。实际项目中，ARI 只能在有部分标注时使用；最终判断往往还要从每个簇里抽样查看，并为簇命名。\n\n## 可运行示例\n\n以下代码在 scikit-learn 1.9、NumPy 2.5、umap-learn 0.6 上实测，输出与上文数字一致（t-SNE 与 UMAP 的结果随版本和线程数可能有小幅差异）。\n\n```python\nimport numpy as np\nfrom sklearn.datasets import load_digits, make_moons\nfrom sklearn.cluster import KMeans, DBSCAN\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE, trustworthiness\nfrom sklearn.metrics import adjusted_rand_score as ari, silhouette_score\n\nX, y = load_digits(return_X_y=True)          # 1797 张 8×8 手写数字，64 维\n\n# 1) 随机初始化与 k-means++：各 20 个种子、每次只初始化 1 次\nfor init in (\"random\", \"k-means++\"):\n    inert = [KMeans(10, init=init, n_init=1, random_state=s).fit(X).inertia_ for s in range(20)]\n    print(f\"{init:10s} 惯量 均值 {np.mean(inert):.0f}  最差 {np.max(inert):.0f}\")\nkm = KMeans(10, n_init=10, random_state=0).fit(X)\nprint(f\"k-means ARI = {ari(y, km.labels_):.3f}\")\n\n# 2) 轮廓系数\nfor k in (5, 8, 10, 12, 15):\n    lab = KMeans(k, n_init=10, random_state=0).fit_predict(X)\n    print(f\"k={k:2d} 轮廓系数 {silhouette_score(X, lab):.3f}\")\n\n# 3) PCA 解释方差\ncum = np.cumsum(PCA().fit(X).explained_variance_ratio_)\nprint(f\"前 2 个主成分 {cum[1]:.3f}；达到 90% 需要 {np.searchsorted(cum, 0.90) + 1} 个\")\n\n# 4) 高斯混合 + BIC（先降到 20 维）\nZ = PCA(20, random_state=0).fit_transform(X)\nfor n in (6, 8, 10, 12, 14, 16):\n    print(n, round(GaussianMixture(n, covariance_type=\"full\", random_state=0).fit(Z).bic(Z)))\ng = GaussianMixture(10, covariance_type=\"full\", random_state=0).fit(Z)\nprint(f\"GMM(10) ARI = {ari(y, g.predict(Z)):.3f}\")\n\n# 5) 非凸簇：k-means 与 DBSCAN\nM, ym = make_moons(500, noise=0.05, random_state=0)\nprint(\"k-means ARI\", round(ari(ym, KMeans(2, n_init=10, random_state=0).fit_predict(M)), 3))\nprint(\"DBSCAN  ARI\", round(ari(ym, DBSCAN(eps=0.2, min_samples=5).fit_predict(M)), 3))\n\n# 6) 二维嵌入的邻域保持\nP2 = PCA(2, random_state=0).fit_transform(X)\nT2 = TSNE(2, perplexity=30, random_state=0).fit_transform(X)\nprint(f\"可信度 PCA {trustworthiness(X, P2, n_neighbors=5):.3f}  t-SNE {trustworthiness(X, T2, n_neighbors=5):.3f}\")\n# UMAP：import umap; umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=0).fit_transform(X)\n\n# 7) 手写 EM：一维两成分高斯混合\nrng = np.random.default_rng(0)\nx = np.concatenate([rng.normal(-2, 0.8, 300), rng.normal(3, 1.2, 700)])\npi, mu, var = np.array([0.5, 0.5]), np.array([-1.0, 1.0]), np.array([1.0, 1.0])\nll = []\nfor _ in range(50):\n    p = pi * np.exp(-(x[:, None] - mu) ** 2 / (2 * var)) / np.sqrt(2 * np.pi * var)\n    ll.append(np.log(p.sum(1)).sum())\n    r = p / p.sum(1, keepdims=True)                       # E 步：责任度\n    nk = r.sum(0); pi = nk / len(x)                       # M 步：加权更新\n    mu = (r * x[:, None]).sum(0) / nk\n    var = (r * (x[:, None] - mu) ** 2).sum(0) / nk\nprint(f\"对数似然 {ll[0]:.1f} → {ll[-1]:.1f}，单调不减 {bool(np.all(np.diff(ll) >= -1e-9))}\")\nprint(\"π\", pi.round(3), \"μ\", mu.round(3), \"σ\", np.sqrt(var).round(3))\n```\n\n实测输出要点：随机初始化惯量均值 1,189,680、最差 1,240,658，k-means++ 均值 1,178,526、最差 1,218,629；k-means ARI 0.666；轮廓系数 0.138 / 0.178 / 0.183 / 0.185 / 0.174；前 2 个主成分解释 28.5% 方差，90% 需要 21 个；BIC 在 10 个成分时最低（213,941），GMM ARI 0.842；半月形数据 k-means ARI 0.257、DBSCAN ARI 1.000；可信度 PCA 0.830、t-SNE 0.995、UMAP 0.990；EM 对数似然 −3604.4 → −2034.5。\n\n## 动手练习\n\n1. **单元项目**：取 1000 条句子，用任一开源句向量模型生成嵌入并做 L2 归一化；用 k-means 聚类，用 UMAP 画成二维图，从每个簇抽 10 条句子人工命名，再比较 k 取不同值时命名是否仍然合理。\n2. 在 [scikit-learn 官方示例库](https://scikit-learn.org/stable/auto_examples/index.html)中找到聚类算法对比示例，对同一组数据比较 k-means、DBSCAN 与高斯混合的结果，并改变 DBSCAN 的 eps 观察簇数变化。\n3. 跑 [Mathematics for Machine Learning 配套仓库](https://github.com/mml-book/mml-book.github.io)中的 PCA 与高斯混合模型 Notebook，对照本课公式自己推一遍 EM 的 M 步。\n4. 在 [Distill 的 t-SNE 交互文章](https://distill.pub/2016/misread-tsne/)中，把 perplexity 分别调到 2、30、100，记录同一份数据的图形变化。\n\n## 推荐学习顺序\n\n先读 [scikit-learn 聚类指南](https://scikit-learn.org/stable/modules/clustering.html)开头的算法对比图和“聚类性能评估”一节，建立整体印象；数学推导读 [Mathematics for Machine Learning](https://mml-book.github.io/) 第 10 章（PCA）与第 11 章（高斯混合模型与 EM）；可视化部分先读 [Distill 的 t-SNE 文章](https://distill.pub/2016/misread-tsne/)，再读 [UMAP 官方文档](https://umap-learn.readthedocs.io/en/latest/)中关于参数和聚类的章节。之后进入[神经网络与反向传播](/learn/neural-networks)，自编码器会把本课的降维思想推广到非线性。"
    }
  }
}