Bayesian model comparison and structure learning
Evidence (m05) compares models with different numbers of parameters without a validation set; here we learn to approximate and use it. We study the Occam factor, the derivation of BIC from Laplace and its limits in singular models, and Bayesian model averaging, applying these ideas to Bayesian network structure learning with BIC and BDeu scores, local search and Chow-Liu trees.
After this lesson you can
- Decompose evidence into fit times the Occam factor and use it to explain Bayesian Occam's razor.
- Derive BIC from Laplace evidence, list its assumptions and recognize when it fails in singular models.
- Build predictions by Bayesian model averaging and compare them with selection of a single model.
- Calculate BDeu as the exact evidence of a Dirichlet-multinomial family and compare it with BIC.
- Learn Bayesian network structure using local search and Chow-Liu, and recognize Markov equivalence classes.
Before you start
- 14Laplace approximation to the evidenceLaplace approximationEvidence approximation (type-II maximum likelihood)Bayesian networkParameter learning in Bayesian networksd-separation
- 05Marginal likelihood (evidence)Bayes factor and the Jeffreys-Lindley paradox
- 07Mutual information
- 08Kruskal algorithmPrim algorithm
- 12Mixture model selection
Comparing hypotheses with the same coin
Does a more complicated relationship explain the data better or merely memorize them? The evidence for a model averages its likelihood over a normalized proper prior:
Posterior model probabilities are proportional to evidence times prior model probability. A Bayes factor alone is not the posterior probability of a hypothesis. Evidences must refer to the same observations and measure; transforming the response requires including the Jacobian. An improper prior does not define its normalization and generally does not provide comparable evidence.
The result depends on prior scale. In the Jeffreys-Lindley paradox a point null test can have a small value while a Bayes factor favors the null as the alternative prior spreads out: it answers a different question and distributes mass over many possible values. This is not a recipe for choosing arbitrarily wide priors.
Fit and volume
The Bayesian Occam’s razor appears through integration. Near an interior mode with positive-definite negative Hessian , Laplace approximates the evidence by
This is local fit multiplied by prior density and posterior volume. In one dimension, with normal prior and posterior centered approximately at the same point, the standard deviation ratio illustrates the volume factor. If the mode moves away from the prior mean, a prior density penalty also appears: the ratio alone is not the whole evidence.
The point model predicts mean zero; the others assign normal priors of different widths to the mean. The figure compares the density of the sample mean under each model, not the full dataset density. The wide model covers more possible outcomes and therefore assigns less density to some. A distant observation can favor it, but the winner depends on scales and model priors, not a rule that always rewards simplicity.
The comparison requires distinguishing curve height from area. Each marginal density integrates to one: as it widens, it cannot maintain the same height everywhere. Evidence does not directly reward flexibility, but the probability the model assigned to the observed result before seeing it. If we move the observation far enough, the narrower model assigns little density and a wide alternative can win. If the prior on the mean becomes infinitely wide, the density of any fixed observation tends to zero. Prior scale is therefore a substantive part of the comparison.
From Laplace to BIC
If there are independent observations, identifiable parameters, an interior mode and a positive, smooth prior near the maximum, observed information scales as . The Hessian determinant contributes and
BIC is usually presented as : lower is better. Here we also use the equivalent score , which is maximized. The terms include prior density and per-observation information. They need not tend to zero and can matter in small samples or when comparing models.
The coin example uses and . For heads in tosses, the exact factor for the sequence is ; the count’s binomial coefficient cancels in the ratio. With a fixed interior proportion, the difference between the exact log factor and the BIC approximation tends to a prior-dependent constant. If the proportion is exactly 1/2, the linear slope is zero and the logarithmic term dominates.
AIC uses and targets predictive risk under its own conditions; it is not evidence and does not use BIC’s penalty. In mixtures with exchangeable components, unidentified parameters or mixture weights on a boundary, the Hessian can be singular. The same can happen in neural networks. There the regular BIC derivation is invalid and asymptotic complexity can have another form. A fully observed, regular discrete Bayesian network does not become singular simply by being a network.
The limit does not justify blindly using the approximation on a small dataset. Check whether the solution is far from boundaries and the information matrix has full rank. A parameter that does not alter predictions is not an identifiable quadratic direction, even if it appears in the code. The local Laplace approximation also does not automatically represent several separated modes. BIC removes constants dependent on geometry and the prior, so two approximations with the same dominant trend can differ materially in a particular comparison.
Averaging models
The model-averaged predictive distribution is
Total variance adds the variance within each model and the variance of their weighted means. Choosing the most probable model omits the latter uncertainty; it does not guarantee worse prediction on every sample. The average remains conditional on the model list, their priors and the noise model.
Data are generated with one of the indicated functions, known normal noise and a visible seed. Models are polynomials of degree 1 to 6 with an independent normal prior of standard deviation 3 on each weight and equal initial probabilities. The bands represent the mean plus or minus 1.96 predictive standard deviations; the mixture is not necessarily normal and those bands are not necessarily 95% probability intervals. Coverage and densities are measured on 300 test data points; repetition uses 150 per set.
When no family contains the truth, the posterior can concentrate on the candidate that best approximates the generating distribution according to its divergence, without making it true. Stacking chooses weights that maximize the log density of an out-of-sample validated predictive mixture, here using leave-one-out. This is a different objective, not a posterior over models; nor does it guarantee better performance on every dataset. Using test data to fit weights would invalidate independent evaluation.
Each leave-one-out fit removes one observation and evaluates its predictive density under the model trained on the rest. Nonnegative weights summing to one are then chosen to maximize the sum of log mixtures of those densities. A combination can exploit different errors among models; it can also overfit the weights when there are few data or many alternatives. The whole procedure should be evaluated with additional data or outer validation. Stacking and BMA bars answer different questions even though both sum to one.
Structures for discrete networks
In structure learning, each node with states and parent configurations contributes a family. Structure search combines those scores and traverses DAGs without cycles. With complete data and independent multinomial parameters, BIC sums local log likelihoods and penalizes parameters.
BDeu is exact Dirichlet-multinomial evidence for each family under its assumptions. If is the count of state with parent configuration , and is the equivalent sample size,
The prior distributes uniformly among cells; its decisions change as varies. The formula scores the sequence of rows under the factorization, not the probability of a count table without its multinomial coefficient. Do not confuse with a number of real observations.
For example, a binary variable with no parents has one row and two prior cells of mass . With a binary parent there are two rows and each cell receives ; the entire family still sums to . Configurations with no observations remain present and their contribution cancels to zero. Ignoring them when building the table changes the prior and the score. Decomposition lets us evaluate an edge operation by recalculating only the affected family, or two families for a reversal.
The Asia network is the one from m14-l02: eight binary variables and explicit tables, including the deterministic variable “tuberculosis or cancer.” The data are simulated from that network, not patients. Each step proposes valid moves, evaluates the local difference and accepts the largest positive increase. The figure allows up to four parents per node; the lab uses three. Caching avoids recalculating identical families. The result depends on the start, constraints and tie-breaking; it does not guarantee the globally best DAG.
Two DAGs are Markov equivalent exactly when they share a skeleton and v-structures unshielded by an edge between their parents. Observational data alone do not orient the reversible edges of the class. A learned arrow does not prove causality either. The Asia network includes a deterministic table: regular approximation’s interior conditions can fail for that particular distribution. The interactive compares classes; the lab separately reports a DAG SHD that counts reversal as one operation and can penalize equivalent orientations.
The best tree
In a tree directed from a root, empirical maximum likelihood uses the empirical marginal and conditional distributions. Its per-observation log likelihood is
The first term does not depend on the tree. The Chow-Liu algorithm obtains the maximum by choosing a maximum spanning tree with empirical mutual information as weight. A root can then be chosen and edges directed outward. Ties can yield several optimal trees and orientation alone does not demonstrate causality.
With few data, mutual-information estimates are noisy and weak edges can change order. The interactive offers a synthetic ten-node tree and the Asia network, whose skeleton is not a tree. The best tree for Asia is an approximation, not full recovery. The exact version of the plot sums the known finite joint distribution; the empirical one depends on the sample. A forest or additional constraints change the optimization problem.
Kruskal sorts candidate edges by decreasing weight and adds each if it connects distinct components. A structure with connected nodes and no cycles contains edges; once that number is reached the procedure stops. Mutual information measures statistical dependence, not direction or intervention. If strong indirect dependence is observed, the maximum tree decides globally which dependencies it can represent, but does not necessarily recover the underlying causal mechanism.
Lab: scoring and search
The following engine uses family counts, BDeu and BIC, local search from the empty DAG and Kruskal. Cardinalities are given explicitly, including states that have not appeared in the sample.
"""Puntuaciones discretas, ascenso de colina y árbol de Chow-Liu."""
from functools import lru_cache
from itertools import combinations
import numpy as np
from scipy.special import gammaln, xlogy
ASIA_NAMES = ('asia','smoke','tub','lung','bronc','either','xray','dysp')
ASIA_PARENTS = ((),(),(0,),(1,),(1,),(2,3),(5,),(4,5))
ASIA_CPT = ((.01,),(.5,),(.01,.05),(.01,.1),(.3,.6),
(0.,1.,1.,1.),(.05,.98),(.1,.7,.8,.9))
def sample_asia(n, seed=1):
"""Cada columna es binaria; reproduce las tablas de la lección m14-l02."""
rng=np.random.default_rng(seed)
x=np.zeros((n,8),dtype=int)
for j,ps in enumerate(ASIA_PARENTS):
ix=np.zeros(n,dtype=int)
for p in ps: ix=2*ix+x[:,p]
x[:,j]=(rng.random(n)<np.asarray(ASIA_CPT[j])[ix]).astype(int)
return x
def family_counts(data, node, parents, cardinalities):
"""Filas: configuraciones de padres; columnas: estados del nodo."""
data=np.asarray(data,dtype=int)
parents=tuple(sorted(parents)); r=cardinalities[node]
q=int(np.prod([cardinalities[p] for p in parents],dtype=int))
ix=np.zeros(len(data),dtype=int)
for p in parents: ix=ix*cardinalities[p]+data[:,p]
counts=np.zeros((q,r),dtype=int)
np.add.at(counts,(ix,data[:,node]),1)
return counts
def bdeu(counts, ess=1.):
"""Log evidencia de una familia para una secuencia de observaciones."""
counts=np.asarray(counts,dtype=float)
if ess<=0: raise ValueError('ESS debe ser positivo')
q,r=counts.shape
return float(np.sum(gammaln(ess/q)-gammaln(ess/q+counts.sum(axis=1))
+np.sum(gammaln(ess/(q*r)+counts)-gammaln(ess/(q*r)),axis=1)))
def bic(counts):
"""Puntuación a maximizar: log-verosimilitud menos k log(n)/2."""
counts=np.asarray(counts,dtype=float); n=counts.sum()
if n<=0: raise ValueError('Se necesita al menos una observación')
totals=counts.sum(axis=1,keepdims=True)
probs=np.divide(counts,totals,out=np.ones_like(counts),where=totals>0)
return float(xlogy(counts,probs).sum()-.5*counts.shape[0]*(counts.shape[1]-1)*np.log(n))
def scorer(data, cardinalities, kind='bic', ess=1.):
if kind not in ('bic','bdeu'): raise ValueError('Puntuación desconocida')
@lru_cache(maxsize=None)
def local(node, parents):
counts=family_counts(data,node,parents,cardinalities)
return bic(counts) if kind=='bic' else bdeu(counts,ess)
return local
def acyclic(parents):
d=len(parents); state=np.zeros(d,dtype=int)
def visit(v):
if state[v]==1:return False
if state[v]==2:return True
state[v]=1
if not all(visit(p) for p in parents[v]):return False
state[v]=2
return True
return all(visit(i) for i in range(d))
def hill_climb(data, cardinalities, kind='bic', ess=1., max_parents=3, tol=1e-10):
"""DAG vacío, movimientos de una arista y mejora estricta; óptimo local."""
d=data.shape[1]; local=scorer(data,cardinalities,kind,ess)
parents=[set() for _ in range(d)]
trace=[sum(local(i,()) for i in range(d))]
while True:
best=tol; chosen=None
for a in range(d):
for b in range(d):
if a==b:continue
if a in parents[b]:
operations=('del','reverse')
elif b not in parents[a] and len(parents[b])<max_parents:
operations=('add',)
else:continue
for op in operations:
new=[s.copy() for s in parents]
if op=='add':new[b].add(a)
else:
new[b].remove(a)
if op=='reverse':
if len(new[a])>=max_parents:continue
new[a].add(b)
if not acyclic(new):continue
changed=(b,a) if op=='reverse' else (b,)
delta=sum(local(i,tuple(sorted(new[i])))-local(i,tuple(sorted(parents[i]))) for i in changed)
if delta>best:best,chosen=delta,new
if chosen is None:break
parents=chosen
trace.append(sum(local(i,tuple(sorted(parents[i]))) for i in range(d)))
return tuple(tuple(sorted(s)) for s in parents),np.array(trace)
def shd(a,b):
"""Adición, eliminación o inversión de una arista cuesta una unidad."""
d=len(a);total=0
for i,j in combinations(range(d),2):
ea=1 if i in a[j] else -1 if j in a[i] else 0
eb=1 if i in b[j] else -1 if j in b[i] else 0
total+=ea!=eb
return int(total)
def mutual_information(data, i, j, cardinalities):
counts=np.zeros((cardinalities[i],cardinalities[j]),dtype=float)
np.add.at(counts,(data[:,i],data[:,j]),1)
p=counts/counts.sum(); pi=p.sum(axis=1); pj=p.sum(axis=0)
expected=pi[:,None]*pj[None,:]
valid=p>0
return float(np.sum(p[valid]*np.log(p[valid]/expected[valid])))
def chow_liu(data, cardinalities):
"""Árbol no dirigido de expansión máximo por información mutua."""
d=data.shape[1]
edges=sorted(((mutual_information(data,i,j,cardinalities),i,j)
for i,j in combinations(range(d),2)),key=lambda t:(-t[0],t[1],t[2]))
parent=list(range(d))
def root(i):
while parent[i]!=i:
parent[i]=parent[parent[i]];i=parent[i]
return i
tree=[]
for weight,i,j in edges:
a,b=root(i),root(j)
if a!=b:
parent[a]=b;tree.append((i,j,weight))
if len(tree)==d-1:break
return treeSimulate 3000 Asia rows with seed 1 and compare three prefixes. Directed SHD compares with the generating DAG: a reversal costs one, even if it belongs to an equivalent class. The results come from one realization and do not establish a monotonic trend with sample size.
data=sample_asia(3000,seed=1);card=[2]*8
for method in ('bic','bdeu'):
for n in (100,1000,3000):
parents,trace=hill_climb(data[:n],card,method,ess=1.,max_parents=3)
print(method,'n',n,'aristas',sum(map(len,parents)),
'SHD dirigido',shd(parents,ASIA_PARENTS),'pasos',len(trace)-1)
assert acyclic(parents) and np.all(np.diff(trace)>0)
tree=chow_liu(data,card)
print('Árbol: índices de nodos y MI en nats',tree)
The following local cell includes the same engine and compares families and searches with pgmpy. It requires pgmpy and pandas installed locally. Available versions may warn that the estimator interface has become deprecated. Tie-breaking orders and local search may produce different graphs; we compare scores, not require the same graph.
"""Puntuaciones discretas, ascenso de colina y árbol de Chow-Liu."""
from functools import lru_cache
from itertools import combinations
import numpy as np
from scipy.special import gammaln, xlogy
ASIA_NAMES = ('asia','smoke','tub','lung','bronc','either','xray','dysp')
ASIA_PARENTS = ((),(),(0,),(1,),(1,),(2,3),(5,),(4,5))
ASIA_CPT = ((.01,),(.5,),(.01,.05),(.01,.1),(.3,.6),
(0.,1.,1.,1.),(.05,.98),(.1,.7,.8,.9))
def sample_asia(n, seed=1):
"""Cada columna es binaria; reproduce las tablas de la lección m14-l02."""
rng=np.random.default_rng(seed)
x=np.zeros((n,8),dtype=int)
for j,ps in enumerate(ASIA_PARENTS):
ix=np.zeros(n,dtype=int)
for p in ps: ix=2*ix+x[:,p]
x[:,j]=(rng.random(n)<np.asarray(ASIA_CPT[j])[ix]).astype(int)
return x
def family_counts(data, node, parents, cardinalities):
"""Filas: configuraciones de padres; columnas: estados del nodo."""
data=np.asarray(data,dtype=int)
parents=tuple(sorted(parents)); r=cardinalities[node]
q=int(np.prod([cardinalities[p] for p in parents],dtype=int))
ix=np.zeros(len(data),dtype=int)
for p in parents: ix=ix*cardinalities[p]+data[:,p]
counts=np.zeros((q,r),dtype=int)
np.add.at(counts,(ix,data[:,node]),1)
return counts
def bdeu(counts, ess=1.):
"""Log evidencia de una familia para una secuencia de observaciones."""
counts=np.asarray(counts,dtype=float)
if ess<=0: raise ValueError('ESS debe ser positivo')
q,r=counts.shape
return float(np.sum(gammaln(ess/q)-gammaln(ess/q+counts.sum(axis=1))
+np.sum(gammaln(ess/(q*r)+counts)-gammaln(ess/(q*r)),axis=1)))
def bic(counts):
"""Puntuación a maximizar: log-verosimilitud menos k log(n)/2."""
counts=np.asarray(counts,dtype=float); n=counts.sum()
if n<=0: raise ValueError('Se necesita al menos una observación')
totals=counts.sum(axis=1,keepdims=True)
probs=np.divide(counts,totals,out=np.ones_like(counts),where=totals>0)
return float(xlogy(counts,probs).sum()-.5*counts.shape[0]*(counts.shape[1]-1)*np.log(n))
def scorer(data, cardinalities, kind='bic', ess=1.):
if kind not in ('bic','bdeu'): raise ValueError('Puntuación desconocida')
@lru_cache(maxsize=None)
def local(node, parents):
counts=family_counts(data,node,parents,cardinalities)
return bic(counts) if kind=='bic' else bdeu(counts,ess)
return local
def acyclic(parents):
d=len(parents); state=np.zeros(d,dtype=int)
def visit(v):
if state[v]==1:return False
if state[v]==2:return True
state[v]=1
if not all(visit(p) for p in parents[v]):return False
state[v]=2
return True
return all(visit(i) for i in range(d))
def hill_climb(data, cardinalities, kind='bic', ess=1., max_parents=3, tol=1e-10):
"""DAG vacío, movimientos de una arista y mejora estricta; óptimo local."""
d=data.shape[1]; local=scorer(data,cardinalities,kind,ess)
parents=[set() for _ in range(d)]
trace=[sum(local(i,()) for i in range(d))]
while True:
best=tol; chosen=None
for a in range(d):
for b in range(d):
if a==b:continue
if a in parents[b]:
operations=('del','reverse')
elif b not in parents[a] and len(parents[b])<max_parents:
operations=('add',)
else:continue
for op in operations:
new=[s.copy() for s in parents]
if op=='add':new[b].add(a)
else:
new[b].remove(a)
if op=='reverse':
if len(new[a])>=max_parents:continue
new[a].add(b)
if not acyclic(new):continue
changed=(b,a) if op=='reverse' else (b,)
delta=sum(local(i,tuple(sorted(new[i])))-local(i,tuple(sorted(parents[i]))) for i in changed)
if delta>best:best,chosen=delta,new
if chosen is None:break
parents=chosen
trace.append(sum(local(i,tuple(sorted(parents[i]))) for i in range(d)))
return tuple(tuple(sorted(s)) for s in parents),np.array(trace)
def shd(a,b):
"""Adición, eliminación o inversión de una arista cuesta una unidad."""
d=len(a);total=0
for i,j in combinations(range(d),2):
ea=1 if i in a[j] else -1 if j in a[i] else 0
eb=1 if i in b[j] else -1 if j in b[i] else 0
total+=ea!=eb
return int(total)
def mutual_information(data, i, j, cardinalities):
counts=np.zeros((cardinalities[i],cardinalities[j]),dtype=float)
np.add.at(counts,(data[:,i],data[:,j]),1)
p=counts/counts.sum(); pi=p.sum(axis=1); pj=p.sum(axis=0)
expected=pi[:,None]*pj[None,:]
valid=p>0
return float(np.sum(p[valid]*np.log(p[valid]/expected[valid])))
def chow_liu(data, cardinalities):
"""Árbol no dirigido de expansión máximo por información mutua."""
d=data.shape[1]
edges=sorted(((mutual_information(data,i,j,cardinalities),i,j)
for i,j in combinations(range(d),2)),key=lambda t:(-t[0],t[1],t[2]))
parent=list(range(d))
def root(i):
while parent[i]!=i:
parent[i]=parent[parent[i]];i=parent[i]
return i
tree=[]
for weight,i,j in edges:
a,b=root(i),root(j)
if a!=b:
parent[a]=b;tree.append((i,j,weight))
if len(tree)==d-1:break
return tree
"""Ejecutar localmente después de structure.py: comparación con pgmpy."""
import pandas as pd
from pgmpy.estimators import HillClimbSearch, BIC, BDeu
from pgmpy.base import DAG
data=sample_asia(1000,seed=1)
frame=pd.DataFrame(data,columns=ASIA_NAMES)
states={name:[0,1] for name in ASIA_NAMES}
own_bic=scorer(data,[2]*8,'bic')
own_bdeu=scorer(data,[2]*8,'bdeu',1.)
scores=(('bic',BIC(frame,state_names=states),own_bic),
('bdeu',BDeu(frame,state_names=states,equivalent_sample_size=1),own_bdeu))
for name,library,own in scores:
differences=[]
for node,ps in enumerate(ASIA_PARENTS):
differences.append(abs(library.local_score(ASIA_NAMES[node],
[ASIA_NAMES[p] for p in ps])-own(node,ps)))
learned=HillClimbSearch(frame,state_names=states).estimate(
scoring_method=library,max_indegree=3,tabu_length=0,
epsilon=1e-10,show_progress=False)
parents=tuple(tuple(sorted(ASIA_NAMES.index(p) for p in learned.predecessors(n)))
for n in ASIA_NAMES)
mine,trace=hill_climb(data,[2]*8,name,ess=1.,max_parents=3)
dag=DAG();dag.add_nodes_from(ASIA_NAMES)
dag.add_edges_from((ASIA_NAMES[p],ASIA_NAMES[v]) for v,ps in enumerate(mine) for p in ps)
print(name,'max family error',max(differences),
'own/library score',library.score(dag),library.score(learned),
'own/library SHD',shd(mine,ASIA_PARENTS),shd(parents,ASIA_PARENTS))
assert max(differences)<1e-8npm run lab and open the connection link.In a local run with pgmpy 1.1.2, the maximum error in family scores was of order . The custom and library algorithms can reach different local optima with BIC. The comparison does not identify a causal orientation and SHD against one DAG is a different measure from distance between equivalence classes.
Exercises
Step 1 of 3. How does the Hessian determinant scale?
Step 1 of 3. Which sum remains after fitting the tables?
import numpy as np
from scipy.special import gammaln
def bdeu_family(counts,alpha):
return NoneReferences
- Schwarz, Estimating the Dimension of a Model (1978).
- Chow and Liu, Approximating Discrete Probability Distributions with Dependence Trees (1968).
- Heckerman, Geiger and Chickering, Learning Bayesian Networks (1995).
- Yao, Vehtari, Simpson and Gelman, Using Stacking to Average Bayesian Predictive Distributions.