AI Wiki中文/EN

Gaussian mixtures: bell curves with soft memberships

高斯混合模型

Derive Gaussian responsibilities and EM updates, then inspect a fixed-variance fit, a stationary initialization and a numerical stop.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Let an observation belong to two explanations

Four toy calibration offsets are −3, −2, 2 and 3. One bell curve centered at zero spreads probability across the gap. Two bell curves can put more density near the observations. A reading near zero may still be compatible with either component; forcing a hard assignment discards that uncertainty.

A Gaussian mixture model first selects a hidden component, then draws an observation from that component’s Gaussian distribution. It is a density model. Component memberships can also be used for clustering, but a component is not automatically a physical operating mode or a verified class.

We will fit two means and their mixing weights while keeping the common variance fixed at one. Starting from means −1 and 1 produces means near −2.499908 and 2.499908 after five EM rounds. Starting both means at zero leaves them there and gives a much lower training likelihood. The same objective can lead to different results because initialization matters.

A sum of densities, a posterior over components

For d-dimensional observations and K components, let πⱼ be nonnegative mixing weights summing to one. Each covariance Σⱼ is positive definite for an ordinary nonsingular Gaussian density:

pθ(x)=∑j=1KπjN(x;μj,Σj),N(x;μ,Σ)=exp⁡ ⁣[−12(x−μ)⊤Σ−1(x−μ)](2π)d/2∣Σ∣1/2.p_\theta(x)=\sum_{j=1}^K\pi_j\mathcal N(x;\mu_j,\Sigma_j),\qquad \mathcal N(x;\mu,\Sigma)=\frac{\exp\!\left[-\frac12(x-\mu)^\top\Sigma^{-1}(x-\mu)\right]}{(2\pi)^{d/2}|\Sigma|^{1/2}}.

The weights describe how frequently the model chooses components. The covariance describes spread and orientation within a component. A mixture can have several peaks even though each component has one. Conversely, K components need not produce K distinct visible peaks. The EM derivation below assumes positive weights; a zero-weight component can be omitted from the density sum.

For IID observations, maximize the sum of log mixture densities. It is a log of a sum, not a sum of component log densities. Numerically, compute each component’s log contribution aᵢⱼ and use:

ℓ(θ)=∑ilog⁡∑jeaij,aij=log⁡πj+log⁡N(xi;μj,Σj),log⁡∑jeaij=mi+log⁡∑jeaij−mi,mi=max⁡jaij.\ell(\theta)=\sum_i\log\sum_j e^{a_{ij}},\qquad a_{ij}=\log\pi_j+\log\mathcal N(x_i;\mu_j,\Sigma_j),\qquad \log\sum_j e^{a_{ij}}=m_i+\log\sum_j e^{a_{ij}-m_i},\quad m_i=\max_j a_{ij}.

Subtracting the maximum prevents an entire row of tiny densities from underflowing before normalization. Very small posterior entries can still round to zero. A density can exceed one; probability requires integrating it over a region.

E-step: compute responsibilities

The responsibility rᵢⱼ is the posterior probability of component j for observation i under the current model:

rij=Pθ(Zi=j∣xi)=πjN(xi;μj,Σj)∑lπlN(xi;μl,Σl),Nj=∑irij.r_{ij}=P_\theta(Z_i=j\mid x_i)=\frac{\pi_j\mathcal N(x_i;\mu_j,\Sigma_j)}{\sum_l\pi_l\mathcal N(x_i;\mu_l,\Sigma_l)},\qquad N_j=\sum_i r_{ij}.

Rows of responsibilities sum to one. Nⱼ is an effective count, usually not an integer. This is different from assigning every point to its nearest mean: weights and covariance also affect the posterior.

M-step: fit using those fractional counts

Holding the responsibilities fixed, maximizing the expected complete-data log likelihood gives the familiar unconstrained updates:

πjnew=Njn,μjnew=∑irijxiNj,Σjnew=∑irij(xi−μjnew)(xi−μjnew)⊤Nj.\pi_j^{\mathrm{new}}=\frac{N_j}{n},\qquad \mu_j^{\mathrm{new}}=\frac{\sum_i r_{ij}x_i}{N_j},\qquad \Sigma_j^{\mathrm{new}}=\frac{\sum_i r_{ij}(x_i-\mu_j^{\mathrm{new}})(x_i-\mu_j^{\mathrm{new}})^\top}{N_j}.

These expressions require Nⱼ > 0. The covariance uses the maximum-likelihood denominator Nⱼ, not Nⱼ−1. If that covariance is singular, it is not an admissible nonsingular Gaussian estimate without an additional convention or constraint. Our program updates only weights and means; its positive common variance is supplied and never estimated. Full, diagonal, spherical and tied covariances impose different parameter families. The fixed Gaussian-mixture guide explains those choices.

For fixed responsibilities, differentiating the mean’s weighted quadratic gives the weighted mean above. Maximizing the weight term, subject to weights summing to one, gives πⱼ = Nⱼ/n. These are exact M-steps for our restricted model in real arithmetic.

Why the likelihood should rise, and what that does not prove

For any strictly positive row distribution r, Jensen’s inequality gives a lower bound:

ℓ(θ)≥F(r,θ)=∑i,jrij[log⁡πj+log⁡N(xi;μj,Σj)−log⁡rij].\ell(\theta)\ge\mathcal F(r,\theta) =\sum_{i,j}r_{ij}\left[\log\pi_j+\log\mathcal N(x_i;\mu_j,\Sigma_j)-\log r_{ij}\right].

At the current model’s posterior, the bound is tight. An exact M-step raises or preserves the bound; evaluating the new posterior then tightens it again. Hence the observed likelihood does not decrease. This argument explains the likelihood property, not global optimality or universal convergence of the parameter sequence. The 1977 EM paper, §§2–3 and 4.3 develops the general incomplete-data framework and its finite-mixture case.

For fixed positive variance, the density has a finite upper bound, so the exact nondecreasing likelihood values are bounded above. That still does not select the best starting point or force duplicate initial components to separate. Floating-point calculations add rounding; the tests check the intended identities within stated numerical tolerances.

Keep variance fixed and expose every completed round

Run this complete Python 3.10+ standard-library program. It accepts finite integers and floats, excluding booleans, with one to 50 observations, one to five initial means, positive variance and an integer round limit from zero to 50. Optional initial weights must be positive and aligned; their relative values are normalized. These bounds keep the exercise small.

trace contains the initial model and every completed update. round-limit only means the requested number of rounds finished; it is not a convergence certificate. Positive weights and finite Gaussian densities give positive responsibilities in exact arithmetic. If a new weight becomes zero because the effective count is zero or dividing it by the sample size underflows, the program returns numerical-empty-component with the last completed model. It does not silently restart or remove that component. Zero normalized initial weights, detected nonfinite results and checked arithmetic overflow raise ValueError. This does not detect every underflow or loss of precision. For constant observations, each updated mean directly preserves that constant, including the smallest representable subnormal values.

Prediction uses an unmodified fitted model and learns nothing from queries. It returns component responsibilities and log densities, accepts an empty list, and retains component order. There is no hard-label tie rule because no hard labels are returned.

import math


def finite(value):
    if type(value) not in (int, float):
        raise ValueError('use finite int or float values, not booleans')
    try:
        value = float(value)
    except OverflowError as exc:
        raise ValueError('number is not representable') from exc
    if not math.isfinite(value):
        raise ValueError('number is not finite')
    return value


def vector(values, empty=False):
    if type(values) not in (list, tuple) or (not values and not empty):
        raise ValueError('expected a nonempty list or tuple')
    return tuple(finite(v) for v in values)


def evaluate(xs, means, weights, variance):
    # Internal: positive normalized weights and fixed positive variance.
    scale = math.sqrt(variance)
    normalizer = (math.log(2*math.pi) + math.log(variance))/2
    rows, logs = [], []
    for x in xs:
        terms = []
        for mean, weight in zip(means, weights):
            z = (x-mean)/scale
            square = z*z
            if not math.isfinite(square):
                raise ValueError('standardized squared residual is not representable')
            terms.append(math.log(weight)-normalizer-square/2)
        peak = max(terms)
        values = tuple(math.exp(t-peak) for t in terms)
        total = math.fsum(values)
        rows.append(tuple(v/total for v in values))
        logs.append(peak+math.log(total))
    try:
        likelihood = math.fsum(logs)
    except OverflowError as exc:
        raise ValueError('log likelihood is not representable') from exc
    if not math.isfinite(likelihood):
        raise ValueError('log likelihood is not finite')
    return tuple(rows), tuple(logs), likelihood


def fit(values, initial_means, variance=1, rounds=5, initial_weights=None):
    xs, means = vector(values), vector(initial_means)
    variance = finite(variance)
    constant = all(x == xs[0] for x in xs)
    if variance <= 0 or type(rounds) is not int or not 0 <= rounds <= 50:
        raise ValueError('positive variance and integer rounds in 0..50 required')
    if len(xs) > 50 or len(means) > 5:
        raise ValueError('teaching limit: 50 observations and five components')
    raw = (1.0,)*len(means) if initial_weights is None else vector(initial_weights)
    if len(raw) != len(means) or any(w <= 0 for w in raw):
        raise ValueError('one positive initial weight per component required')
    largest = max(raw)
    scaled = tuple(w/largest for w in raw)
    total_weight = math.fsum(scaled)
    weights = tuple(w/total_weight for w in scaled)
    if any(w == 0 for w in weights):
        raise ValueError('normalized initial weight underflow')
    responsibilities, logs, likelihood = evaluate(xs, means, weights, variance)
    trace = [(means, weights, likelihood)]
    status = 'round-limit'
    for _ in range(rounds):
        counts = tuple(math.fsum(row[j] for row in responsibilities) for j in range(len(means)))
        new_weights = tuple(count/len(xs) for count in counts)
        if any(w == 0 for w in new_weights):
            status = 'numerical-empty-component'
            break
        try:
            new_means = ((xs[0],)*len(means) if constant else
                         tuple(math.fsum((row[j]/counts[j])*x for x, row in zip(xs, responsibilities))
                               for j in range(len(means))))
        except OverflowError as exc:
            raise ValueError('updated mean is not representable') from exc
        if not all(math.isfinite(v) for v in new_means):
            raise ValueError('updated mean is not representable')
        responsibilities, logs, likelihood = evaluate(xs, new_means, new_weights, variance)
        means, weights = new_means, new_weights
        trace.append((means, weights, likelihood))
    return {'means': means, 'weights': weights, 'variance': variance,
            'responsibilities': responsibilities, 'log_densities': logs,
            'log_likelihood': likelihood, 'trace': tuple(trace),
            'rounds_completed': len(trace)-1, 'status': status}


def predict(model, values):
    xs = vector(values, empty=True)
    responsibilities, logs, _ = evaluate(xs, model['means'], model['weights'], model['variance'])
    return {'responsibilities': responsibilities, 'log_densities': logs}


if __name__ == '__main__':
    xs = [-3, -2, 2, 3]
    model = fit(xs, [-1, 1], rounds=5)
    print('means:', tuple(round(v, 6) for v in model['means']))
    print('weights:', tuple(round(v, 6) for v in model['weights']))
    print('log likelihood:', round(model['trace'][0][2], 6), '->', round(model['log_likelihood'], 6))
    print('middle responsibility:', tuple(round(v, 6) for v in predict(model, [0])['responsibilities'][0]))
    stuck = fit(xs, [0, 0], rounds=5)
    print('identical initialization:', stuck['means'], round(stuck['log_likelihood'], 6))
    print('status / completed:', model['status'], model['rounds_completed'])
    empty = fit([0], [0, 1000], rounds=2)
    print('numerical stop:', empty['status'], empty['rounds_completed'])

Actual output:

means: (-2.499908, 2.499908)
weights: (0.5, 0.5)
log likelihood: -11.407092 -> -6.948251
middle responsibility: (0.5, 0.5)
identical initialization: (0.0, 0.0) -16.675754
status / completed: round-limit 5
numerical stop: numerical-empty-component 0

The separated initialization raises log likelihood from −11.407092 to −6.948251. At the midpoint zero, the two responsibilities remain 1/2 each. The identical initialization instead stays at means (0,0), with log likelihood −16.675754. This is an executed example of a worse stationary fit, not evidence that EM always finds two groups.

The last line is a numerical boundary case. A component at 1000 has negligible responsibility for a sole observation at zero; its computed effective count becomes zero. The explicit stop records that loss of numerical resolution. It is unrelated to a theorem claiming that Gaussian density is exactly zero far from the mean.

For n observations, K components and R completed rounds, the fixed-variance calculations take O((R+1)nK) arithmetic/transcendental operations and O(nK+(R+1)K) retained numeric slots, including the final responsibilities and all model snapshots. Prediction on q points takes O(K+qK+1) operations and space for validation, model normalization constants and returned rows. String formatting and floating-point representability are separate from these operation counts. A general full-covariance implementation has additional dimension-dependent costs.

The test companion independently sums whole-sample latent assignments using 70-digit decimal probabilities. It compares the resulting posterior sufficient statistics, means, weights and likelihoods with the program’s rowwise log-space computation. A separate bound calculation checks the E/M-step inequality on a small dataset.

Density estimation needs more than an increasing score

If variances are allowed to shrink freely, an ordinary Gaussian-mixture likelihood can be unbounded. With two components and observations 0 and 2, put one mean at zero and shrink its variance toward zero while another positive-weight component supplies positive density to the remaining observation. Density at zero diverges. This is not successful discovery of an infinitely precise population. Covariance restrictions, regularization or priors change the estimation problem and must be documented. The fixed guide flags covariance singularities; our known positive variance excludes that particular collapse mechanism.

Component numbers are arbitrary. Permuting weights, means and covariances together leaves the density unchanged while permuting responsibility columns. Identical components introduce additional redundancies. Neither issue permits attaching a real-world label to a component without evidence. An identified statistical component and a causal explanation are different claims.

Choose component count, covariance family and initialization policy within a validation design. Held-out log likelihood evaluates density prediction; comparison with known classes evaluates a different task. AIC/BIC and held-out criteria have their own assumptions and do not reveal a universally correct group count. Fit scaling on the training portion and keep a final test set separate from repeated model selection.

Our model uses one dimension and one fixed variance. It does not handle missing coordinates, fit covariance matrices, perform Bayesian inference or guarantee a global solution. Several restarts may improve the attained objective; retaining the best training fit does not by itself establish generalization.

Read the probabilities and the stopping reason

1. Why does a midpoint reading have responsibility 1/2 for each fitted component?

Answer: The example’s weights are equal and its means remain symmetric around zero, with equal variance. At zero the two weighted densities are equal, so Bayes normalization gives (1/2,1/2). This is model uncertainty over components, not a verified probability of two physical machine modes.

2. Does finishing five rounds prove convergence or optimality?

Answer: No. round-limit records completed work. Starting both means at zero leaves them there, with log likelihood −16.675754; the separated initialization reaches −6.948251. A fixed point or a small update can therefore coexist with a substantially better fit elsewhere.

3. For one component with known variance, what does one M-step do to observations 1, 2 and 6?

Answer: All responsibilities equal one, so N = 3, the weight is one and the new mean is (1+2+6)/3 = 3. The supplied variance stays unchanged. Estimating a sample variance would solve a different parameter problem.

4. Why is a zero numerical effective count treated differently from a tiny positive count?

Answer: A zero count makes the mean update divide by zero, although this positive-weight Gaussian model has no exactly zero responsibility in real arithmetic. The program stops before that update and retains the last completed model. A tiny positive count can be updated if its normalized weight remains representable, but its fit may be sensitive; changing precision, initialization or model constraints requires a deliberate choice.

The missing variable is component membership

Dempster, Laird and Rubin’s 1977 paper organized a general expectation/maximization framework and discussed earlier special-case mixture procedures. It did not invent Gaussian mixtures as a distribution family. In a mixture, the observations are present; the missing part is which component generated each one. That makes the weighted fitting interpretation concrete.

The versioned mixture guide connects that model to covariance constraints, component selection and variational alternatives. Changing those constraints changes the objective or parameter space; sharing an EM-style loop does not make different models interchangeable.

Continue with Gaussian distributions for covariance geometry, EM for the broader optimization framework, and unsupervised learning for the distinction between observable fit and semantic interpretation.

Make a prediction, then check

Two initial means are identical and remain identical after every requested EM round. Has the program demonstrated the best possible mixture fit?

Choose one answer

Learning objectives

  • Distinguish a mixture density, posterior responsibility and a real-world class.
  • Derive fractional-count EM updates and explain why likelihood monotonicity does not imply global optimality.
  • Audit a fixed-variance floating-point fit, its initialization and its explicit numerical stopping condition.

Prerequisites & connections

Explore related knowledge →

References

  1. Maximum Likelihood from Incomplete Data via the EM Algorithm
    A. P. Dempster; N. M. Laird; D. B. Rubin · 1977
  2. Gaussian mixture models — 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. Four independent 70-digit Decimal whole-sample latent-assignment calculations check 16 model snapshots, 24 final responsibility entries, means, weights and log likelihoods; 208 complete latent assignments are summed across the snapshots. This differs from the implemented rowwise log-sum-exp calculation. Comparisons use relative/absolute tolerance 2e-12. A separate Jensen bound and weighted-mean stationarity check verifies an E/M update.
  • Verified separated versus identical initialization, equal midpoint responsibilities, a single-component analytic mean, density greater than one, finite far-tail log scores, explicit numerical-empty-component status, zero rounds, component relabeling, empty queries and input/model preservation. Rejects seven invalid input/size forms, nine parameter/weight configurations, two unrepresentable arithmetic inputs and an invalid query. Redundant repeated initial weight normalization scans were removed before freezing.
  • Full bilingual original articles have identical complete standard-library Python, seven actual stdout lines, five displayed formulas, six stable anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML pass; all five math annotations match. EM derivation explicitly assumes positive weights, with zero-weight components omitted. Pinned Humanizer prose review completed. Only verified published unsupervised-learning uses a direct wiki route; other related topics use catalogue routes.
  • Review remains written with AI author checks only. General covariance updates are explained but the runnable model estimates only scalar means and weights with one known positive variance. Limits, density-versus-probability interpretation, label ambiguity, covariance collapse outside this model and floating-point underflow are explicit. No human review, general covariance solver, global optimum claim, library training, benchmark, browser acceptance or whole-site build.
  • Independent AI review identified loss of a representable constant mean when multiplying the smallest subnormal observation by fractional weights. A constant-observation branch now preserves that value directly; eight one/two-component runs cover positive/negative 5e-324, zero and three. Both languages narrow numerical error detection to the implemented checks and label the negative exercise values explicitly as log likelihood. The stopping prose now also includes positive counts whose division by n underflows; an executed boundary confirms that case. The eight-test suite and strict actual HTML were rerun after these changes.
  • 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:

  • Maximum Likelihood from Incomplete Data via the EM Algorithm · Actually opened the University of Sydney 39-page scan. Cover identifies JRSS Series B 39(1), 1977, pages 1–38 including discussion; the publisher separately lists the article as pages 1–22. Read printed pages 1–3 (physical 2–4) for title/authors, 8 December 1976 presentation and general EM naming with earlier special cases; Theorem 1 and following qualifications on printed pages 7–8 (physical 8–9) for nondecreasing likelihood versus additional convergence conditions; section 4.3 on printed pages 15–16 (physical 16–17) for hidden component indicators, posterior expected sufficient statistics and earlier Gaussian-mixture work. Text extraction only; no full discussion or visual audit. Some extracted inequality signs are ambiguous, so the article independently derives the Jensen lower-bound argument and makes no universal parameter-convergence claim.
  • Gaussian mixture models — scikit-learn 1.7.2 · Actually reopened fixed 1.7 guide rendered 1.7.2. Read lines 69–79 for mixture density and full/diagonal/spherical/tied covariance options, lines 99–116 for singularities and component-selection assumptions, and the variational comparison. Shared source record/URL reused exactly from the published unsupervised-learning chapter. Did not adopt the guide’s absolute fastest or guaranteed-local-optimum wording, run sklearn, or claim the scalar fixed-known-variance program implements its API.
  • Maximum Likelihood from Incomplete Data via the EM Algorithm · Actually opened the University of Sydney 39-page original scan. Read the cover and printed pages 1–3: authors, 1977 journal date, separate 8 December 1976 meeting and prior special cases. Read Theorem 1 and qualifications on printed pages 7–8: nondecreasing likelihood does not by itself guarantee convergence to a maximum-likelihood estimator. Read section 4.3 printed pages 15–16 on hidden component indicators, joint complete-data likelihood and expected sufficient statistics. Text extraction has damaged inequality glyphs; monotonicity was independently checked by the valid Jensen argument, not copied from ambiguous glyphs. No full discussion or visual-page claim.
  • Gaussian mixture models — scikit-learn 1.7.2 · Actually read fixed 1.7 guide rendered 1.7.2, lines 69–79 for Gaussian mixture model and covariance families, 99–116 for singular covariance and selection/EM discussion, and 140–149 for variational alternatives. Did not adopt its overbroad guaranteed-local-optimum or fastest wording. No sklearn run.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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