Iti0210w9tut

Allikas: Lambda
import csv
from collections import defaultdict

counts = defaultdict(int)
with open("somerville.txt") as f:
    rd = csv.reader(f, delimiter=",")
    print(next(rd))
    for r in rd:
        counts[tuple(r)] += 1

# ['happiness', 'house_price', 'school_quality', 'road_quality']

N = sum(counts.values())
jpd = {}
for happiness in ["happy" , "unhappy"]:
    for house_price in ["low", "ok", "high"]:
        for school_quality in ["low", "ok", "high"]:
            for road_quality in ["low", "ok", "high"]:
                p = counts[(happiness,house_price,school_quality,road_quality)]/N
                jpd[(happiness,house_price,school_quality,road_quality)] = p

# e: road_quality = low
# q: happiness = happy
# hidden variables h: [house_price, school_quality]

P_e = 0
for happiness in ["happy" , "unhappy"]:
    for house_price in ["low", "ok", "high"]:
        for school_quality in ["low", "ok", "high"]:
            P_e += jpd[(happiness,house_price,school_quality,"low")]

P_qe = 0
for house_price in ["low", "ok", "high"]:
    for school_quality in ["low", "ok", "high"]:
        P_qe += jpd[("happy",house_price,school_quality,"low")]

# P(happy|road_quality=low)
P = P_qe / P_e