Reasoning under uncertainty in symbolic systems: from certainty factors to probabilistic logic
Real-world rules have exceptions and evidence is noisy. Study why MYCIN certainty factors failed, the contributions and failures of Dempster–Shafer, and how possible-world semantics joins logic and probability. The computational core covers model counting (#SAT), weighted model counting, knowledge compilation and probabilistic logic programming with ProbLog, directly reusing the module’s SAT machinery.
After this lesson you can
- Explain why certainty factors are incoherent with probability.
- Calculate belief, plausibility and Dempster combinations and recognize their failures.
- Reduce discrete probabilistic inference to weighted model counting.
- Implement a model counter with component decomposition and caching.
- Model uncertain knowledge with ProbLog and reason about its distribution semantics.
Before you start
- 10Conflict analysis and 1-UIP learningDefinite programs and least Herbrand modelProduction systemExpert system architectureBucket elimination and tree decomposition for CSPsAssignment trail and decision levels
- 01DPLL algorithmTseitin transformation
- 04Conditional probabilityBayes' theoremConditional independenceJoint law and marginals
- 08Class NP and verifiersClass #P and the permanent
The problem: rules with exceptions and noisy evidence
Production-system rules are logical truths: if premises hold, the conclusion is true. Expert knowledge brought to those systems rarely is. The expert-systems lesson showed a MYCIN rule:
IF the organism’s stain is gram-negative, morphology is bacillus, and it is anaerobic, THEN suggestive evidence (0.6) indicates it is Bacteroides.
The 0.6 says two things. First, the rule has exceptions: some anaerobic gram-negative bacilli are not Bacteroides, and listing all as negated premises is impossible (the qualification problem in nonmonotonic reasoning, which handles exceptions qualitatively without weights). Second, evidence is noisy: staining can fail, cultures become contaminated. A security operations analyst faces the same world: “IP on a reputation list” or “out-of-hours login” suggests account compromise, but does not prove it, and sources err.
We need a number per rule and a way to combine numbers when rules share a conclusion or chain. The lesson’s tension follows: rule systems want modularity, each rule contributing independently so rules can be added, removed and explained individually; probability is global, evidence value depending on everything else known. Three historic answers occupy the first half:
- MYCIN certainty factors, modular and, as Heckerman showed, probabilistically coherent only under independence assumptions rarely met.
- Dempster–Shafer theory, separating belief from plausibility and representing ignorance, but with a combination rule that misleads when sources conflict.
- Possible-worlds semantics, placing a probability distribution over models of a logical theory and joining both traditions.
The second half is computational. With possible worlds, query probability sums exponentially many models: weighted model counting, #SAT. You will see how to count with the module’s SAT machinery (DPLL, propagation, components and caching), how its trace is a compiled circuit answering thousands of queries, and how ProbLog packages this into logic programming where a rule with exceptions is written directly.
Certainty factors
MYCIN associates each rule and conclusion with a number in . Shortliffe and Buchanan (1975) defined it from two measures, belief and disbelief evidence adds to hypothesis :
The certainty factor is their difference. Since one is always zero, it can be written as one expression.
In practice experts gave rule numbers directly, not probabilities, and the system combined them using three fixed functions without returning to probabilities.
- Parallel combination. Rules and , factors and , merge into one rule with factor
- Sequential combination. If has factor and has , chain has .
- Compound premises. Conjunction takes the minimum premise factor, disjunction the maximum.
These functions have useful properties. Parallel combination is commutative and associative (evidence arrival order does not matter), has neutral element and absorbing elements (except undefined : one item proves and another refutes it), and . They are modular: a rule factor is used identically regardless of other knowledge (locality), and an obtained conclusion is used without inspecting provenance (detachment). Modularity was the point: each rule could be elicited and explained separately.
Why certainty factors are incoherent
David Heckerman analyzed the scheme in Probabilistic Interpretations for MYCIN’s Certainty Factors, presented at the first Uncertainty in Artificial Intelligence conference (1985) and published in proceedings edited by Kanal and Lemmer (1986). He found two things.
The original definition contradicts the combination functions. If is defined as above, parallel combination should follow from probability, but does not. Worse, as an update rule the original definition does not commute. Heckerman’s example starts with and two evidence items with factors and . Positive first: gives ; then negative gives . In reverse, negative gives and positive . Final belief depends on arrival order, exactly what combination functions forbid. The cause is asymmetry: positive evidence is measured against distance from to 1, negative against distance from to 0.
Combination functions do have a probabilistic reading, but a restrictive one. Heckerman treated desired factor properties (above) as axioms and sought probabilistic quantities satisfying them. All are monotone transformations of the likelihood ratio
where are odds and equality is Bayes’ theorem in odds form. One transformation reproduces MYCIN’s parallel combination exactly.
Proof
The inverse is if and if , with branches joining continuously at , . Check three cases of .
If : , so .
If : .
If , product is at least 1 exactly when , i.e. when and the minimum is . Then . If , the minimum is and . Both match the third branch of . Case swaps roles because both expressions are symmetric.
Finally Bayes’ theorem in odds form yields unconditionally, and conditional independence given and factorizes and likewise , giving .
∎Heckerman goes further: the appendix shows the modularity axiom (factor independent of previous evidence) forces that conditional independence in any probabilistic interpretation, and propagation through a rule network is coherent only if the network is a tree. MYCIN’s sequential combination admits no probabilistic interpretation: it implicitly assumes , i.e. absence of says nothing about . In his example “likes parties” () and “likes solo hikes” () inform “is extroverted”, which informs “does volunteer work” (). The probabilistic version needs one more number, the effect of not being extroverted on volunteering, fixed at . With only the second evidence MYCIN concludes change 0 in volunteering because maximum with 0 cuts the chain, while the probabilistic interpretation gives : lower extroversion probability does convey information.
import numpy as np
def combinar(x, y):
"""Combinación paralela de MYCIN (dos reglas con la misma conclusión)."""
if x >= 0 and y >= 0:
return x + y - x * y
if x < 0 and y < 0:
return x + y + x * y
return (x + y) / (1 - min(abs(x), abs(y)))
def cf_de_lambda(lam):
"""Interpretación de Heckerman que reproduce exactamente la regla de MYCIN."""
return (lam - 1) / lam if lam >= 1 else lam - 1
def lambda_de_cf(cf):
return 1 / (1 - cf) if cf >= 0 else 1 + cf
def posterior(prior, lam):
o = lam * prior / (1 - prior)
return o / (1 + o)
rng = np.random.default_rng(0)
trios = rng.uniform(-0.99, 0.99, size=(20000, 3))
e_prod = max(abs(lambda_de_cf(combinar(x, y)) / (lambda_de_cf(x) * lambda_de_cf(y)) - 1) for x, y, _ in trios)
e_asoc = max(abs(combinar(combinar(x, y), z) - combinar(x, combinar(y, z))) for x, y, z in trios)
print(f"máx error relativo de λ(x ⊕ y) = λ(x)·λ(y): {e_prod:.1e}")
print(f"máx |(x ⊕ y) ⊕ z − x ⊕ (y ⊕ z)|: {e_asoc:.1e}")
def actualizar_original(p, cf):
"""Definición de Shortliffe y Buchanan despejada: de (prior, CF) a la posterior."""
return p + cf * (1 - p) if cf >= 0 else p + cf * p
p1 = actualizar_original(actualizar_original(0.4, 0.7), -0.5)
p2 = actualizar_original(actualizar_original(0.4, -0.5), 0.7)
print(f"\ndefinición original, prior 0.4: +0.7 y luego −0.5 → {p1:.2f}; al revés → {p2:.2f}")
print(f"combinación de MYCIN de los mismos números: {combinar(0.7, -0.5):.2f} en cualquier orden")The first two lines’ errors are rounding ( and ): the theorem’s identity is exact and combination associative. Two updates of the original definition reproduce Heckerman’s versus .
Correlated evidence: double counting
The theorem says when MYCIN works. In practice it breaks on evidence not conditionally independent, most commonly because two rules ultimately read the same fact. Imagine detection rules “source IP is on reputation list A compromised account”, likewise lists B and C. If lists share sources, the IP appearing in B after A adds little. Yet each rule evaluated alone is correct: its factor matches its likelihood ratio. The problem is combining them.
The interactive’s model is explicit. means “compromised account” with prior . Each list alone flags an IP with and , so its rule has . List A decides independently; each other list copies A’s flag with probability or decides independently with the same rates. Thus each retains exactly the same marginal reliability for any , with only dependence changing. “Out-of-hours login” evidence, with , is independent of everything else.
With initial values (prior , three lists with and , plus out-of-hours login), MYCIN multiplies odds by and concludes ; real evidence justifies only , . In evidence-weight units , it counts information times. The next cell checks the interactive’s closed formula by summing the complete joint law, including latent copy variables, without time-of-day evidence:
import itertools
import matplotlib.pyplot as plt
def posterior_enumerando(prior, a, b, n, c):
"""P(H | las n listas marcan) sumando la ley conjunta: H, la marca de A y,
para cada otra lista, si copia a A y cuál sería su marca propia."""
num = den = 0.0
for h in (1, 0):
ph = prior if h else 1 - prior
q = a if h else b # P(marca propia | h)
for mA in (1, 0):
pA = q if mA else 1 - q
for resto in itertools.product((1, 0), repeat=2 * (n - 1)):
p, todas = ph * pA, mA == 1
for copia, propia in zip(resto[::2], resto[1::2]):
p *= (c if copia else 1 - c) * (q if propia else 1 - q)
todas &= (mA if copia else propia) == 1
if todas:
den += p
num += p * h
return num / den
def posterior_mycin(prior, a, b, n):
cf1 = cf_de_lambda(a / b)
cf = cf1
for _ in range(n - 1):
cf = combinar(cf, cf1)
return posterior(prior, lambda_de_cf(cf)), cf
prior, a, b = 0.05, 0.5, 0.125 # cada lista sola: λ = 4, CF = 0.75
print(f"{'n':>2} {'CF MYCIN':>9} {'P según CF':>11} {'P (c = 1)':>10} {'P (c = 0.5)':>12} {'P (c = 0)':>10}")
for n in range(1, 7):
pm, cfn = posterior_mycin(prior, a, b, n)
fila = [posterior_enumerando(prior, a, b, n, c) for c in (1.0, 0.5, 0.0)]
print(f"{n:>2} {cfn:>9.4f} {pm:>11.4f} {fila[0]:>10.4f} {fila[1]:>12.4f} {fila[2]:>10.4f}")
ns = range(1, 7)
plt.plot(ns, [posterior_mycin(prior, a, b, n)[0] for n in ns], "o-", label="CF de MYCIN")
for c, ls in ((1.0, "-"), (0.5, "--"), (0.0, ":")):
plt.plot(ns, [posterior_enumerando(prior, a, b, n, c) for n in ns], ls, marker="s", label=f"probabilidad, c = {c}")
plt.xlabel("listas que marcan la IP"); plt.ylabel("P(H | evidencia)"); plt.legend(); plt.show()With the correct posterior remains for any list count, that of one list, while MYCIN moves from to with six. With lists are truly independent evidence and columns agree. With , the realistic case, probability grows slowly (, , … to ) and MYCIN remains far above. Naive Bayes makes the same assumption: adding evidence weights is correct exactly under conditional independence. Heckerman notes Peirce proposed that evidence weight in 1878, Turing and Good rediscovered it, and INTERNIST-1’s score closely resembles it. Any risk score adding indicators makes the interactive’s error when two measure the same thing.
Dempster–Shafer theory
Certainty factors have a subtler flaw: one number cannot distinguish “I know nothing about ” from “balanced evidence for and against”. Nor can one probability: means both. Arthur Dempster (1967) and Glenn Shafer (A Mathematical Theory of Evidence, 1976) built a theory where evidence supports a set of hypotheses without distributing support among its elements.
is mass evidence assigns exactly to without knowing how to split it. Belief sums what implies ; plausibility what is compatible with . Always and : the gap is ignorance. Two extremes clarify. Vacuous mass yields and for every : I know nothing. A Bayesian mass with singleton focal elements gives : a probability.
Dempster’s reading explains the rest. A witness is reliable with probability and says “it was ”. If reliable the culprit is in ; otherwise testimony says nothing and the culprit is in . Mass is , : a probability over witness states transferred to by multivalued mapping with . Thus and are lower and upper probabilities: every distribution over compatible with the testimony satisfies .
Combination rule
Two independent sources, with mappings and , point to . If the intersection is empty, source states conflict: Dempster discards them and conditions on compatibility.
It is commutative and associative, vacuous mass is neutral, and if either mass is Bayesian the result is too: with Bayesian masses and , , Bayes’ rule with two likelihoods and uniform prior. General computation is expensive: Orponen (1990) proved evaluating Dempster’s rule #P-complete, a first sign counting is central.
from itertools import combinations
import numpy as np
def masa(**kw):
"""masa(a=0.5, ab=0.3, abc=0.2): cada clave es un subconjunto del marco escrito como cadena."""
return {frozenset(k): v for k, v in kw.items()}
def creencia(m, A):
return sum(v for B, v in m.items() if B <= A)
def plausibilidad(m, A):
return sum(v for B, v in m.items() if B & A)
def combinar_ds(m1, m2, regla="dempster", marco=None):
bruto, K = {}, 0.0
for B, x in m1.items():
for C, y in m2.items():
I = B & C
if I:
bruto[I] = bruto.get(I, 0.0) + x * y
else:
K += x * y
if regla == "dempster":
if K >= 1:
raise ValueError("conflicto total: la regla de Dempster no está definida")
return {A: v / (1 - K) for A, v in bruto.items()}, K
if regla == "yager": # el conflicto pasa a ser ignorancia
bruto[marco] = bruto.get(marco, 0.0) + K
return bruto, K
raise ValueError(regla)
def mostrar(m):
orden = sorted(m.items(), key=lambda t: (len(t[0]), sorted(t[0])))
return " ".join(f"{''.join(sorted(A))}: {v:.4f}" for A, v in orden)
m1 = masa(a=0.5, ab=0.3, abc=0.2)
m2 = masa(b=0.6, bc=0.2, abc=0.2)
m12, K = combinar_ds(m1, m2)
print("K =", round(K, 4), " m1 ⊕ m2 →", mostrar(m12))
for h in "abc":
A = frozenset(h)
print(f" {h}: Bel = {creencia(m12, A):.4f} Pl = {plausibilidad(m12, A):.4f}")
# el ejemplo de Zadeh: dos médicos casi opuestos
z1, z2 = masa(M=0.99, T=0.01), masa(C=0.99, T=0.01)
mz, Kz = combinar_ds(z1, z2)
print("\nZadeh, Dempster: K =", round(Kz, 4), " ", mostrar(mz))
my, _ = combinar_ds(z1, z2, "yager", frozenset("MCT"))
print("Zadeh, Yager: ", mostrar(my))
# masas bayesianas: Dempster es el producto normalizado; la masa vacía es el neutro
p, q = np.array([0.6, 0.3, 0.1]), np.array([0.2, 0.5, 0.3])
mb, _ = combinar_ds(masa(a=p[0], b=p[1], c=p[2]), masa(a=q[0], b=q[1], c=q[2]))
print("\nbayesianas:", mostrar(mb), " producto normalizado:", np.round(p * q / (p @ q), 4))
print("con la masa vacía:", mostrar(combinar_ds(m1, masa(abc=1.0))[0]))
# asociatividad en masas aleatorias sobre los 7 subconjuntos
subs = [frozenset(s) for r in (1, 2, 3) for s in combinations("abc", r)]
g = np.random.default_rng(1)
peor = 0.0
for _ in range(300):
x, y, z = (dict(zip(subs, g.dirichlet(np.ones(7)))) for _ in range(3))
izq = combinar_ds(combinar_ds(x, y)[0], z)[0]
der = combinar_ds(x, combinar_ds(y, z)[0])[0]
peor = max(peor, max(abs(izq.get(A, 0) - der.get(A, 0)) for A in subs))
print(f"máx diferencia (x⊕y)⊕z frente a x⊕(y⊕z) en 300 tríos: {peor:.1e}")In the first example, 40% of mass is conflict (one source’s clashes with the other’s and ), and the rest is rescaled by . Hypothesis gets and ; gets but : nothing supports it, but something is compatible.
Zadeh’s critique
Lotfi Zadeh, reviewing Shafer’s book (AI Magazine, 1984), proposed his namesake example. One physician believes meningitis with probability or tumor ; another contusion or tumor . Both consider tumor unlikely. Dempster’s rule gives conflict and after normalization : certainty in what neither believed. The cell shows it; the interactive shows why.
The rule’s interpretation explains it: Dempster conditions on “the two sources are compatible”, here probability . High conflict discards nearly all evidence, leaving a residue representing neither. Haenni (2005) argued the issue is modeling (experts so confident and opposed cannot both be reliable independent sources) rather than the rule; either way high calls for model review, not normalization. Alternatives change conflict’s destination: Yager (1987) assigns it to , acknowledging ignorance ( in the example), while Smets’ transferable belief model leaves it in as a signal the frame may be incomplete.
Vagueness is not uncertainty
Fuzzy logic (Zadeh, 1965), popularized around the same time, is often conflated with uncertainty. It addresses something else. “Juan is tall”, with Juan 1.78 m, is not uncertain: height is known exactly. The predicate “tall” is gradual, and fuzzy logic assigns membership degree . Probability measures uncertainty about a crisp fact, like “it will rain tomorrow”.
The difference is formal. Fuzzy logic is truth-functional: the degree of is a function of degrees of and (minimum in Zadeh’s proposal). Probability cannot be: and only bound between and (Fréchet bounds), with any intermediate value possible depending on dependence. With , is if , if independent and if ; fuzzy minimum says in all three, also for “ and not ”, impossible probabilistically. Fuzzy operators for uncertainty again ignore dependence.
Possible worlds: semantics joining logic and probability
The previous three proposals invent calculi. The alternative is to take propositional logic unchanged and put a probability distribution over its models.
Everything you know about logic and probability still holds: is a distribution over an -bit random vector, formulas are events. Valid formulas have probability 1, equivalent ones the same probability, and conditional probability is unchanged. Two consequences:
- Material implication is not a rule. is not . Since , holds: material implication is at least as probable, much more if is rare. A rule with exceptions “ usually implies ” uses the conditional, not the arrow.
- Knowing probabilities of some formulas bounds, not determines, another’s. This is Nilsson’s probabilistic logic (1986): constraints are linear in unknowns , and minimum and maximum come from two linear programs.
import itertools
from scipy.optimize import linprog
def cotas(n, restricciones, consulta):
"""Mín y máx de P(consulta) sobre todas las distribuciones en {0,1}^n que cumplen P(f) = p para cada (f, p)."""
mundos = list(itertools.product((1, 0), repeat=n))
fila = lambda f: [1.0 if f(*w) else 0.0 for w in mundos]
A = [fila(f) for f, _ in restricciones] + [[1.0] * len(mundos)]
b = [p for _, p in restricciones] + [1.0]
c = fila(consulta)
lo = linprog(c, A_eq=A, b_eq=b, bounds=(0, 1)).fun
hi = -linprog([-x for x in c], A_eq=A, b_eq=b, bounds=(0, 1)).fun
return f"[{lo + 0.0:.2f}, {hi + 0.0:.2f}]" # + 0.0 convierte un −0.0 en 0.0
# modus ponens probabilístico
print("P(A) = 0.7, P(A → B) = 0.8 ⟹ P(B) ∈", cotas(2, [(lambda A, B: A, 0.7), (lambda A, B: (not A) or B, 0.8)], lambda A, B: B))
# conocer P(B | A) = 0.8 en lugar de P(A → B) = 0.8
print("P(A) = 0.7, P(B | A) = 0.8 ⟹ P(B) ∈", cotas(2, [(lambda A, B: A, 0.7), (lambda A, B: A and B, 0.56)], lambda A, B: B))
# las cotas de Fréchet: dos marginales no fijan la conjunción
print("P(A) = P(B) = 0.5 ⟹ P(A ∧ B) ∈", cotas(2, [(lambda A, B: A, 0.5), (lambda A, B: B, 0.5)], lambda A, B: A and B))
print(" P(A ∧ ¬A) =", cotas(1, [(lambda A: A, 0.5)], lambda A: A and not A))With and , can range from to ; conditional (i.e. ) changes the interval to . Marginals and leave throughout , as Fréchet bounds said.
Independence as representation
An arbitrary distribution over needs numbers: over a billion for 30 atoms. No one can elicit or store them. The familiar Bayesian-network solution assumes conditional independences factorizing the distribution into small pieces. Independence is not just a property: it is how the distribution is written.
For rule systems one factorization is natural. Take mutually independent probabilistic facts with , and deterministic rules defining other atoms from them. Each fact choice fixes one world by the rules, and its probability is a product:
MYCIN’s rule with exceptions is then written without a rule number: with fact of probability saying “the rule applies in this case”. Exceptions are worlds where is false. Note is the fraction of premise-matching cases where the conclusion holds, a conditional probability to estimate; MYCIN’s is not, since certainty factors measure belief change. Something certainty factors could not do comes for free: observing the conclusion raises cause probabilities (effect-to-cause reasoning), and one cause explaining the conclusion weakens others (explaining away), because all conditions one distribution. Binary Bayesian networks can be written this way losslessly: each conditional probability table entry is a probabilistic fact. This is ProbLog’s idea, seen later.
Computation remains: sums terms, one per fact choice. We must count.
Counting models: #SAT
#SAT is the archetypal #P-complete problem: it is in #P because it counts witnesses of an NP problem, and complete because Cook–Levin reductions preserve witness counts. Counting is much harder than decision. Valiant (1979) proved counting models of a monotone two-literal-per-clause CNF is already #P-complete, although deciding 2-SAT is in P (and this formula is satisfied by setting all true). Toda’s theorem (1991) gives a #P oracle enough power for the entire polynomial hierarchy: .
Counting DPLL
The exact algorithm starts with familiar DPLL with three changes:
- Do not stop at the first model. Branch on and add: , where is simplified with true. If a branch empties all clauses with variables unassigned, it contributes models.
- Decompose into components. If and , share no variables, , because each model of is a pair of independent models. After a few decisions the residual formula often splits: CSP tree decomposition applied dynamically.
- Cache each solved component. The same residual formula appears through different search paths; caching counts it once.
Bacchus, Dalmao and Pitassi (2003) proved component-caching DPLL theoretically competitive with the best Bayesian inference methods, exponential in treewidth. In practice the key was combining caching with CDCL conflict-analysis clause learning, nontrivial because learned clauses cross components and grow without bound. Sang, Bacchus, Beame, Kautz and Pitassi (2004) solved this by analyzing components on the original formula without learned clauses. Their Cachet counter was often orders of magnitude faster than relsat, which decomposes but does not cache: on five random 75-variable 3-CNFs at ratio 1.0, their figure 2 times run 3809–31660 for relsat and 2–20 for Cachet, over three orders of magnitude, and Cachet recorded about twice as many cache hits as decisions.
Lab: a counter from scratch
The counter implements all three changes. It represents CNF as lists of literal sets (signed integers as in DIMACS), simplifies by copying (no watched literals, for readability), and accepts literal weights from the start: all weights 1 count models; next section explains others. The branching variable appears most frequently in the component, as in Cachet.
import itertools, random
from collections import defaultdict
def asignar(clausulas, lit):
"""Hace cierto lit: quita las cláusulas satisfechas y el literal opuesto. None si alguna se vacía."""
salida = []
for c in clausulas:
if lit in c:
continue
if -lit in c:
c = c - {-lit}
if not c:
return None
salida.append(c)
return salida
def propagar(clausulas):
"""Propagación unitaria: (cláusulas restantes, literales forzados), o (None, None) si hay conflicto."""
forzados = []
while True:
unidad = next((c for c in clausulas if len(c) == 1), None)
if unidad is None:
return clausulas, forzados
(lit,) = unidad
forzados.append(lit)
clausulas = asignar(clausulas, lit)
if clausulas is None:
return None, None
def componentes(clausulas):
"""Agrupa las cláusulas que comparten variables (union-find sobre las variables)."""
padre = {}
def raiz(v):
while padre.setdefault(v, v) != v:
padre[v] = padre[padre[v]]
v = padre[v]
return v
for c in clausulas:
vs = [abs(l) for l in c]
for v in vs[1:]:
padre[raiz(v)] = raiz(vs[0])
grupos = defaultdict(list)
for c in clausulas:
grupos[raiz(abs(next(iter(c))))].append(c)
return list(grupos.values())
class Contador:
"""WMC exacto: DPLL con propagación unitaria, componentes y caché de componentes.
w[l] es el peso del literal l (±v). Con todos los pesos a 1 cuenta modelos (#SAT)."""
def __init__(self, w, cache=True):
self.w, self.usar_cache = w, cache
self.cache, self.llamadas, self.aciertos = {}, 0, 0
def contar(self, clausulas, variables):
"""WMC de la conjunción de 'clausulas' sobre 'variables' (las que no aparecen quedan libres)."""
clausulas, forzados = propagar(clausulas)
if clausulas is None:
return 0.0
r = 1.0
for l in forzados:
r *= self.w[l]
usadas = {abs(l) for l in forzados}
for comp in componentes(clausulas):
vs = {abs(l) for c in comp for l in c}
usadas |= vs
r *= self.contar_componente(comp, vs)
if r == 0.0:
return 0.0
for v in variables - usadas: # libres: cualquier valor sirve
r *= self.w[v] + self.w[-v]
return r
def contar_componente(self, comp, vs):
self.llamadas += 1
clave = frozenset(comp)
if self.usar_cache and clave in self.cache:
self.aciertos += 1
return self.cache[clave]
frecuencia = defaultdict(int)
for c in comp:
for l in c:
frecuencia[abs(l)] += 1
x = max(frecuencia, key=lambda v: (frecuencia[v], -v)) # la variable que más aparece
total = 0.0
for lit in (x, -x):
sub = asignar(comp, lit)
if sub is not None:
total += self.w[lit] * self.contar(sub, vs - {x})
if self.usar_cache:
self.cache[clave] = total
return total
def wmc(clausulas, variables, w, cache=True):
c = Contador(w, cache)
return c.contar([frozenset(x) for x in clausulas], set(variables)), c
def wmc_enumerando(clausulas, variables, w):
variables, total = sorted(variables), 0.0
for signos in itertools.product((1, -1), repeat=len(variables)):
a = {v * s for v, s in zip(variables, signos)}
if all(any(l in a for l in c) for c in clausulas):
p = 1.0
for l in a:
p *= w[l]
total += p
return total
azar = random.Random(0)
for _ in range(300):
n = azar.randint(1, 9)
cls = [{azar.choice((1, -1)) * azar.randint(1, n) for _ in range(azar.randint(1, 3))} for _ in range(azar.randint(0, 14))]
cls = [c for c in cls if not any(-l in c for l in c)]
w = {s * v: azar.random() for v in range(1, n + 1) for s in (1, -1)}
a, _ = wmc(cls, range(1, n + 1), w)
assert abs(a - wmc_enumerando(cls, range(1, n + 1), w)) <= 1e-9 * max(1, a)
uno = {s * v: 1.0 for v in range(1, 4) for s in (1, -1)}
print("300 FNC aleatorias con pesos aleatorios: el contador coincide con la enumeración")
print("#SAT de (x1 ∨ x2) ∧ (¬x2 ∨ x3):", wmc([[1, 2], [-2, 3]], {1, 2, 3}, uno)[0])Enumeration checks use arbitrary weights, not just ones, and CNFs with free variables, repeated clauses and unsatisfiable formulas. The final example gives 4: of 8 assignments, violates the first clause (2 assignments according to ) and violates the second (another 2).
Weighted model counting
With this is #SAT. With and per variable, each assignment weighs its independent-variable probability, and . The counter already calculates it: multiply the decided literal’s weight in branches, forced literal weights in propagation, and for each free variable instead of 2.
Probabilistic inference as WMC
Return to possible-world factorization: independent probabilistic facts and deterministic rules. For an acyclic definite program with rules , Clark completion writes each derived atom as equivalent to the disjunction of its rule bodies (with false if no rules). Let be that formula converted to CNF by Tseitin transformation (one auxiliary variable per multi-atom body). Weights are and per fact, and for derived and auxiliary atoms.
The idea: adds no uncertainty. In an acyclic program each fact choice has one unique extending model of , and derived atoms, weight 1 on either literal, do not change the product. You prove this step by step in the guided exercise. With normalized fact weights , but the denominator matters with evidence or unnormalized weights, as in Markov logic networks.
Chavira and Darwiche (2008) studied encodings with an indicator variable per value of each variable and a parameter variable per table entry. Their advantage over variable elimination is local structure: parameter 0 or 1 becomes a clause unit propagation exploits (determinism), and equal parameters within a table let the counter decompose where graph structure does not (context-specific independence). Variable elimination and weighted counting are sides of the same calculation; the latter also sees numbers.
Lab: risk in an attack network
A typical defensive analysis models how compromise of one machine can propagate to others. Each possible entry (exposed web server, VPN, a workstation compromised by phishing) and each step between machines (unpatched vulnerability, reused credentials) is a fact with the probability that condition exists. Two rules: a machine is compromised if it is an active entry, or another compromised machine has a step to it. With this example’s probabilities (illustrative, not measured), ask the database’s risk and, if backup falls, the likely entry.
class Programa:
"""Programa definido acíclico y ya instanciado, con hechos probabilísticos p::f."""
def __init__(self):
self.ids, self.nombres, self.w = {}, [], {}
self.hechos, self.reglas = {}, defaultdict(list)
def var(self, atomo):
if atomo not in self.ids:
self.nombres.append(atomo)
v = self.ids[atomo] = len(self.nombres)
self.w[v] = self.w[-v] = 1.0 # derivados y auxiliares: peso 1 a los dos literales
return self.ids[atomo]
def hecho(self, p, atomo):
v = self.var(atomo)
self.hechos[atomo] = p
self.w[v], self.w[-v] = p, 1 - p
def regla(self, cabeza, *cuerpo):
self.var(cabeza)
for a in cuerpo:
self.var(a)
self.reglas[cabeza].append(cuerpo)
def cnf(self):
"""Compleción de Clark, con una variable de Tseitin por cada cuerpo de más de un átomo."""
cls = []
for h in [a for a in self.nombres if a not in self.hechos and a[0] != "aux"]:
hv, cuerpos = self.ids[h], []
for k, cuerpo in enumerate(self.reglas.get(h, [])):
if len(cuerpo) == 1:
cuerpos.append(self.ids[cuerpo[0]])
continue
b, lits = self.var(("aux", h, k)), [self.ids[a] for a in cuerpo]
cls += [[-b, l] for l in lits] + [[b] + [-l for l in lits]] # b ↔ ∧ cuerpo
cuerpos.append(b)
cls.append([-hv] + cuerpos) # h → ∨ cuerpos (sin reglas: h falso)
cls += [[hv, -b] for b in cuerpos] # cada cuerpo → h
return cls
def modelo_minimo(self, ciertos):
M, cambio = set(ciertos), True
while cambio:
cambio = False
for h, cuerpos in self.reglas.items():
if h not in M and any(all(a in M for a in c) for c in cuerpos):
M.add(h)
cambio = True
return M
def red_de_ataque():
P = Programa()
for p, x in ((0.30, "web"), (0.10, "vpn"), (0.25, "ws")):
P.hecho(p, ("entrada", x))
P.regla(("comp", x), ("entrada", x))
for p, x, y in ((0.6, "web", "app"), (0.8, "vpn", "app"), (0.3, "ws", "app"), (0.4, "ws", "ad"),
(0.5, "app", "db"), (0.7, "ad", "db"), (0.5, "ad", "backup"), (0.2, "db", "backup")):
P.hecho(p, ("paso", x, y))
P.regla(("comp", y), ("comp", x), ("paso", x, y))
return P
P = red_de_ataque()
delta = P.cnf()
V = set(range(1, len(P.nombres) + 1))
print(f"{len(P.hechos)} hechos, {len(V)} variables, {len(delta)} cláusulas; WMC(Δ) = {wmc(delta, V, P.w)[0]:.6f}")
def prob(consulta, evidencia=()):
"""P(consulta | evidencia) = WMC(Δ ∧ q ∧ e) / WMC(Δ ∧ e); evidencia: pares (átomo, valor)."""
e = [[P.ids[a] if v else -P.ids[a]] for a, v in evidencia]
return wmc(delta + [[P.ids[consulta]]] + e, V, P.w)[0] / wmc(delta + e, V, P.w)[0]
def prob_enumerando(consulta, evidencia=()):
"""La semántica, sin atajos: suma sobre las 2^m elecciones de hechos con su modelo mínimo."""
hechos, num, den = list(P.hechos), 0.0, 0.0
for bits in itertools.product((1, 0), repeat=len(hechos)):
p = 1.0
for f, b in zip(hechos, bits):
p *= P.hechos[f] if b else 1 - P.hechos[f]
M = P.modelo_minimo([f for f, b in zip(hechos, bits) if b])
if all((a in M) == v for a, v in evidencia):
den += p
num += p * (consulta in M)
return num / den
for x in ("app", "ad", "db", "backup"):
print(f"P(comp({x})) = {prob(('comp', x)):.6f} enumerando 2^11 mundos: {prob_enumerando(('comp', x)):.6f}")
ev = [(("comp", "backup"), True)]
print("\nsabiendo que cayó la copia de seguridad:")
for x in ("web", "vpn", "ws"):
a = ("entrada", x)
print(f" P(entrada({x}) | comp(backup)) = {prob(a, ev):.4f} (prior {P.hechos[a]:.2f}) enumerando: {prob_enumerando(a, ev):.4f}")The eleven probabilities give variables (11 facts, 7 derived atoms, 8 auxiliaries) and 42 clauses, and as the theorem predicts. Database compromise probability is , backup , and counting matches enumeration of worlds to six figures. Diagnosis is interesting: if backup fell, workstation-entry probability rises from to , web from to and VPN from to . Workstation dominates because it alone has a path to Active Directory (ad), from which backup falls directly with probability ; other entries only reach it through the database with an step. No program rule reasons effect-to-cause: conditioning does.
Why caching matters
To see caching’s effect we need many variables. The layered network below has two machines per layer, both layer-0 machines already compromised, and four possible steps between each pair of layers, each with probability . With layers there are facts and worlds.
import matplotlib.pyplot as plt
def escalera(L, p=0.5):
"""Red por capas: dos máquinas por capa, la capa 0 comprometida, cuatro pasos posibles entre capas."""
E = Programa()
for a in (0, 1):
E.hecho(1.0, ("entrada", (0, a)))
E.regla(("comp", (0, a)), ("entrada", (0, a)))
for i in range(L):
for a in (0, 1):
for b in (0, 1):
E.hecho(p, ("paso", (i, a), (i + 1, b)))
E.regla(("comp", (i + 1, b)), ("comp", (i, a)), ("paso", (i, a), (i + 1, b)))
return E
print(f"{'L':>3} {'hechos':>6} {'P(comp(L,0))':>13} {'llamadas con caché':>19} {'sin caché':>10}")
filas = []
for L in (2, 4, 6, 8, 12, 16, 20):
E = escalera(L)
cls, VE, q = E.cnf(), set(range(1, len(E.nombres) + 1)), [[E.ids[("comp", (L, 0))]]]
val, c1 = wmc(cls + q, VE, E.w)
sin = wmc(cls + q, VE, E.w, cache=False)[1].llamadas if L <= 8 else None
filas.append((L, c1.llamadas, sin))
print(f"{L:>3} {4 * L:>6} {val:>13.6f} {c1.llamadas:>19} {sin if sin else '':>10}")
Ls = [f[0] for f in filas]
plt.semilogy(Ls, [f[1] for f in filas], "o-", label="con caché")
plt.semilogy([f[0] for f in filas if f[2]], [f[2] for f in filas if f[2]], "s--", label="sin caché")
plt.semilogy(Ls, [2.0 ** (4 * L) for L in Ls], ":", color="gray", label="mundos: 2^(4L)")
plt.xlabel("capas L"); plt.ylabel("llamadas a contar_componente"); plt.legend(); plt.show()With caching, calls grow linearly: from exactly (81, 161, 241, …, 721), 40 per layer. Without caching they quadruple roughly every two layers (23, 105, 433, 1745). With there are facts and worlds, and the counter answers in 721 calls. Structure explains it: once steps entering layer are decided, all prior history reduces to which of its two machines are compromised, so the residual formula has few forms and caching recognizes them. This exploits the ladder’s small treewidth without computing a decomposition.
Knowledge compilation
Each call to prob repeats the entire search. For many queries on one base (all machines, varying evidence and probabilities), save the search. Component-DPLL’s trace is a circuit: each decision on is an OR of two branches, , and each decomposition an AND of components. Caching makes it a directed acyclic graph, not a tree, because a reused component has multiple parents.
Proof
Induct from leaves. At a leaf, definition. At an AND with children over disjoint variables, a model of over is exactly a tuple of models of each over (decomposability), with weight the product of part weights; summing over tuples, sum of products is product of sums. At OR, child model sets are disjoint (determinism), so provided each is counted over the same variables as , guaranteed by smoothness. If a child omitted , its models over would be its own with free, multiplying weight by .
∎Each property protects one proof step, failing concretely without it: without decomposability multiplication treats shared-variable parts as independent; without determinism addition counts common models repeatedly; without smoothness missing-variable factors are lost. Smoothness is cheapest: Darwiche and Marquis (2002) show any d-DNNF can be smoothed in polynomial time by adding where is absent. With probability weights , missing factors are 1 and smoothness unnecessary except when evidence sets a weight to 0.
In the proof DNF for the bridge formula, the root is , a “probability” above 1, because three ways from to overlap heavily. This is the certainty-factor error, counting nonindependent information twice, now in calculation structure rather than numbers.
Compilation map
Darwiche and Marquis (2002) arranged languages by polynomial-time queries and transformations and succinctness (potential translation growth). From more to less succinct: DNNF, d-DNNF, FBDD, OBDD, fixed-order OBDD, explicit model list. Most relevant here:
| Language | Counting (and WMC) | Conditioning | Conjunction of two circuits | Equivalence |
|---|---|---|---|---|
| DNNF | no (unless P = NP) | yes | no | no |
| d-DNNF | yes | yes | no | unknown |
| Fixed-order OBDD | yes | yes | yes, bounded (apply) | yes |
d-DNNF answers consistency, validity, clause entailment, counting and model enumeration in polynomial time, but no target language is closed under conjunction of arbitrary circuits. OBDDs do combine circuits (Bryant’s apply) at a substantial succinctness cost. SDDs (sentential decision diagrams, Darwiche 2011) are intermediate: a d-DNNF subset generalizing OBDDs (an OBDD is an SDD with a linear variable tree), canonical for a given variable tree and with polynomial-time apply. ProbLog2 defaults to them when PySDD is installed: build bottom-up, conjunction by conjunction.
Top-down d-DNNF compilers are trace-saving counters: c2d (Darwiche, 2004), Dsharp (Muise et al., 2012) and d4 (Lagniez and Marquis, 2017) produce decision-DNNF, whose ORs are variable decisions (deterministic by construction) and ANDs are components (decomposable by construction). Your counter is too with small changes: construct corresponding AND/OR nodes instead of multiplying and adding numbers.
class Compilador(Contador):
"""El mismo DPLL, pero devuelve nodos de un circuito d-DNNF suave en lugar de números."""
def __init__(self):
super().__init__(w=None)
self.nodos, self.unicos = [], {}
def nodo(self, *n): # ('lit', l) | ('and', hijos) | ('or', hijos) | ('const', 0 o 1)
if n not in self.unicos:
self.unicos[n] = len(self.nodos)
self.nodos.append(n)
return self.unicos[n]
def contar(self, clausulas, variables):
clausulas, forzados = propagar(clausulas)
if clausulas is None:
return self.nodo("const", 0)
hijos = [self.nodo("lit", l) for l in forzados]
usadas = {abs(l) for l in forzados}
for comp in componentes(clausulas):
vs = {abs(l) for c in comp for l in c}
usadas |= vs
hijos.append(self.contar_componente(comp, vs))
for v in sorted(variables - usadas): # suavidad: v ∨ ¬v por cada variable libre
hijos.append(self.nodo("or", (self.nodo("lit", v), self.nodo("lit", -v))))
return hijos[0] if len(hijos) == 1 else self.nodo("and", tuple(hijos))
def contar_componente(self, comp, vs):
clave = frozenset(comp)
if clave in self.cache:
return self.cache[clave]
frecuencia = defaultdict(int)
for c in comp:
for l in c:
frecuencia[abs(l)] += 1
x = max(frecuencia, key=lambda v: (frecuencia[v], -v))
ramas = []
for lit in (x, -x):
sub = asignar(comp, lit)
if sub is not None:
ramas.append(self.nodo("and", (self.nodo("lit", lit), self.contar(sub, vs - {x}))))
r = ramas[0] if len(ramas) == 1 else self.nodo("or", tuple(ramas))
self.cache[clave] = r
return r
def evaluar(nodos, raiz, w):
"""WMC de un d-DNNF suave: hojas con su peso, AND multiplica, OR suma (los hijos tienen índice menor)."""
val = [0.0] * (raiz + 1)
for i, n in enumerate(nodos[: raiz + 1]):
if n[0] == "lit":
val[i] = w[n[1]]
elif n[0] == "const":
val[i] = float(n[1])
elif n[0] == "and":
v = 1.0
for h in n[1]:
v *= val[h]
val[i] = v
else:
val[i] = sum(val[h] for h in n[1])
return val[raiz]
compilador = Compilador()
raiz = compilador.contar([frozenset(c) for c in delta], V)
print(f"Δ compilada a d-DNNF suave: {raiz + 1} nodos")
def p_circuito(q, w):
wq = dict(w)
wq[-P.ids[q]] = 0.0 # condicionar a q es anular el peso de ¬q
return evaluar(compilador.nodos, raiz, wq) / evaluar(compilador.nodos, raiz, w)
nombre = lambda f: f"{f[0]}({', '.join(f[1:])})"
base = p_circuito(("comp", "db"), P.w)
print(f"P(comp(db)) evaluando el circuito: {base:.6f}")
print("\nreducción de P(comp(db)) al eliminar cada condición (p → 0):")
efectos = []
for f in P.hechos:
w = dict(P.w)
w[P.ids[f]], w[-P.ids[f]] = 0.0, 1.0
efectos.append((base - p_circuito(("comp", "db"), w), f))
for d, f in sorted(efectos, reverse=True)[:5]:
print(f" {nombre(f):16s} {d:.4f}")The circuit has 200 nodes and is compiled once; each later query is a linear pass, with query and evidence as zeroed weights (derived atoms are circuit variables too). This makes a mitigation question trivial: which condition should be removed first? Since is multilinear in fact probabilities, , and moving to 0 reduces risk by exactly . The application-to-database step is most profitable to close ( of ), followed by phishing entry (); web-to-application and web entry tie at because web threatens the database only through that step.
Probabilistic logic programming
Everything above can be written by hand: facts, rules, completion, counter. ProbLog turns it into a language.
This is possible-world semantics factorized by independent facts, with the least model acting as deterministic rules. An important difference from completion: the least model is defined for cyclic programs too, like reachability, making distribution semantics more than a Bayesian network with different syntax. The interactive program has four facts, hence 16 worlds.
With initial values ; adding probabilities of the two proofs, , overestimates because worlds with both paths are counted twice. This is the disjoint-sum problem: original ProbLog (De Raedt, Kimmig and Toivonen, 2007) gathered proofs into DNF and compiled it to a BDD precisely to make them disjoint.
How ProbLog infers
Fierens, Van den Broeck et al. (2015) describe ProbLog2’s pipeline, reusing this lesson:
- Ground only relevant parts. SLD resolution and tabling from queries and evidence collect ground rules influencing them. In their experiments, removing 17% of ground-program rules reduced formula clauses by up to 90%, as each removed rule may break formula-expanding cycles.
- Convert to a formula. For acyclic rules, Clark completion. With positive cycles (like
comp(Y) :- comp(X), paso(X, Y)in a cyclic graph), completion is incorrect: it admits models in which atoms mutually support one another without external cause. ProbLog uses cycle-breaking conversion, rule-based (Janhunen, 2004) or proof-based (Mantadelis and Janssens, 2010). - Compile and count. Compile the weighted formula to d-DNNF or SDD and evaluate with WMC. On WebKB, BDDs were manageable only for domains of size 3 or 4, while d-DNNFs reached 18.
Unlike PRISM, which requires acyclic programs and mutually exclusive bodies for rules sharing a head, ProbLog admits cycles and overlapping bodies and must truly count. The translation also gives the most probable explanation (MPE) as weighted MaxSAT and supports learning fact probabilities from partial interpretations with EM (LFI-ProbLog, Gutmann et al., 2011): the E-step uses circuits to calculate each fact’s probability given each observation.
Lab: ProbLog in practice
The following cells need the local lab, with pip install problog pysdd. The first hidden cell repeats counter and attack-network definitions locally because that process does not share browser memory.
First, the same model in ProbLog. Notice its brevity: two variable rules rather than eight hand-written instances, query and evidence as language predicates. Then a positive cycle shows Clark completion failing.
from problog.program import PrologString
from problog import get_evaluatable
RED = """
0.30::entrada(web). 0.10::entrada(vpn). 0.25::entrada(ws).
0.6::paso(web, app). 0.8::paso(vpn, app). 0.3::paso(ws, app). 0.4::paso(ws, ad).
0.5::paso(app, db). 0.7::paso(ad, db). 0.5::paso(ad, backup). 0.2::paso(db, backup).
comp(X) :- entrada(X).
comp(Y) :- comp(X), paso(X, Y).
"""
def problog(programa, motor="sdd"):
"""Evalúa todas las consultas del programa (con su evidencia): {consulta: probabilidad}."""
res = get_evaluatable(motor).create_from(PrologString(programa)).evaluate()
return {str(k): v for k, v in res.items()}
r = problog(RED + "query(comp(app)). query(comp(db)). query(comp(backup)).")
for x in ("app", "db", "backup"):
print(f"comp({x}): ProbLog {r[f'comp({x})']:.6f} contador propio {prob(('comp', x)):.6f}")
r = problog(RED + "evidence(comp(backup), true). query(entrada(_)).")
print("\ncon evidence(comp(backup), true):", {k: round(v, 4) for k, v in sorted(r.items())})
# un ciclo positivo: desde la aplicación también se puede comprometer la web
CICLO = RED + "0.5::paso(app, web).\n"
print("\ncon el ciclo web → app → web, P(comp(web)) según ProbLog:", round(problog(CICLO + "query(comp(web)).")["comp(web)"], 6))
P = red_de_ataque()
P.hecho(0.5, ("paso", "app", "web"))
P.regla(("comp", "web"), ("comp", "app"), ("paso", "app", "web"))
delta = P.cnf()
V = set(range(1, len(P.nombres) + 1))
print(f"compleción de Clark: WMC(Δ) = {wmc(delta, V, P.w)[0]:.6f}, WMC(Δ ∧ comp(web)) / WMC(Δ) = {prob(('comp', 'web')):.6f}")
print(f"suma sobre los modelos mínimos: P(comp(web)) = {prob_enumerando(('comp', 'web')):.6f}")
P = red_de_ataque() # restablece la red acíclica
delta = P.cnf()
V = set(range(1, len(P.nombres) + 1))npm run lab and open the connection link.ProbLog and the custom counter agree to six figures on all three queries and diagnosis with evidence (, , ). With the cycle the difference is Fierens’ prediction: completion gives because worlds with both steps paso(web, app) and paso(app, web) where no entry reaches web or application admit two models (both compromised, mutually supporting, or neither), yielding false probability . Correct least-model probability is , as ProbLog returns.
Now learning. Simulate incidents with the true model and retain only what responders would observe: which machines ended compromised, not entry or steps. LFI-ProbLog estimates eleven probabilities from those partial interpretations.
from problog.logic import Term
from problog.learning import lfi
VERDAD = {("entrada", "web"): 0.30, ("entrada", "vpn"): 0.10, ("entrada", "ws"): 0.25,
("paso", "web", "app"): 0.6, ("paso", "vpn", "app"): 0.8, ("paso", "ws", "app"): 0.3,
("paso", "ws", "ad"): 0.4, ("paso", "app", "db"): 0.5, ("paso", "ad", "db"): 0.7,
("paso", "ad", "backup"): 0.5, ("paso", "db", "backup"): 0.2}
MAQUINAS = ["web", "vpn", "ws", "app", "ad", "db", "backup"]
def interpretacion(azar):
"""Un incidente simulado: se sortean los hechos y solo se observa qué máquinas acabaron comprometidas."""
ciertos = [f for f, p in VERDAD.items() if azar.random() < p]
M = P.modelo_minimo(ciertos)
return [(Term("comp", Term(m)), ("comp", m) in M) for m in MAQUINAS]
PLANTILLA = "\n".join(f"t(_)::{f[0]}({', '.join(f[1:])})." for f in VERDAD) + """
comp(X) :- entrada(X).
comp(Y) :- comp(X), paso(X, Y).
"""
azar = random.Random(0)
for n in (100, 1000):
datos = [interpretacion(azar) for _ in range(n)]
_, pesos, atomos, iters, _ = lfi.run_lfi(PrologString(PLANTILLA), datos, max_iter=500, min_improv=1e-6)
aprendido = {str(a).split("::")[1]: float(w) for a, w in zip(atomos, pesos)}
clave = lambda f: f"{f[0]}({','.join(f[1:])})"
err = [abs(aprendido[clave(f)] - p) for f, p in VERDAD.items()]
print(f"\n{n} incidentes, {iters} iteraciones de EM: error medio {sum(err) / len(err):.3f}, máximo {max(err):.3f}")
if n == 1000:
for f, p in VERDAD.items():
print(f" {clave(f):20s} real {p:.2f} aprendido {aprendido[clave(f)]:.3f}")npm run lab and open the connection link.With 100 incidents mean error is and maximum ; with 1000 they fall to and . Entries are learned well because comp(web), comp(vpn) and comp(ws) can only be true via their entry. Worst-estimated steps are rarely tested: paso(vpn, app) ( versus ) is observed only when VPN fell, 10% of 1000, and still confounded with two other paths to app. This limits learning from partial interpretations: a parameter is identified only as well as data exercise it.
Finally compare timing against the custom counter on the ladder, where results must agree:
print(f"{'L':>3} {'hechos':>6} {'contador propio (s)':>20} {'ProbLog con SDD (s)':>20} {'cociente':>9}")
for L in (4, 8, 16, 32):
E = escalera(L)
cls, VE = E.cnf(), set(range(1, len(E.nombres) + 1))
t = time.perf_counter()
a = wmc(cls + [[E.ids[("comp", (L, 0))]]], VE, E.w)[0]
t1 = time.perf_counter() - t
prog = "1.0::entrada(n0_0). 1.0::entrada(n0_1).\n" + "".join(
f"0.5::paso(n{i}_{x}, n{i + 1}_{y}).\n" for i in range(L) for x in (0, 1) for y in (0, 1))
prog += "comp(X) :- entrada(X).\ncomp(Y) :- comp(X), paso(X, Y).\n" + f"query(comp(n{L}_0)).\n"
t = time.perf_counter()
b = problog(prog)[f"comp(n{L}_0)"]
t2 = time.perf_counter() - t
assert abs(a - b) < 1e-9, (a, b)
print(f"{L:>3} {4 * L:>6} {t1:>20.3f} {t2:>20.3f} {t2 / t1:>9.2f}")npm run lab and open the connection link.Both give the same number in every row. Timing trends matter, not machine-dependent absolute values: with few layers the custom counter wins because ProbLog pays fixed grounding and compilation overhead; after about eight layers ProbLog is faster and the gap grows with . The custom counter grows approximately with : linearly many calls, but each copies the clause list without watched literals or incremental structures. This distinguishes a correct algorithm from production implementation.
A look at Markov logic networks
ProbLog defines distribution generatively: independent facts and rules deriving the rest, with probabilities summing to 1 by construction. Markov logic networks (Richardson and Domingos, 2006) take the undirected route: first-order formulas with real weights , and for each grounded world ,
where counts instances of true in and normalizes. Infinite weight is a hard constraint and first-order logic the limiting case. With one formula of weight and one person there are four worlds; it is true in three weighing and false in one weighing . Each formula multiplies odds of satisfying worlds by rather than prohibiting others.
Inference is also WMC: auxiliary variable per instance, with and , and weights 1 elsewhere. The denominator is no longer 1: , hence the earlier ratio theorem. The modeling difference is directed versus undirected: in ProbLog each number is a locally readable, learnable probability; in a Markov network weights only make sense together.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. How many models of extend a given total choice ?
wmc_circuito(nodos, raiz, w, variables), which calculates the weighted model count of a d-DNNF circuit (decomposable and deterministic) which need not be smooth. Nodes are tuples ('lit', l) with l a signed integer, ('const', 0) or ('const', 1), ('and', hijos) or ('or', hijos), where hijos is a tuple of indices smaller than the node's own. w gives each literal's weight (w[v] and w[-v]), and variables is the set of variables counted over: those the circuit does not mention, or that are missing from an OR child, must contribute their factor w[v] + w[-v].def wmc_circuito(nodos, raiz, w, variables):
"""WMC de un d-DNNF no necesariamente suave, sobre el conjunto 'variables'."""
# tu código: para cada nodo, su valor y sus variables; en los OR, completa a cada hijo
# con las variables que le faltan; en la raíz, con las de 'variables' que no aparezcan
return NoneMore than one answer may be correct.
entrada(web), for salto(web,app), for salto(web,db) and for salto(app,db), calculate the probability that the direct hop existed, . This is a forensic question: the database fell; did they enter by the direct path?Summary
- MYCIN certainty factors are modular and therefore incoherent: parallel combination is equivalent to multiplying likelihood ratios (Heckerman), which is correct only when evidence is conditionally independent given the hypothesis and its negation. Correlated evidence is counted repeatedly.
- Dempster-Shafer represents ignorance with masses on sets and bounds each hypothesis between belief and plausibility, but its rule conditions on source compatibility: with high conflict (Zadeh, ), the result represents neither source. Fuzzy logic models vagueness, not uncertainty, and cannot be probability because it is truth-functional.
- Possible-worlds semantics puts a distribution over models of a theory; with independent probabilistic facts and deterministic rules, exceptions are worlds and reasoning from effect to cause follows from conditioning.
- #SAT is #P-complete; DPLL with propagation, components and caching counts in practice, and with weights computes WMC: .
- The counter trace is a d-DNNF circuit; in a decomposable, deterministic and smooth circuit, WMC is evaluated in linear time, and compiling once supports many queries. Without determinism models are counted repeatedly, as when adding proofs.
- ProbLog defines probability through Sato’s distribution semantics and computes it by instantiating what is relevant, converting to a formula (taking care with positive cycles, where Clark completion fails), compiling and counting; it also learns probabilities from partial data using EM. Markov logic networks are its undirected counterpart, with .