AI Wiki中文/EN

Unsupervised learning: patterns need a purpose

无监督学习

Compare exact unlabeled mixture fits and see why identical observable distributions can imply different hidden memberships.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Finding a pattern is not naming its cause

A workshop records two binary indicator lights, A and B. Eight observations contain three 00 pairs, one 01, one 10 and three 11. The lights agree more often than they disagree. We can study that pattern without a column saying which machine mode produced each row.

That is the starting point of unsupervised learning: the fitting objective uses observations without supplied target labels. It still needs an objective, a model family and choices about what to preserve. “Let the data speak” does not specify any of those choices.

Different questions lead to different outputs:

QuestionOutputA useful check
Which records should be grouped together?A partition, overlapping groups or a hierarchyStability and agreement with a justified similarity measure; external classes when available
Which information should a compact code retain?A representation or embeddingReconstruction under a stated distortion, retrieval or a separately evaluated downstream task
Which observations are probable?A probability mass or density modelPredictive log likelihood on held-out observations
Which records deserve inspection?An anomaly ranking or decision regionFalse alarms and missed events against the operational task

There is no universal “unsupervised accuracy.” A representation can reconstruct every pixel while preserving background rather than the object of interest. A tidy partition can separate recording devices rather than machine modes. The clustering guide distinguishes external partition comparisons from internal geometric criteria; neither assigns a scientific meaning to a cluster number.

Three explanations with exactly the same observations

We will compare finite mixture models for the two lights. A latent variable Z chooses a component with probability πⱼ. Within that component, A and B are independent Bernoulli variables with success probabilities aⱼ and bⱼ. They need not be independent after mixing. Write B(p,u) = p when u = 1, and 1−p when u = 0:

pθ(u,v)=∑j=0J−1πjB(aj,u)B(bj,v),πj≥0,∑jπj=1.p_\theta(u,v)=\sum_{j=0}^{J-1}\pi_j B(a_j,u)B(b_j,v), \qquad \pi_j\ge0,\quad\sum_j\pi_j=1.

This separates a model of observations from a model of hidden memberships. Under a chosen model, Bayes’ rule gives:

Pθ(Z=j∣A=u,B=v)=πjB(aj,u)B(bj,v)pθ(u,v),pθ(u,v)>0.P_\theta(Z=j\mid A=u,B=v) =\frac{\pi_j B(a_j,u)B(b_j,v)}{p_\theta(u,v)}, \qquad p_\theta(u,v)>0.

A zero denominator means the model excludes the observation. The conditional distribution is undefined there; our program returns None.

Here are three original models. Each has two equally weighted components. The entries are the pairs (aⱼ, bⱼ), not observed data labels.

ModelComponent 0Component 1
A-groups(0, 1/4)(1, 3/4)
B-groups(1/4, 0)(3/4, 1)
soft-groups(1/6, 1/8)(5/6, 7/8)

In A-groups, Z equals A. In B-groups, it equals B. In soft-groups, neither light determines Z. All three nevertheless give:

(p(0,0),p(0,1),p(1,0),p(1,1))=(38,18,18,38),P(Z=1∣1,0)∈{1,0,512}.\bigl(p(0,0),p(0,1),p(1,0),p(1,1)\bigr) =\left(\frac38,\frac18,\frac18,\frac38\right), \qquad P(Z=1\mid1,0)\in\left\{1,0,\frac5{12}\right\}.

For example, the soft model assigns joint mass (1/2)(5/6)(1/8) = 5/96 to component 1 and observation 10. Dividing by its observable mass 1/8 gives 5/12. Its other component supplies the remaining 7/12.

This is nonidentifiability of the hidden explanation from the observations. Even the exact population distribution of the two lights cannot distinguish these models. Any procedure given only IID pairs has the same input distribution under all three explanations. It cannot be guaranteed to select the true hidden explanation in each of them.

This ambiguity goes beyond renaming components. Across 00, 01, 10, 11, A-groups assigns component-1 probabilities (0, 0, 1, 1), while B-groups gives (0, 1, 0, 1). Neither that vector nor its complement equals the A-groups vector. More unlabeled observations of the same two variables cannot resolve the difference.

A finite counterexample is enough to refute a universal recovery promise; it does not establish that every latent model is unidentifiable. Locatello and colleagues’ 2019 paper, §3 studies a different setting: continuous latent variables with factorized densities and arbitrary generative models. Its theorem identifies an ambiguity in recovering disentangled coordinates without suitable assumptions. Our binary mixture calculation is a separate construction, not an implementation of that theorem.

Select a model while keeping its unresolved ties

The complete Python 3.10+ program below selects among a supplied finite set of candidate mixtures. It does not run EM or optimize over all mixture parameters. A fourth candidate treats both lights as independent fair bits.

For counts cᵤᵥ, maximizing the likelihood is equivalent to maximizing the log likelihood when it is positive:

L(θ)=∏u,vpθ(u,v)cuv,log⁡L(θ)=∑u,v:cuv>0cuvlog⁡pθ(u,v).\mathcal L(\theta)=\prod_{u,v}p_\theta(u,v)^{c_{uv}}, \qquad \log\mathcal L(\theta)=\sum_{u,v:c_{uv}>0}c_{uv}\log p_\theta(u,v).

This is the likelihood of any particular ordered observation sequence with those counts. The probability of the unordered count table additionally includes a multinomial coefficient, common to all candidates and irrelevant to their ranking. Zero-count cells are omitted. If an observed cell has probability zero, the candidate likelihood is zero and its log likelihood is −∞.

Training rows are (A, B, count), with integer bits and nonnegative integer counts. Duplicate rows are combined; the total count must be positive. Mixture weights and probabilities must be integers or Fraction values in [0,1], with nonempty components and weights summing to one. Zero-weight components are allowed. Names must be unique nonblank strings. Booleans and floating-point probabilities are rejected.

All positive-likelihood maximizers are returned in candidate order. When every likelihood is zero, the mathematical argmax still contains tied candidates, but each rules out the data. The program reports incompatible and no usable winner. It does not invent a posterior or silently favor the first name.

Let L be the raw input length, including a constant 1, table rows, components and names; K the number of candidates; and n the total count. With constant-cost arithmetic and ordinary hash lookups, fitting costs O(L + K log(n+1)) operations: each candidate evaluates four cells and at most four integer powers. It stores O(L + K) values, including validated components and reports. One posterior query with J components uses O(J+1) operations and space. Exact fraction bit costs grow with the integers, especially likelihood powers; the program is a small audit experiment, not a large-data numerical implementation.

from fractions import Fraction as F
from math import prod

PATTERNS = ((0, 0), (0, 1), (1, 0), (1, 1))


def sequence(value):
    if not isinstance(value, (tuple, list)):
        raise ValueError('expected a list or tuple')
    return value


def probability(value):
    if isinstance(value, bool) or not isinstance(value, (int, F)):
        raise ValueError('probabilities must be integers or Fraction values')
    value = F(value)
    if not 0 <= value <= 1:
        raise ValueError('probability outside [0,1]')
    return value


def pattern(value):
    value = sequence(value)
    if len(value) != 2 or any(type(v) is not int or v not in (0, 1) for v in value):
        raise ValueError('expected two integer bits')
    return tuple(value)


def mixture(components):
    result = []
    for component in sequence(components):
        component = sequence(component)
        if len(component) != 3:
            raise ValueError('component is (weight, probability_A, probability_B)')
        result.append(tuple(probability(v) for v in component))
    if not result or sum(c[0] for c in result) != 1:
        raise ValueError('need nonempty components whose weights sum to one')
    return tuple(result)


def joint_parts(components, observed):
    a, b = observed
    return tuple(weight * (pa if a else 1-pa) * (pb if b else 1-pb)
                 for weight, pa, pb in components)


def distribution(components):
    components = mixture(components)
    return tuple(sum(joint_parts(components, observed), F(0)) for observed in PATTERNS)


def posterior(components, observed):
    components, observed = mixture(components), pattern(observed)
    parts = joint_parts(components, observed)
    total = sum(parts, F(0))
    return None if total == 0 else tuple(p / total for p in parts)


def fit_candidates(table, candidates):
    counts = dict.fromkeys(PATTERNS, 0)
    for row in sequence(table):
        row = sequence(row)
        if len(row) != 3:
            raise ValueError('table rows are (A, B, count)')
        observed, count = pattern(row[:2]), row[2]
        if type(count) is not int or count < 0:
            raise ValueError('counts must be nonnegative integers')
        counts[observed] += count
    n = sum(counts.values())
    if n == 0:
        raise ValueError('need at least one observation')
    reports, names = [], set()
    for candidate in sequence(candidates):
        candidate = sequence(candidate)
        if len(candidate) != 2:
            raise ValueError('candidate is (unique name, components)')
        name, components = candidate
        if not isinstance(name, str) or not name.strip() or name in names:
            raise ValueError('need unique nonblank candidate names')
        names.add(name)
        components = mixture(components)
        masses = distribution(components)
        likelihood = prod((p ** counts[x] for x, p in zip(PATTERNS, masses)
                           if counts[x] > 0), start=F(1))
        reports.append({'name': name, 'components': components,
                        'mass': masses, 'likelihood': likelihood})
    if not reports:
        raise ValueError('need at least one candidate')
    best = max(r['likelihood'] for r in reports)
    winners = tuple(r['name'] for r in reports if r['likelihood'] == best) if best else ()
    return {'n': n, 'counts': tuple(counts[x] for x in PATTERNS),
            'status': 'fitted' if best else 'incompatible',
            'winners': winners, 'reports': tuple(reports)}


def demo_candidates():
    return (
        ('A-groups', ((F(1, 2), 0, F(1, 4)), (F(1, 2), 1, F(3, 4)))),
        ('B-groups', ((F(1, 2), F(1, 4), 0), (F(1, 2), F(3, 4), 1))),
        ('soft-groups', ((F(1, 2), F(1, 6), F(1, 8)),
                         (F(1, 2), F(5, 6), F(7, 8)))),
        ('independent', ((1, F(1, 2), F(1, 2)),)),
    )


if __name__ == '__main__':
    candidates = demo_candidates()
    table = ((0, 0, 3), (0, 1, 1), (1, 0, 1), (1, 1, 3))
    report = fit_candidates(table, candidates)
    print('observations, status:', report['n'], report['status'])
    print('winners:', report['winners'])
    for row in report['reports']:
        print(row['name'], 'mass:', tuple(map(str, row['mass'])),
              'likelihood:', str(row['likelihood']))
    print('component 1 at (1,0):', tuple(str(posterior(c, (1, 0))[1])
                                       for _, c in candidates[:3]))
    print('likelihood ratio:', report['reports'][0]['likelihood'] /
          report['reports'][3]['likelihood'])

Actual output:

observations, status: 8 fitted
winners: ('A-groups', 'B-groups', 'soft-groups')
A-groups mass: ('3/8', '1/8', '1/8', '3/8') likelihood: 729/16777216
B-groups mass: ('3/8', '1/8', '1/8', '3/8') likelihood: 729/16777216
soft-groups mass: ('3/8', '1/8', '1/8', '3/8') likelihood: 729/16777216
independent mass: ('1/4', '1/4', '1/4', '1/4') likelihood: 1/65536
component 1 at (1,0): ('1', '0', '5/12')
likelihood ratio: 729/256

The three mixture explanations beat the fixed independent candidate on this table by a likelihood ratio of 729/256. This is neither a posterior probability that one model is true nor a measure of future accuracy. Changing the table can change which candidates win. Within this candidate set, however, no table can separate the first three: they agree on every observable cell.

The tests check likelihoods by a different calculation: enumerate all complete latent-component assignments to a short observation sequence, compute each joint probability and sum them. Binary moment inversion independently recovers the four observable masses. Both checks use exact arithmetic.

Evaluate the job the representation will do

Unlabeled training does not forbid labeled evaluation. If the intended use is sorting observations by verified operating mode, obtain a separately evaluated set with that information. If the use is probability prediction, test predictive probability. If the use is inspection, measure whether the ranking helps reviewers find consequential events. Reporting one of these results does not establish the others.

Internal clustering scores depend on geometry. Silhouette compares within-group and between-group distances; it cannot check whether a group corresponds to a failure mechanism. External scores such as adjusted Rand compare partitions while ignoring arbitrary label permutations. Use them only with a meaningful reference partition, and retain the distinction between choosing a model with labels and assessing a previously chosen model with labels. These are different information flows. The fixed clustering documentation explains both score families.

Model choices enter before optimization: which sensor variables to collect, which distances to use, which features to scale, which transformations a representation should ignore, and which latent dependencies to permit. Self-supervised methods create prediction targets from the data itself; this describes a training signal and should not be confused with access to externally supplied semantic classes. A system that also uses labeled training examples has a different supervision contract, even if most of its data are unlabeled.

Preserve a final evaluation set when selecting features, candidate counts or hyperparameters. Unsupervised preprocessing can still leak test information if it is fitted on the test set. If the intended task is explicitly transductive—organizing this fixed observed collection—say so, rather than implying that every method automatically supplies a prediction rule for new records.

In the workshop example, a documented relationship between a hidden mode and a light could exclude a candidate. Additional measurements, grouping information or interventions may also help when they constrain the competing models differently. Merely attaching a plausible name to component 1 adds no evidence. The example establishes a limit on one information source, not a reason to abandon learning without labels.

Separate fit, membership and meaning

1. Recompute the likelihood ratio.

Answer: Each of the first three candidates assigns 3/8 to each agreeing pair and 1/8 to each disagreeing pair. The eight-record likelihood is (3/8)^6(1/8)^2 = 729/16777216. The fair independent model gives (1/4)^8 = 1/65536. Their ratio is 729/256. No claim about the true hidden component follows from that comparison.

2. Would an unlimited held-out set of light pairs distinguish the three mixtures?

Answer: No. They agree on all four possible observable pairs, so they give identical probabilities to every IID sequence and identical predictive log likelihoods. Their posteriors for component 1 at 10 are still 1, 0 and 5/12. Resolving this disagreement requires constraints or information beyond this observable distribution.

3. Is this merely the usual ambiguity of cluster numbers?

Answer: No. A-groups gives (0,0,1,1) across the four patterns. B-groups gives (0,1,0,1); swapping its two component numbers gives (1,0,1,0). Neither equals A-groups. Ordinary label switching preserves the same partition with different names; this example changes the hidden assignment itself.

4. What should happen when every candidate excludes an observed pair?

Answer: A sole component (weight=1, a=0, b=0) assigns zero probability to 11. A table containing that pair therefore has likelihood zero under this candidate. With no compatible alternative, the program returns incompatible and an empty winner tuple. Asking for its posterior at 11 returns None, since conditioning on a zero-probability event is undefined in this finite model.

Assumptions make an unsupervised question answerable

Mixture models connect density estimation and uncertain membership. The Gaussian mixture guide describes fitting unknown mixture parameters with EM and choosing structural constraints. The shared idea is to sum over a hidden component; Gaussian observations, covariance estimation and iterative fitting are additional machinery absent from our binary candidate selector. A likelihood objective must be read together with its permitted model family.

Locatello et al. distinguish matching an observed distribution from recovering particular latent factors. Their argument makes the need for inductive assumptions explicit. It does not say that every embedding is useless or that every useful assumption must take the form of a class label.

The next branch depends on the task: k-means for one geometric partition objective, Gaussian mixtures for probabilistic components, representation learning for learned codes, and one-class SVM for a fitted decision region. In each case, write down the output you need and the evidence that would make it useful before treating an attractive pattern as an explanation.

Make a prediction, then check

Three models agree on every observable light pair but disagree on hidden membership. Can more IID observations of the same two lights identify the true membership model?

Choose one answer

Learning objectives

  • Choose an unsupervised objective and evaluation protocol for clustering, representations, probability prediction or inspection.
  • Separate observable fit, latent membership and externally justified semantic meaning.
  • Run a finite exact mixture comparison and prove its hidden nonidentifiability exceeds mere label switching.

Prerequisites & connections

Explore related knowledge →

References

  1. Challenging Common Assumptions in the Unsupervised Learning of Disentangled Representations
    Francesco Locatello; Stefan Bauer; Mario Lucic; Gunnar Rätsch; Sylvain Gelly; Bernhard Schölkopf; Olivier Bachem · 2019
  2. Gaussian mixture models — scikit-learn 1.7.2
    scikit-learn developers
  3. Clustering — scikit-learn 1.7.2
    scikit-learn developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Eight tests pass. Independent binary-moment Mobius inversion checks eight mixtures and 32 mass/posterior queries, including zero-probability conditionals. Complete latent-assignment probability summation checks twelve candidate likelihoods over three short datasets (843 assignments), unlike the implemented product of observed marginal masses. Winner sets and the exact likelihood ratio 729/256 agree.
  • Verified the common distribution (3/8,1/8,1/8,3/8), posteriors 1/0/5/12 at (1,0), non-equivalence under component relabeling, and tied fit on each possible held-out pair. Checked component reordering, zero weights, undefined conditioning, all-zero incompatible models, zero-count omission, duplicate count rows, candidate-order tie policy and input preservation. Rejects eight invalid mixture forms, eight table forms, five candidate forms and five posterior query forms.
  • Full bilingual prose and original complete standard-library code share eight stdout lines, four matching displayed formulas, six stable anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML pass, all four mathematical annotations agree, and no literal emphasis markers remain. All topic links and prerequisites use actual catalogue IDs. Pinned Humanizer prose review completed.
  • Explicitly separates finite candidate selection from continuous parameter fitting, table probability from sequence likelihood, all-zero mathematical ties from usable winners, external assessment from labeled model selection, and continuous disentanglement theory from the finite counterexample. Operation counts include input validation and exact powers; rational bit complexity is qualified. AI author checks only, review written. No human review, third-party model fitting, benchmark, browser acceptance or whole-site build.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • Challenging Common Assumptions in the Unsupervised Learning of Disentangled Representations · Actually opened the PMLR publication record and linked eleven-page PDF. Record confirms ICML 2019, volume 97, pages 4114–4124 and authors. Read PDF page 1 introduction, page 3 section 3/Theorem 1 (lines 172–227): d > 1, factorized latent density, mixing bijections preserving latent distribution and observationally equivalent generative models. Read page 8 conclusion on explicit assumptions, grouping/temporal information and evaluating concrete usefulness. Did not read the separate supplementary proof or reproduce benchmarks. Our two-light finite mixture construction does not instantiate that continuous theorem, and prose does not extend it to all useful unsupervised learning.
  • Gaussian mixture models — scikit-learn 1.7.2 · Actually opened fixed 1.7 guide rendered 1.7.2. Read lines 69–79 for Gaussian mixture family and EM API, 99–116 for covariance singularities, component count and latent memberships, and 142–168 for variational assumptions and application-dependent group counts. Article uses only mixture/EM/model-family context. It does not adopt the guide’s overly broad fastest-method or guaranteed-local-optimum statements. No sklearn execution or source code reuse.
  • Clustering — scikit-learn 1.7.2 · Actually opened fixed 1.7 clustering guide rendered 1.7.2. Read lines 69–86 for unlabeled input matrices and geometric/inductive/transductive context; section 2.3.11 lines 492–549 for external references, label permutation and Rand comparison; section 2.3.11.5 lines 849–860 for silhouette within/between distances. The article distinguishes criterion quality from semantic or causal correctness; it does not claim an internal score validates a failure mechanism.
  • Challenging Common Assumptions in the Unsupervised Learning of Disentangled Representations · Actually opened the official eleven-page ICML 2019 PDF. Read title/authors/year, introduction on observed and latent variables, and page 3 section 3/Theorem 1: dimension greater than one, a factorized latent density, distribution-preserving mixing bijections and observationally equivalent generative models. The article correctly describes this scope without treating its separate binary mixture counterexample as an implementation of that continuous theorem. No benchmark or supplementary-proof replication claimed.
  • Gaussian mixture models — scikit-learn 1.7.2 · Actually read the exact fixed /1.7/ guide, rendered 1.7.2, lines 69–79: finite Gaussian components, unknown parameters, EM fitting and covariance-family choices. These support the research comparison, not the binary candidate-selector specification. No software execution or source example reused.
  • Clustering — scikit-learn 1.7.2 · Actually read the exact fixed /1.7/ clustering guide, rendered 1.7.2, section 2.3.11 lines 494–548: external partition comparison, ignored label permutations and adjusted Rand interpretation; section 2.3.11.5 lines 849–883: within-group and nearest-other-group distances and silhouette geometry. The article appropriately separates those criteria from causal or semantic recovery.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.