Module contents
Lesson 8 of 27Core 110 min

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

Comparing hypotheses with the same coin

Does a more complicated relationship explain the data better or merely memorize them? The evidence for a model MM averages its likelihood over a normalized proper prior:

p(D∣M)=∫p(D∣θ,M)p(θ∣M)  ⁣dθ,BF⁡10=p(D∣M1)p(D∣M0).p(\Data\given M)=\int p(\Data\given\theta,M)p(\theta\given M)\,\dd\theta,\qquad \operatorname{BF}_{10}=\frac{p(\Data\given M_1)}{p(\Data\given M_0)}.

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 pp 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 θ^\hat\theta with positive-definite negative Hessian H\mat H, Laplace approximates the evidence by

p(D∣M)≈p(D∣θ^,M)p(θ^∣M)(2π)k/2∣H∣−1/2.p(\Data\given M)\approx p(\Data\given\hat\theta,M) p(\hat\theta\given M)(2\pi)^{k/2}|\mat H|^{-1/2}.

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 σpost/σprior\sigma_{\rm post}/\sigma_{\rm prior} 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.

InteractiveEvidence distributes mass
Evidence p(yˉ∣M)p(\bar y \mid M) of each model over possible data
Posterior probability of each model (uniform prior) as a function of the data
Cost of each model: −ln⁡p(yˉ∣M)-\ln p(\bar y \mid M) minus a constant = fit + Occam
Simple: μ = 03.13Intermediate: τ = 1.51.55Complex: τ = 6.01.89
  • fit cost (yˉ−m)2/2s2(\bar y - m)^2/2s^2
  • Occam cost −ln⁡(σpost/τ)+m2/2τ2-\ln(\sigma_{\text{post}}/\tau) + m^2/2\tau^2
2.50
9
6.0
P(simple∣yˉ)P(\text{simple} \mid \bar y)10.8 %
P(intermediate∣yˉ)P(\text{intermediate} \mid \bar y)52.1 %
P(complex∣yˉ)P(\text{complex} \mid \bar y)37.1 %
Noise of the mean, ss1.00
Bayes factor complex / intermediate0.712
Here the intermediate model wins: it assigns more observed density than the simple and complex models.
Move the observed mean and compare three Gaussian marginal distributions.

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 NN independent observations, kk identifiable parameters, an interior mode and a positive, smooth prior near the maximum, observed information scales as NN. The Hessian determinant contributes klog⁡Nk\log N and

log⁡p(D∣M)=log⁡p(D∣θ^ML,M)−k2log⁡N+O(1).\log p(\Data\given M)=\log p(\Data\given\hat\theta_{\rm ML},M) -\tfrac{k}{2}\log N+O(1).

BIC is usually presented as −2log⁡Lmax⁡+klog⁡N-2\log L_{\max}+k\log N: lower is better. Here we also use the equivalent score log⁡Lmax⁡−(k/2)log⁡N\log L_{\max}-(k/2)\log N, which is maximized. The O(1)O(1) terms include prior density and per-observation information. They need not tend to zero and can matter in small samples or when comparing models.

InteractiveBIC and exact evidence
Log Bayes factor of M1M_1 versus M0M_0, against log⁡10n\log_{10} n
  • exact (evidence)
  • BIC
  • AIC
BIC error: exact − BIC, against its theoretical limit
  • exact − BIC
  • limit
100
0.55
Prior for θ\theta in M1M_1
Observed heads ss of n=100n = 10055
ln⁡BF10\ln \mathrm{BF}_{10} exact−1.588
ln⁡BF10\ln \mathrm{BF}_{10} by BIC−1.802
Difference, exact − BIC0.2133
Limit ln⁡π(p^)+12ln⁡2π+12ln⁡p^(1−p^)\ln\pi(\hat p) + \tfrac12\ln 2\pi + \tfrac12\ln\hat p(1-\hat p)0.2208
By AIC, −ΔAIC/2-\Delta\mathrm{AIC}/2−0.499
With a fixed proportion other than 1/2, the leading term of ln⁡BF\ln\mathrm{BF} grows linearly in nn. At 1/2 that slope vanishes and the logarithmic penalty appears. BIC omits a prior-dependent constant: it is O(1)O(1) and does not vanish.
Compare the beta-binomial Bayes factor with BIC and AIC.

The coin example uses M0:θ=1/2M_0:\theta=1/2 and M1:θ∼Beta⁡(a,a)M_1:\theta\sim\operatorname{Beta}(a,a). For ss heads in NN tosses, the exact factor for the sequence is 2NB(s+a,N−s+a)/B(a,a)2^N B(s+a,N-s+a)/B(a,a); 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 −2log⁡Lmax⁡+2k-2\log L_{\max}+2k 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 N→∞N\to\infty 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

p(y∗∣D)=∑mp(y∗∣D,Mm) p(Mm∣D).p(y_*\given\Data)=\sum_m p(y_*\given\Data,M_m)\,p(M_m\given\Data).

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.

InteractiveAverage or choose
  • data
  • true function
  • best model ± 1.96 sd
  • BMA ± 1.96 sd
  • stacking ± 1.96 sd
Weight of each degree: posterior probability (uniform model prior, weight prior N(0,32)N(0, 3^2)) and stacking
00.51degree 1degree 2degree 3degree 4degree 5degree 6
  • posterior probability (BMA)
  • stacking weight
14
0.20
Dataset seed3
Highest-evidence modeldegree 2: 34 %
Predictive log density (test): best−1.435
Predictive log density: BMA−0.439
Predictive log density: stacking−0.332
Coverage of ±1.96 sd: best / BMA68 % / 92 %
Evidence is spread out (the best has 34 %): choosing one discards uncertainty between models, while averaging retains it.
Compare polynomial degrees, Bayesian averaging and stacking on new synthetic data.

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 XiX_i with rir_i states and qiq_i 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 ∑iqi(ri−1)\sum_i q_i(r_i-1) parameters.

BDeu is exact Dirichlet-multinomial evidence for each family under its assumptions. If NijkN_{ijk} is the count of state kk with parent configuration jj, Nij=∑kNijkN_{ij}=\sum_kN_{ijk} and α\alpha is the equivalent sample size,

log⁡p(Di∣Pai)=∑j=1qi[log⁡Γ(α/qi)−log⁡Γ(α/qi+Nij)+∑k=1ri{log⁡Γ(α/(qiri)+Nijk)−log⁡Γ(α/(qiri))}].\log p(\Data_i\given\mathrm{Pa}_i)= \sum_{j=1}^{q_i}\left[ \log\Gamma(\alpha/q_i)-\log\Gamma(\alpha/q_i+N_{ij}) +\sum_{k=1}^{r_i}\left\{\log\Gamma(\alpha/(q_i r_i)+N_{ijk}) -\log\Gamma(\alpha/(q_i r_i))\right\}\right].

The prior distributes α\alpha uniformly among cells; its decisions change as α\alpha 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 α\alpha with a number of real observations.

For example, a binary variable with no parents has one row and two prior cells of mass α/2\alpha/2. With a binary parent there are two rows and each cell receives α/4\alpha/4; the entire family still sums to α\alpha. 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.

InteractiveHill climbing on Asia
Step 0 of 7
ViajeFumarTBCáncerBronq.TB o CRayos XDisnea
Best candidates from this state (2 tied)
  • ▶ add Bronq. → Disnea · equivalent+741.3
  • add Disnea → Bronq. · equivalent+741.3
  • add TB o C → Cáncer+577.7
  • add Cáncer → TB o C+577.7
  • add Rayos X → TB o C+504.4
  • add TB o C → Rayos X+504.4
“Equivalent”: the resulting graph is in the same Markov class as the chosen graph, so its score matches exactly. The first in column order wins.
true structure−6677−8927search step (total structure score)
  • correct edge
  • orientation contrary to true class
  • extra edge
  • missing true edge
3000
Score
Column order (breaks ties)
Dataset seed1
Step0 of 7
Last moveempty structure
Score improvement0
Structure score−8927.4
True structure score−6681.0
SHD to true class (CPDAG)8
Edges: correct / reversed / extra / missing0 / 0 / 0 / 8
Add, remove or reverse edges and compare the result with the true equivalence class.

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

−∑iH^(Xi)+∑(i,j)∈TI^(Xi;Xj).-\sum_i \widehat H(X_i)+\sum_{(i,j)\in T}\widehat I(X_i;X_j).

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.

InteractiveBuilding Chow-Liu
Pair 1 of 13
X1X1X2X2X3X3X4X4X5X5X6X6X7X7X8X8X9X9X10X10.22.23.05.01.14.02.00.00.01.22.07.14.04.03.02.01.00.01.23.07.01.02.47.06.00.00.11.05.14.01.00.01.02.00.00.02.01.04.02.00.01.02.25.00.00.14.03.47.01.01.03.00.00.17.02.02.06.02.02.03.00.01.01.00.01.00.00.25.00.00.04.01.00.00.00.00.00.00.01.04.00.01.01.11.02.00.17.01.01.00X1X2X3X4X5X6X7X8X9X10
  • tree edge in the true skeleton
  • tree edge not in the true skeleton
  • true edge missing from tree (at the end)
  • cell: mutual information (darker means more)
True world
Mutual information
50
Dataset seed1
Pair examinedX3 ↔ X6
Mutual information (nats)0.4675
Decisionaccepted
Accepted edges / tree edges1 / 9
Edges in the true skeleton1 of 1
Mutual-information sum of the current forest0.467
Mean log likelihood of current forest (nats/row)−6.404
Typical empirical MI bias without dependence, 1/2n1/2n0.0100
Kruskal accepts high mutual-information edges when they do not close a cycle.

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 dd connected nodes and no cycles contains d−1d-1 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.

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.

[ ]Structure engine from scratchBrowser
"""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

Simulate 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.

[ ]Search and Chow-Liu on AsiaBrowser
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.

[ ]Comparison with pgmpyLocal GPU
"""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-8
This cell needs the local lab (PyTorch with your GPU). Start it with npm 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 10−1210^{-12}. 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

ProofFrom Laplace to BIC
Prove: Derive the BIC penalty for a regular model with k parameters.
0
The log-likelihood Hessian is N times an information matrix with a positive-definite limit.

Step 1 of 3. How does the Hessian determinant scale?

ProofMaximum-likelihood tree
Prove: Justify the Chow-Liu algorithm.
0
For a tree directed from a root, fit the marginal and conditional tables by maximum likelihood.

Step 1 of 3. Which sum remains after fitting the tables?

Numeric
A normal prior has standard deviation 10 and the posterior has standard deviation 0.5. Calculate the natural logarithm of the ratio σ_post/σ_prior.
Numeric
Two binary variables have counts by rows X and columns Y: [[30,10],[10,30]]. With ESS α=1, calculate ln BF for the model X→Y versus independence, using BDeu.
Quiz
Which pair of three-node DAGs is Markov equivalent?
CodeBDeu from a count table
Implement bdeu_family(counts,alpha): counts has q rows of parent configurations and r columns of states; alpha is positive. Return the family's log BDeu score.
import numpy as np
from scipy.special import gammaln
def bdeu_family(counts,alpha):
  return None
Shift+Enter to run
Key idea
Evidence integrates parameters under specific priors; BIC approximates it under regularity, and structure learning must respect equivalence, cycles and uncertainty.

References