Module contents
Lesson 9 of 27Core 110 min

Latent variable models: mixed membership, mixtures of experts and EM on graphs

Building on EM and Gaussian mixtures from m12, this lesson broadens the repertoire of latent-variable models and trains them on graphical models. It distinguishes global and local latent variables, formulates LDA and mixtures of experts, treats the E-step in Bayesian networks as inference and the M-step as re-estimation from expected counts, and studies symmetries that make these models non-identifiable.

After this lesson you can

  • Write the generative story, plate graph and marginal likelihood of a latent-variable model, distinguishing global from local variables.
  • Formulate LDA and mixtures of experts and explain how they differ from a simple mixture.
  • Derive EM for a Bayesian network with hidden nodes as family-marginal inference plus expected counts.
  • Implement EM for a mixture of experts with softmax gating and linear experts.
  • Detect and handle label switching and other symmetries when comparing, averaging or interpreting solutions.

Before you start

What you do not observe

A document can mix several topics, a prediction can depend on an unobserved regime, and several symptoms can share a hidden cause. In a latent-variable model we write a joint distribution for observations and unobserved variables, and sum or integrate out the latter to obtain the data probability:

p(x∣θ)=∑zp(x,z∣θ).p(\vb x\given\theta)=\sum_{\vb z}p(\vb x,\vb z\given\theta).

In the EM algorithm, the E-step calculates the posterior distribution of the hidden variables with the current parameters; the M-step improves the expected log complete joint. With an exact E-step and an exact or sufficiently controlled improvement of that expectation, observed likelihood does not decrease. With priors, approximations or penalties we must specify which objective is increasing.

Global and local variables differ by what they share. In LDA, word topics are global to the corpus; each document has its own proportions and each word a local assignment. In a Bayesian Gaussian mixture, weights, means and covariances are shared and each observation has a label; in an HMM with unknown parameters, transition and emission are global and the hidden state is local to a time in a sequence. The number of states or assignments grows with data, while the number of global parameters remains fixed if the model and dimensions are fixed.

Mixed membership in LDA

In LDA with KK topics and vocabulary size VV, each topic ϕk∼Dirichlet⁡(β1V)\boldsymbol\phi_k\sim\operatorname{Dirichlet}(\beta\mathbf1_V) is a distribution over words. Each document dd receives θd∼Dirichlet⁡(α1K)\boldsymbol\theta_d\sim\operatorname{Dirichlet}(\alpha\mathbf1_K). At each position nn, generate zdn∼Categorical⁡(θd)z_{dn}\sim\operatorname{Categorical}(\boldsymbol\theta_d) and then wdn∼Categorical⁡(ϕzdn)w_{dn}\sim\operatorname{Categorical}(\boldsymbol\phi_{z_{dn}}). The original model of Blei, Ng and Jordan formalizes this idea.

InteractiveThe generative story of LDA
Topic 1Topic 2Topic 3
Topic 131201712Topic 23743Topic 3134129networkdatagoalcellpricefieldmodelleaguegeneriskpassprotein
modelgenepricepricedatariskdatariskgenegeneriskgenefieldgeneriskriskgenedatadatapricemodelpricedatarisk
  • document proportions θd\theta_d
  • highlighted document
  • empirical proportion of zz
Topic concentration
0.20
0.32
24 / 24 words
θ\theta of highlighted document(0.99, 0.01, 0.00)
Empirical proportion of zz so far(1.00, 0.00, 0.00)
Mean dominant topic, E[max⁡kθk]\E[\max_k\theta_k] (60 docs)0.81
Topics with θk>0.1\theta_k > 0.1 per document1.58
Mean θ\theta (theory: 1/3 each)0.33 · 0.40 · 0.27
Effective words per topic (of 12)5.0
Change topic and word concentrations and play the generation of a synthetic document.

The figure generates three topics, twelve words, sixty documents and twenty-four words per document, with a fixed seed. Vocabulary labels are toy names, not observed documents. For a symmetric Dirichlet with small α\alpha, proportions concentrate near vertices; with large α\alpha they cluster near 1/K1/K. Parameter β\beta controls word dispersion within each topic. This describes a distributional tendency, not a guarantee that every document or topic follows the same pattern.

A simple mixture usually chooses one label for a whole document; LDA chooses a topic per word and allows a document to share several. The posterior couples proportions, topics and assignments, and summing all word-topic configurations can grow as KNK^N. Variational approximations or sampling are used; the distinction between global and local variables is central to stochastic variational inference. An estimated topic is a statistical structure subject to prior, data and stability, not necessarily a true semantic entity.

The joint reflects this story exactly: multiply the prior of each ϕk\boldsymbol\phi_k, the prior of each θd\boldsymbol\theta_d and, within each document, the topic and word factors at each position. A topic plate shares ϕk\boldsymbol\phi_k across documents; a document plate in turn contains a positions plate. This nesting explains why two words in the same document are not independent after integrating out their shared proportions.

Normalization also determines what counts as a free parameter. Each topic vector has VV entries but only V−1V-1 degrees of freedom; there are K(V−1)K(V-1) in total if distributions are treated as parameters. Document proportions are counted separately: they grow with the corpus and are local, although inferred jointly with global topics.

Context-dependent experts

A mixture of experts conditions its mixture weights on the input:

p(y∣x)=∑k=1Kgk(x) pk(y∣x),gk(x)=evk⊤φ(x)∑jevj⊤φ(x).p(y\given x)=\sum_{k=1}^K g_k(x)\,p_k(y\given x),\qquad g_k(x)=\frac{e^{\vb v_k\T\boldsymbol\varphi(x)}}{\sum_j e^{\vb v_j\T\boldsymbol\varphi(x)}}.

With Gaussian linear experts, the E-step calculates responsibilities proportional to gk(xi)pk(yi∣xi)g_k(x_i)p_k(y_i\given x_i). The M-step fits each line with weighted least squares and trains the gate with those responsibilities as soft labels. A reference gate with zero logit eliminates the redundancy of adding the same vector to all logits. Jordan and Jacobs study hierarchical mixtures and EM.

InteractiveExperts and gate
0.72−1.05iteration 060mean log likelihood per data point
  • truth ff
  • each expert where its gate exceeds 0.3
  • predicted mean ∑kgk y^k\sum_k g_k\,\hat{y}_k
Experts KK
iteration 60
Mean log likelihood0.724
Predicted-mean error versus ff (RMSE)0.067
True noise σ\sigma0.12
Mean responsibility, expert 10.32
Mean responsibility, expert 20.35
Mean responsibility, expert 30.34
Compare a line with several experts, run EM and try different initializations.

The figure uses 150 stratified inputs in [−1,1][-1,1], Gaussian noise with standard deviation 0.12 and three segments: 1.3+2.2x1.3+2.2x for x<−0.3x<-0.3, 0.55−3.2x0.55-3.2x up to x<0.35x<0.35 and −1.1+1.9x-1.1+1.9x thereafter. It updates variances with a floor and the gate with a few Newton steps and a small penalty. The curve shows observed log likelihood; because of the penalty and floor, it should not be interpreted as general proof of monotonic unpenalized likelihood. Symmetric initialization can keep experts identical; an expert with almost zero responsibility may receive no useful information. Restarts and diagnostics are part of fitting, not a guarantee of a global optimum.

A point’s responsibility depends on its input and output. A large gate gk(xi)g_k(x_i) indicates the expert is plausible before looking at yiy_i, but a large prediction error can reduce its posterior responsibility. In the M-step that expert’s fractional weights are exactly those responsibilities. If every point assigns it practically zero weight, the weighted least-squares matrix can be singular; keeping the old expert or regularizing requires an explicit rule.

The gate has no count-normalization solution like a table without covariates: its parameters affect all inputs simultaneously. Weighted multinomial optimization can be solved with Newton or IRLS. A step that improves the auxiliary function suffices for generalized EM, without requiring exact completion of the inner optimizer. Modern neural MoE layers also use gates and experts, but typically include sparse routing and additional objectives; they are not identical to this Gaussian model.

EM over a network

In a discrete Bayesian network with family Fi={Xi,pa⁡(Xi)}F_i=\{X_i,\operatorname{pa}(X_i)\}, the log complete joint is the sum of log conditional tables. The E-step only needs the joint posterior marginal of each family given the observed row. For state xix_i and parent configuration uu:

Nˉi(xi,u)=∑dP(Xi=xi,pa⁡(Xi)=u∣xdobs,θviejo).\bar N_i(x_i,u)=\sum_d P(X_i=x_i,\operatorname{pa}(X_i)=u\given x_d^{\rm obs},\theta_{\rm viejo}).

The maximum-likelihood M-step normalizes each row: θi(xi∣u)=Nˉi(xi,u)/∑xNˉi(x,u)\theta_i(x_i\given u)=\bar N_i(x_i,u)/\sum_x\bar N_i(x,u), when the denominator is positive. An isolated node marginal generally does not suffice: child-parent dependence determines joint counts. Variable elimination or sum-product provides those marginals; Lauritzen explains graphical inference in the E-step.

InteractiveExpected counts with a hidden cause
S1S2S3Dhidden
S₁ S₂ S₃rowspattern split between D = 0 and D = 1counts
10379.6 | 23.4
2515.1 | 9.9
3020.9 | 9.1
2412.1 | 11.9
188.9 | 9.1
216.4 | 14.6
208.0 | 12.0
5913.4 | 45.6
Expected counts Nˉ\bar N (fractions)
N(D)N(D)N(S1,D)N(S_1,D)N(S2,D)N(S_2,D)N(S3,D)N(S_3,D)
D=0164.346.954.336.7
D=1135.782.178.781.3
Current parameters (truth below)
πd\pi_dP(S1 ⁣∣ ⁣d)P(S_1\!\mid\! d)P(S2 ⁣∣ ⁣d)P(S_2\!\mid\! d)P(S3 ⁣∣ ⁣d)P(S_3\!\mid\! d)
D=00.5000.600.4000.150.4500.200.3500.10
D=10.5000.400.6000.800.5500.700.6500.75
  • part of pattern with D=0D = 0
  • part with D=1D = 1
Data
Log likelihood of observed rows−611.775
EM iterations0
Maximum error of the 7 parameters (up to permutation of DD)0.250
Noninteger countsyes
Each pattern is split fractionally across D values. In each family, counting all states sums to the number of observed rows.
Distribute each pattern across cause values and compare the M-step with complete counts.

The interactive generates 300 rows from a binary cause and three symptoms, with true parameters visible only to evaluate this example. One row might contribute 0.2 to hidden state zero and 0.8 to state one. With the cause observed it would contribute an integer to one of the two. Fractional counts still sum to the number of rows.

With a Dirichlet prior with parameters αx>1\alpha_x>1, the interior MAP adds αx−1\alpha_x-1 to each count; the posterior mean adds αx\alpha_x and uses another denominator. EM’s MAP increase concerns log likelihood plus log prior, not necessarily bare likelihood. With zero counts and no prior, an unobserved row needs explicit handling, as it does not determine a unique conditional distribution.

To see the update, fix a parent configuration uu and maximize ∑xNˉi(x,u)log⁡θi(x∣u)\sum_x\bar N_i(x,u)\log\theta_i(x\given u) under constraint ∑xθi(x∣u)=1\sum_x\theta_i(x\given u)=1. The multiplier condition equates Nˉi(x,u)/θi(x∣u)\bar N_i(x,u)/\theta_i(x\given u) to a constant; summing over xx yields the row total. The same argument applies to each table and each parent configuration separately.

E-step accuracy matters for the guarantee. If the network is large and exact inference infeasible, an approximation can be used, but maximizing a function calculated with approximate marginals no longer ensures the real likelihood rises every iteration. Record which objective you observe and check its trajectory; a rising line in one synthetic example does not prove that all problems converge to a global optimum.

Symmetries and labels

Permuting mixture labels and coherently permuting their parameters leaves the observed distribution unchanged. Label non-identifiability means two solutions can be the same distribution with exchanged names. Other symmetries also exist, such as rotations and scales in certain factor models, which cannot be resolved merely by permutation.

InteractiveLabels switch
123
1: 231 · −2.522: 321 · −2.523: 213 · −2.524: 132 · −2.525: 312 · −2.526: 123 · −2.527: 123 · −2.528: 123 · −2.52
  • component kk mean in one run
  • average by index kk
  • truth
How labels are aligned before averaging
8
1.00
Mean error of the 3 averaged means (current mode)0.854
Error if averaged without alignment0.854
Distinct labelings across runs6 of 8
Runs close to the best observed8 of 8
Mean log-likelihood range−2.518 to −2.518
Likelihood does not change when labels are permuted. Averaging by index can mix different clusters, although some runs also differ by local optima.
Compare averaging by index with component alignment across EM restarts.

The figure fits a Gaussian mixture to 240 synthetic points: 80 per component, with standard deviation 0.55 and base means (−1,−0.6)(-1,-0.6), (1,−0.6)(1,-0.6) and (0,1.1)(0,1.1) multiplied by the chosen separation. For three components it compares all six permutations and obtains the optimal assignment, equivalent here to the Hungarian algorithm. The reference is the best observed run. Alignment removes the difference in names but does not correct distinct local minima or turn several solutions into independent posterior samples. When comparing with synthetic truth, error must also allow a permutation.

A historical application: alignment

IBM alignment models treat the position of the source word that generated each target word as latent. In model 1, given source words e0,…,ele_0,\ldots,e_l (including NULL), each alignment is uniform and the probability of a target word fjf_j is

p(fj∣e)=1l+1∑i=0lt(fj∣ei).p(f_j\given\vb e)=\frac{1}{l+1}\sum_{i=0}^{l}t(f_j\given e_i).

The E-step distributes each word among possible sources proportionally to t(fj∣ei)t(f_j\given e_i); the M-step normalizes expected counts by source word. Length and sentences are taken as given in this formulation. The model 1 log likelihood is a sum of logarithms of linear functions of translation probabilities: it is concave over the product of simplices. Therefore an interior local maximum is global, although the maximum need not be unique and a finite run does not guarantee reaching it. This property does not automatically extend to richer alignment models. See Brown and colleagues.

InteractiveAlignments and translation counts
launacasaflorverdeNULL0.200.200.200.200.20the0.200.200.200.200.20a0.200.200.200.200.20house0.200.200.200.200.20flower0.200.200.200.200.20green0.200.200.200.200.20NULLthegreenhouselacasaverde0.25 → NULL0.25 → NULL0.25 → NULL−8.6−14.5corpus log likelihood by iteration
  • probability t(f∣e)t(f \mid e)
  • alignment posterior P(aj=i∣e,f)P(a_j = i \mid \mathbf{e}, \mathbf{f})
Sentence pair
iteration 0
Corpus log likelihood−14.485
t(la∣the)t(\text{la}\mid\text{the})0.200
t(la∣NULL)t(\text{la}\mid\text{NULL})0.200
t(casa∣house)t(\text{casa}\mid\text{house})0.200
t(flor∣flower)t(\text{flor}\mid\text{flower})0.200
Run EM on four toy sentence pairs and observe how latent assignments are distributed.

The toy corpus contains the pairs “the house / la casa”, “the flower / la flor”, “a flower / una flor” and “the green house / la casa verde”. Each adds NULL on the source side. Probabilities are estimated on this minimal corpus, so its associations should not be interpreted as a reliable translation system.

A reproducible synthetic corpus

The following generator builds topics and document proportions with symmetric Dirichlet priors and assigns a different topic to each word. It returns the document-word matrix, true proportions and topics, and individual assignments and words. It is also used in lessons 18 and 22; this is a synthetic experiment, not a real document collection.

[ ]Shared LDA corpusBrowser
"""Corpus LDA sintético reproducible para m14-l09, l18 y l22."""
import numpy as np


def synthetic_lda(seed=2026, n_docs=250, n_words=60, n_topics=3,
                  n_vocab=12, alpha=.3, beta=.12):
    """Devuelve (conteos, theta, temas, asignaciones, palabras).

    Temas: (K,V); theta: (D,K); asignaciones y palabras: (D,N).
    Los temas y proporciones se generan de priors Dirichlet simétricos,
    cada palabra tiene su propio tema, y las filas de conteos suman N.
    """
    if min(n_docs,n_words,n_topics,n_vocab)<1 or alpha<=0 or beta<=0:
        raise ValueError('tamaños y concentraciones deben ser positivos')
    rng=np.random.default_rng(seed)
    topics=rng.dirichlet(np.full(n_vocab,beta),size=n_topics)
    theta=rng.dirichlet(np.full(n_topics,alpha),size=n_docs)
    assignments=np.empty((n_docs,n_words),dtype=int)
    words=np.empty_like(assignments)
    counts=np.zeros((n_docs,n_vocab),dtype=int)
    for d in range(n_docs):
        assignments[d]=rng.choice(n_topics,size=n_words,p=theta[d])
        for n,z in enumerate(assignments[d]):
            words[d,n]=rng.choice(n_vocab,p=topics[z])
        counts[d]=np.bincount(words[d],minlength=n_vocab)
    return counts,theta,topics,assignments,words
[ ]Generate and check the LDA corpusBrowser
counts,theta,topics,z,words=synthetic_lda()
assert counts.shape==(250,12) and np.all(counts.sum(axis=1)==60)
assert np.allclose(theta.sum(axis=1),1) and np.allclose(topics.sum(axis=1),1)
assert np.array_equal(counts[0],np.bincount(words[0],minlength=12))
prior_variance=(.3*(.9-.3))/(.9**2*(.9+1))
print('forma y tokens:',counts.shape,counts.sum())
print('medias de theta:',theta.mean(axis=0),'teoría:',np.full(3,1/3))
print('varianzas de theta:',theta.var(axis=0),'teoría:',prior_variance)

Empirical means and variances fluctuate around those of the Dirichlet; 250 documents do not reproduce them exactly. We fit variational LDA with scikit-learn to the counts and align estimated topics with true ones only because here we know them. L1 distance between distributions is between zero and two. Fitting uses the same data to train and measure topic error; it is not a generalization evaluation.

[ ]Fit and align topicsBrowser
from sklearn.decomposition import LatentDirichletAllocation
from scipy.optimize import linear_sum_assignment
lda=LatentDirichletAllocation(n_components=3,doc_topic_prior=.3,topic_word_prior=.12,
                              learning_method='batch',max_iter=25,random_state=17,n_jobs=1).fit(counts)
estimated=lda.components_/lda.components_.sum(axis=1,keepdims=True)
cost=np.sum(abs(topics[:,None,:]-estimated[None,:,:]),axis=2)
row,col=linear_sum_assignment(cost)
print('asignación de tema verdadero a estimado:',list(zip(row,col)))
print('distancias L1 por tema y media:',cost[row,col],cost[row,col].mean())
print('iteraciones y perplejidad de entrenamiento:',lda.n_iter_,lda.bound_)

The assignment selects the smallest sum of distances, but does not change distributions or ensure other restarts find the same topics. The perplexity reported by this implementation is an approximate training-set measure, not test perplexity.

Lab: EM with exact inference

The lesson 2 class and lesson 4 factor engine are reproduced below to run this lab without local file dependencies. The network is binary and each node’s tables store P(Xi=1∣pa⁡(Xi))P(X_i=1\given\operatorname{pa}(X_i)). The E-step queries the joint marginal of unobserved variables in each family, conditioned on all observations, and reinserts observed states into the counts.

[ ]BayesNet from lesson 2Browser
import itertools
import numpy as np

class BayesNet:
    def __init__(self, parents, probs):
        self.parents, self.probs = parents, probs
        self.nodes = list(parents)  # orden topológico
        assert all(p in self.nodes[:i] for i, n in enumerate(self.nodes)
                   for p in parents[n])

    def joint(self, values):
        out = 1.0
        for n in self.nodes:
            q = self.probs[n][tuple(values[p] for p in self.parents[n])]
            out *= q if values[n] else 1 - q
        return out

    def sample(self, size, seed=0):
        rng = np.random.default_rng(seed)
        rows = []
        for _ in range(size):
            row = {}
            for n in self.nodes:
                q = self.probs[n][tuple(row[p] for p in self.parents[n])]
                row[n] = int(rng.random() < q)
            rows.append(row)
        return rows

    def query(self, event, evidence):
        num = den = 0.0
        for bits in itertools.product((0, 1), repeat=len(self.nodes)):
            row = dict(zip(self.nodes, bits))
            if any(row[k] != v for k, v in evidence.items()):
                continue
            p = self.joint(row)
            den += p
            if all(row[k] == v for k, v in event.items()):
                num += p
        if den == 0:
            raise ValueError("Evidencia imposible")
        return num / den

    def separated(self, X, Y, Z):
        parents = self.parents
        children = {n: [] for n in self.nodes}
        for child, ps in parents.items():
            for p in ps:
                children[p].append(child)
        ancestors, todo = set(Z), list(Z)
        while todo:
            for p in parents[todo.pop()]:
                if p not in ancestors:
                    ancestors.add(p); todo.append(p)
        queue = [(x, 'up') for x in X]
        seen, reached = set(), set()
        while queue:
            n, direction = queue.pop()
            if (n, direction) in seen:
                continue
            seen.add((n, direction))
            if n not in Z:
                reached.add(n)
            if direction == 'up' and n not in Z:
                queue.extend((p, 'up') for p in parents[n])
                queue.extend((c, 'down') for c in children[n])
            elif direction == 'down':
                if n not in Z:
                    queue.extend((c, 'down') for c in children[n])
                if n in ancestors:
                    queue.extend((p, 'up') for p in parents[n])
        return not bool(reached & set(Y))
[ ]Factor engine from lesson 4Browser
"""Factores tabulares con ejes nombrados e inferencia exacta discreta."""
from itertools import product
import numpy as np


class Factor:
    def __init__(self, scope, values):
        self.scope = tuple(scope)
        self.values = np.asarray(values, dtype=float)
        if len(set(self.scope)) != len(self.scope) or self.values.ndim != len(self.scope):
            raise ValueError('cada eje debe tener un nombre distinto')
        if not np.all(np.isfinite(self.values)) or np.any(self.values < 0):
            raise ValueError('los factores deben ser finitos y no negativos')

    def restrict(self, variable, value):
        if variable not in self.scope:
            return self
        axis = self.scope.index(variable)
        if not isinstance(value, (int, np.integer)) or not 0 <= value < self.values.shape[axis]:
            raise ValueError('valor de evidencia fuera del dominio')
        scope = self.scope[:axis] + self.scope[axis+1:]
        return Factor(scope, np.take(self.values, value, axis=axis))

    def __mul__(self, other):
        union = self.scope + tuple(v for v in other.scope if v not in self.scope)
        for v in set(self.scope) & set(other.scope):
            if self.values.shape[self.scope.index(v)] != other.values.shape[other.scope.index(v)]:
                raise ValueError('cardinalidades incompatibles')
        def align(factor):
            ordered = [v for v in union if v in factor.scope]
            axes = [factor.scope.index(v) for v in ordered]
            data = np.transpose(factor.values, axes) if axes else factor.values
            shape = [factor.values.shape[factor.scope.index(v)] if v in factor.scope else 1 for v in union]
            return data.reshape(shape)
        return Factor(union, align(self) * align(other))

    def sum_out(self, variable):
        if variable not in self.scope:
            return self
        axis = self.scope.index(variable)
        return Factor(self.scope[:axis] + self.scope[axis+1:], self.values.sum(axis=axis))

    def reorder(self, order):
        order = tuple(order)
        if set(order) != set(self.scope) or len(order) != len(self.scope):
            raise ValueError('orden incompatible')
        return Factor(order, np.transpose(self.values, [self.scope.index(v) for v in order]))


def factor_graph(factors):
    graph = {v: set() for factor in factors for v in factor.scope}
    for factor in factors:
        for v in factor.scope:
            graph[v].update(set(factor.scope) - {v})
    return graph


def min_fill_order(graph, candidates=None):
    """Ordena candidatos; el ancho incluye vecinos retenidos en la consulta."""
    graph = {v: set(neighbors) for v, neighbors in graph.items()}
    if any(v in ns or any(u not in graph or v not in graph[u] for u in ns) for v, ns in graph.items()):
        raise ValueError('se requiere un grafo simple no dirigido')
    remaining = set(graph) if candidates is None else set(candidates)
    if not remaining <= set(graph):
        raise ValueError('candidato ausente del grafo')
    order, width = [], 0
    while remaining:
        def score(v):
            ns = list(graph[v])
            missing = sum(b not in graph[a] for i, a in enumerate(ns) for b in ns[i+1:])
            return missing, len(ns), str(v)
        v = min(remaining, key=score)
        neighbors = list(graph[v])
        width = max(width, len(neighbors))
        for a in neighbors:
            graph[a].update(set(neighbors) - {a})
            graph[a].discard(v)
        del graph[v]
        remaining.remove(v)
        order.append(v)
    return order, width


def variable_elimination(factors, query, evidence=None):
    evidence = {} if evidence is None else dict(evidence)
    query = tuple(query)
    if not factors:
        raise ValueError('se requiere al menos un factor')
    sizes = {}
    for factor in factors:
        for variable, size in zip(factor.scope, factor.values.shape):
            if variable in sizes and sizes[variable] != size:
                raise ValueError('cardinalidades incompatibles')
            sizes[variable] = size
    graph0 = factor_graph(factors)
    if len(set(query)) != len(query) or not set(query) <= set(graph0) or set(query) & set(evidence):
        raise ValueError('consulta y evidencia deben ser variables distintas del modelo')
    if not set(evidence) <= set(graph0):
        raise ValueError('evidencia ajena al modelo')
    reduced = list(factors)
    for variable, value in evidence.items():
        reduced = [factor.restrict(variable, value) for factor in reduced]
    graph = factor_graph(reduced)
    order, width = min_fill_order(graph, set(graph) - set(query))
    for variable in order:
        bucket = [factor for factor in reduced if variable in factor.scope]
        reduced = [factor for factor in reduced if variable not in factor.scope]
        joint = bucket[0]
        for factor in bucket[1:]:
            joint = joint * factor
        reduced.append(joint.sum_out(variable))
    joint = reduced[0]
    for factor in reduced[1:]:
        joint = joint * factor
    result = joint.reorder(query)
    evidence_weight = result.values.sum()
    if evidence_weight <= 0:
        raise ValueError('evidencia con peso cero')
    return Factor(query, result.values / evidence_weight), evidence_weight, order, width


def exhaustive(factors, query, evidence=None):
    evidence = {} if evidence is None else dict(evidence)
    sizes = {}
    for factor in factors:
        for variable, size in zip(factor.scope, factor.values.shape):
            if variable in sizes and sizes[variable] != size:
                raise ValueError('cardinalidades incompatibles')
            sizes[variable] = size
    variables = tuple(sizes)
    out = np.zeros(tuple(sizes[v] for v in query))
    for values in product(*(range(sizes[v]) for v in variables)):
        state = dict(zip(variables, values))
        if any(state[v] != x for v, x in evidence.items()):
            continue
        weight = np.prod([factor.values[tuple(state[v] for v in factor.scope)] for factor in factors])
        out[tuple(state[v] for v in query)] += weight
    if out.sum() <= 0:
        raise ValueError('evidencia con peso cero')
    return out/out.sum(), out.sum()
[ ]Family EM with exact inferenceBrowser
"""EM para una red binaria: usa BayesNet y Factor de las lecciones 2 y 4."""
import itertools
import numpy as np


class GraphEM(BayesNet):
    def factors(self):
        factors=[]
        for node in self.nodes:
            parents=tuple(self.parents[node]);table=np.zeros((2,)*(len(parents)+1))
            for state in itertools.product((0,1),repeat=len(parents)):
                q=self.probs[node][state]
                table[state+(0,)]=1-q;table[state+(1,)]=q
            factors.append(Factor(parents+(node,),table))
        return factors

    def expected_counts(self, patterns):
        """patterns es lista de (evidencia observada, frecuencia)."""
        counts={node:np.zeros((2,)*(len(self.parents[node])+1)) for node in self.nodes}
        factors=self.factors();loglik=0.
        for evidence,frequency in patterns:
            _,weight,_,_=variable_elimination(factors,(),evidence)
            loglik+=frequency*np.log(weight)
            for node in self.nodes:
                family=tuple(self.parents[node])+(node,)
                hidden=tuple(v for v in family if v not in evidence)
                marginal,_,_,_=variable_elimination(factors,hidden,evidence)
                for assignment in itertools.product((0,1),repeat=len(hidden)):
                    state={**evidence,**dict(zip(hidden,assignment))}
                    index=tuple(state[v] for v in family)
                    counts[node][index]+=frequency*marginal.values[assignment]
        return counts,loglik

    def m_step(self, counts, pseudo=0.):
        if pseudo<0:raise ValueError('pseudo debe ser no negativo')
        for node in self.nodes:
            for state in itertools.product((0,1),repeat=len(self.parents[node])):
                n0,n1=counts[node][state]
                if n0+n1+2*pseudo>0:
                    self.probs[node][state]=(n1+pseudo)/(n0+n1+2*pseudo)

    def fit_em(self,patterns,steps=30,pseudo=0.):
        history=[]
        for _ in range(steps):
            counts,ll=self.expected_counts(patterns)
            penalty=pseudo*sum(np.log(q)+np.log1p(-q) for node in self.nodes for q in self.probs[node].values()) if pseudo else 0.
            history.append((ll,ll+penalty))
            self.m_step(counts,pseudo)
        _,ll=self.expected_counts(patterns)
        penalty=pseudo*sum(np.log(q)+np.log1p(-q) for node in self.nodes for q in self.probs[node].values()) if pseudo else 0.
        history.append((ll,ll+penalty))
        return np.asarray(history)


def compress_patterns(rows, observed):
    """Agrupa filas observadas idénticas sin utilizar sus valores ocultos."""
    counts={}
    for row in rows:
        key=tuple(row[v] for v in observed);counts[key]=counts.get(key,0)+1
    return [(dict(zip(observed,key)),n) for key,n in counts.items()]

The experiment generates 3000 rows from a diagnostic network with one binary cause and three symptoms. The cause is hidden, the eight observable patterns are grouped and one hundred ML iterations run. True parameters are available only because the data are synthetic. A second fit adds 0.3 to each count for the MAP of a Beta(1.3,1.3) prior: we verify monotonicity of the penalized objective, rather than assume it for bare likelihood.

[ ]EM for a hidden causeBrowser
parents={'D':[],'S1':['D'],'S2':['D'],'S3':['D']}
true={'D':{():.4},'S1':{(0,):.15,(1,):.8},'S2':{(0,):.2,(1,):.7},'S3':{(0,):.1,(1,):.75}}
start={'D':{():.5},'S1':{(0,):.25,(1,):.75},'S2':{(0,):.3,(1,):.8},'S3':{(0,):.2,(1,):.65}}
data=BayesNet(parents,true).sample(3000,seed=22)
patterns=compress_patterns(data,['S1','S2','S3'])
net=GraphEM(parents,start)
counts_family,ll=net.expected_counts(patterns)
assert all(np.isclose(counts_family[x].sum(),len(data)) for x in parents)
history=net.fit_em(patterns,steps=100,pseudo=0)
print('log-verosimilitud inicial y final:',history[0,0],history[-1,0],
      'menor cambio:',np.diff(history[:,0]).min())
print('tablas ajustadas:',net.probs,'tablas verdaderas:',true)
assert np.diff(history[:,0]).min()>-1e-8
net2=GraphEM(parents,{'D':{():.5},'S1':{(0,):.25,(1,):.75},
                     'S2':{(0,):.3,(1,):.8},'S3':{(0,):.2,(1,):.65}})
h=net2.fit_em(patterns,steps=30,pseudo=.3)
print('menor cambio de objetivo MAP:',np.diff(h[:,1]).min(),
      'menor cambio de log-verosimilitud:',np.diff(h[:,0]).min())
assert np.diff(h[:,1]).min()>-1e-8

This network is small enough to sum exactly and compare with truth up to switching D’s labels. One trajectory does not show that every initialization reaches the same maximum. The implementation keeps a table without data if its denominator is zero; a positive proper prior makes the update defined.

A Bernoulli mixture over digits

The scikit-learn load_digits dataset contains small real digit images. We binarize each pixel at threshold 8 and fit a mixture of ten independent per-pixel Bernoulli distributions. Its E-step analytically eliminates the single label; its M-step normalizes expected counts. Each probability is constrained to [10−6,1−10−6][10^{-6},1-10^{-6}] to avoid infinite logarithms. True generating parameters are not available for these digits.

[ ]Bernoulli mixtureBrowser
"""Mezcla Bernoulli binaria, EM con probabilidades restringidas."""
import numpy as np
from scipy.special import logsumexp


def bernoulli_estep(X,pi,means):
    logjoint=np.log(pi)+X@np.log(means).T+(1-X)@np.log1p(-means).T
    norm=logsumexp(logjoint,axis=1)
    return np.exp(logjoint-norm[:,None]),norm.sum()


def bernoulli_em(X,K,seed=3,steps=30,eps=1e-6):
    X=np.asarray(X,float)
    rng=np.random.default_rng(seed)
    means=rng.uniform(.2,.8,(K,X.shape[1]));pi=np.full(K,1/K)
    history=[]
    for _ in range(steps):
        r,ll=bernoulli_estep(X,pi,means);history.append(ll)
        totals=r.sum(axis=0)
        pi=totals/totals.sum()
        means=np.clip((r.T@X)/totals[:,None],eps,1-eps)
    r,ll=bernoulli_estep(X,pi,means);history.append(ll)
    return pi,means,np.asarray(history),r
[ ]Fit binarized digitsBrowser
from sklearn.datasets import load_digits
from scipy.optimize import linear_sum_assignment
digits=load_digits();X_digits=(digits.data>=8).astype(float);labels=digits.target
rng=np.random.default_rng(5);order=rng.permutation(len(X_digits));train,test=order[:1400],order[1400:]
pi,means,h,r=bernoulli_em(X_digits[train],10,steps=35)
print('formas y partición:',X_digits.shape,len(train),len(test))
print('log-verosimilitud inicial y final, menor cambio:',h[0],h[-1],np.diff(h).min())
print('log-verosimilitud media en prueba:',bernoulli_estep(X_digits[test],pi,means)[1]/len(test))
assert np.diff(h).min()>-1e-8
trainpred=r.argmax(axis=1);cross=np.zeros((10,10),int)
for k,v in zip(trainpred,labels[train]):cross[k,v]+=1
row,col=linear_sum_assignment(-cross);mapping=np.zeros(10,int);mapping[row]=col
testpred=bernoulli_estep(X_digits[test],pi,means)[0].argmax(axis=1)
print('exactitud de prueba tras alinear con etiquetas de entrenamiento:',
      np.mean(mapping[testpred]==labels[test]),'asignación:',mapping)

Digit labels are used after fitting the mixture to align components with names using training data only. Test accuracy measures that particular rule; it does not turn unsupervised fitting into supervised classification or guarantee each component represents a single digit.

[ ]Inspect learned templatesBrowser
import matplotlib.pyplot as plt
fig,axes=plt.subplots(2,5,figsize=(9,4),constrained_layout=True)
for k,ax in enumerate(axes.flat):
    ax.imshow(means[k].reshape(8,8),vmin=0,vmax=1,cmap='gray_r')
    ax.set_title(f'{k} → {mapping[k]}',fontsize=10);ax.axis('off')
plt.show()

Each title shows the component index and digit label assigned with training data. A template is the estimated probability of activating each pixel, not an observed image.

Lab: mixture of experts

Experts are lines with known Gaussian noise σ=0.12\sigma=0.12 and a softmax gate with linear logits. The last logit is fixed to zero. Lines are updated by weighted least squares; the gate improves its objective using Newton or multinomial IRLS with line search, so this is generalized EM. Fixing noise avoids variance collapse, although a separable gate can still produce very large parameters.

[ ]Generalized EM for expertsBrowser
"""EM generalizado: expertos lineales gaussianos y compuerta softmax."""
import numpy as np
from scipy.special import logsumexp


def gating(X,V):
    logits=np.column_stack((X@V.T,np.zeros(len(X))))
    return np.exp(logits-logsumexp(logits,axis=1,keepdims=True))


def e_step(X,y,W,V,sigma):
    logits=np.column_stack((X@V.T,np.zeros(len(X))))
    log_gate=logits-logsumexp(logits,axis=1,keepdims=True)
    residual=(y[:,None]-X@W.T)/sigma
    scores=log_gate-.5*residual**2-np.log(sigma*np.sqrt(2*np.pi))
    normalizer=logsumexp(scores,axis=1)
    return np.exp(scores-normalizer[:,None]),normalizer.sum()


def m_step(X,y,responsibilities,W,V):
    K=len(W);new_W=W.copy()
    for k in range(K):
        weight=np.sqrt(responsibilities[:,k])
        if np.sum(weight**2)>1e-10:
            new_W[k]=np.linalg.lstsq(weight[:,None]*X,weight*y,rcond=None)[0]
    if K==1:return new_W,V.copy()
    def loss(matrix):
        logits=np.column_stack((X@matrix.T,np.zeros(len(X))))
        logp=logits-logsumexp(logits,axis=1,keepdims=True)
        return -np.sum(responsibilities*logp),np.exp(logp)
    new_V=V.copy();d=X.shape[1]
    for _ in range(20):
        value,p=loss(new_V)
        gradient=((p[:,:-1]-responsibilities[:,:-1]).T@X).ravel()
        if np.linalg.norm(gradient,np.inf)<1e-7:break
        H=np.zeros(((K-1)*d,(K-1)*d))
        for a in range(K-1):
            for b in range(K-1):
                weights=p[:,a]*((1. if a==b else 0.)-p[:,b])
                H[a*d:(a+1)*d,b*d:(b+1)*d]=X.T@(weights[:,None]*X)
        direction=np.linalg.lstsq(H,gradient,rcond=1e-12)[0].reshape(V.shape)
        rate=1.
        while rate>1e-10 and loss(new_V-rate*direction)[0]>value-1e-4*rate*(gradient@direction.ravel()):
            rate*=.5
        if rate<=1e-10:break
        new_V-=rate*direction
    return new_W,new_V


def fit_moe(X,y,K,sigma,seed=0,steps=40):
    rng=np.random.default_rng(seed)
    W=rng.normal(0,1,(K,X.shape[1]))
    V=rng.normal(0,.3,(K-1,X.shape[1]))
    history=[]
    for _ in range(steps):
        r,ll=e_step(X,y,W,V,sigma);history.append(ll)
        W,V=m_step(X,y,r,W,V)
    r,ll=e_step(X,y,W,V,sigma);history.append(ll)
    return W,V,np.asarray(history),r


def piece_data(seed,n):
    rng=np.random.default_rng(seed)
    x=rng.uniform(-1,1,n)
    truth=np.where(x<-.3,1.3+2.2*x,np.where(x<.35,.55-3.2*x,-1.1+1.9*x))
    return np.column_stack((np.ones(n),x)),truth+.12*rng.normal(size=n),truth
[ ]Fit experts and compare initializationsBrowser
X_moe,y_moe,truth_moe=piece_data(10,300)
X_test_moe,y_test_moe,test_truth=piece_data(11,600)
fits=[]
for seed in (0,2,3):
    W,V,history_moe,responsibilities=fit_moe(X_moe,y_moe,3,.12,seed=seed,steps=50)
    pred=np.sum(gating(X_test_moe,V)*(X_test_moe@W.T),axis=1)
    print('semilla:',seed,'log-verosimilitud inicial y final:',history_moe[0],history_moe[-1],
          'menor incremento:',np.diff(history_moe).min(),
          'RMSE frente a función conocida en prueba:',np.sqrt(np.mean((pred-test_truth)**2)))
    print('expertos:',W,'máximo absoluto de coeficientes de compuerta:',np.max(abs(V)))
    assert np.diff(history_moe).min()>-1e-6
    fits.append((W,V,history_moe))

Error compares with the known function at new test points; in real data that truth would not be available. Initializations can lead to different solutions. Huge gate values indicate near separation and warn of an ill-conditioned fit: an explicit penalty changes the objective and must be included in diagnostics.

[ ]Compare with a neural networkBrowser
from sklearn.neural_network import MLPRegressor
mlp=MLPRegressor(hidden_layer_sizes=(30,30),activation='tanh',solver='lbfgs',
                 max_iter=500,random_state=42).fit(X_moe,y_moe)
pred_mlp=mlp.predict(X_test_moe)
print('iteraciones MLP:',mlp.n_iter_,'límite:',mlp.max_iter,
      'RMSE frente a función conocida en prueba:',np.sqrt(np.mean((pred_mlp-test_truth)**2)))

Both models train on the same data and are evaluated on the same points, but this single configuration does not establish a general ranking. If the MLP reaches its iteration limit, it is reported as an unconverged run; varying architecture and optimization is part of a broader comparison.

Exercises

ProofExpected counts by family
Prove: Derive the maximum-likelihood M-step for a conditional table of a Bayesian network with hidden nodes.
0
The E-step uses the exact posterior under the previous parameters.

Step 1 of 3. Which distribution do you need for counts of a node and its parents?

Numeric
An LDA has 1000 documents of 200 words, 20 topics and a vocabulary of 5000 words. How many global free parameters do the topic word distributions have?
Quiz
Which is a correct distinction between global and local variables?
Quiz
Ten mixture restarts give similar parameters with different labels. What goes wrong when averaging directly by index?
CodeOne EM step for experts
Implement moe_step(X,y,W,V,sigma). X has shape (n,d), W (K,d), V (K−1,d), and the final gate logit is zero. Use normal experts with standard deviation sigma, exact responsibilities, weighted least squares and BFGS to improve the gate. Return (W_new,V_new). Tests check monotonicity and fitting of two synthetic segments.
import numpy as np
def moe_step(X,y,W,V,sigma):
  return W,V
Shift+Enter to run
Key idea
In graphical EM, the E-step obtains family marginals and the M-step normalizes expected counts. Local variables allow mixed membership or input-dependent regimes; their symmetries must be handled when comparing results.