concept

Bayesian network intuition

A DAG with local conditional distributions factors the joint distribution. In a common-parent fork, the children are conditionally independent given the parent under the network model. Enumerate worlds, sum over unobserved variables, normalize by evidence probability, and report undefined for zero-probability evidence. The Python function is a teaching interface, not a built-in.

Formal Syntax & Structure

artificial-intelligence syntaxartificial-intelligence
P(r,w,v) = P(r) × P(w|r) × P(v|r); probability(rows, query, evidence) → Fraction or None

Working Example

Example Snippetartificial-intelligence
from fractions import Fractionfrom itertools import product
def weather_joint(prior, wet, poor):    # All inputs are probabilities for True, indexed by rain status.    rows = {}    for rain, surface, visibility in product((False, True), repeat=3):        r = prior if rain else 1 - prior        w = wet[rain] if surface else 1 - wet[rain]        v = poor[rain] if visibility else 1 - poor[rain]        rows[rain, surface, visibility] = r * w * v    return rows
def probability(rows, query, evidence):    # query and evidence map tuple positions to Boolean values.    def matches(world, conditions):        return all(world[i] == value for i, value in conditions.items())    denominator = sum(p for world, p in rows.items()                      if matches(world, evidence))    if denominator == 0:        return None    numerator = sum(p for world, p in rows.items()                    if matches(world, evidence) and matches(world, query))    return numerator / denominator
rows = weather_joint(Fraction(1, 4),                     {False: Fraction(1, 5), True: Fraction(4, 5)},                     {False: Fraction(1, 10), True: Fraction(3, 5)})print(probability(rows, {0: True}, {1: True}))print(probability(rows, {0: True}, {1: True, 2: True}))print(probability(rows, {0: False}, {0: True}))