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
- 14Bayesian networkPlate notationAncestral samplingParameter learning in Bayesian networksVariable eliminationSum-product algorithm
- 12EM lower boundEM monotonicity and convergenceEM variantsGaussian mixture modelEM for Gaussian mixtures
- 04Beta and Dirichlet distributionsBernoulli-trial distributions
- 11Softmax (multinomial logistic) regression
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:
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 topics and vocabulary size , each topic is a distribution over words. Each document receives . At each position , generate and then . The original model of Blei, Ng and Jordan formalizes this idea.
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 , proportions concentrate near vertices; with large they cluster near . Parameter 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 . 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 , the prior of each and, within each document, the topic and word factors at each position. A topic plate shares 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 entries but only degrees of freedom; there are 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:
With Gaussian linear experts, the E-step calculates responsibilities proportional to . 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.
The figure uses 150 stratified inputs in , Gaussian noise with standard deviation 0.12 and three segments: for , up to and 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 indicates the expert is plausible before looking at , 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 , 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 and parent configuration :
The maximum-likelihood M-step normalizes each row: , 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.
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 , the interior MAP adds to each count; the posterior mean adds 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 and maximize under constraint . The multiplier condition equates to a constant; summing over 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.
The figure fits a Gaussian mixture to 240 synthetic points: 80 per component, with standard deviation 0.55 and base means , and 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 (including NULL), each alignment is uniform and the probability of a target word is
The E-step distributes each word among possible sources proportionally to ; 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.
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.
"""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,wordscounts,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.
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 . The E-step queries the joint marginal of unobserved variables in each family, conditioned on all observations, and reinserts observed states into the counts.
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))"""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()"""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.
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-8This 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 to avoid infinite logarithms. True generating parameters are not available for these digits.
"""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)[email protected](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),rfrom 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.
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 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.
"""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(([email protected],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(([email protected],np.zeros(len(X))))
log_gate=logits-logsumexp(logits,axis=1,keepdims=True)
residual=(y[:,None][email protected])/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(([email protected],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*([email protected]()):
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),truthX_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)*([email protected]),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.
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
Step 1 of 3. Which distribution do you need for counts of a node and its parents?
import numpy as np
def moe_step(X,y,W,V,sigma):
return W,V