2023-10-02 00:24:05 +00:00
|
|
|
from itertools import product
|
2023-10-01 23:09:50 +00:00
|
|
|
|
|
|
|
|
2023-10-02 00:24:05 +00:00
|
|
|
def calc_posterior(p_c1: float, D: int, p_ij: dict[tuple[int, int], float]):
|
|
|
|
priors = {
|
|
|
|
1: p_c1,
|
|
|
|
2: 1 - p_c1,
|
|
|
|
}
|
2023-10-01 23:09:50 +00:00
|
|
|
|
2023-10-02 00:24:05 +00:00
|
|
|
def p_x_given_Ci(xs: list[int], i: int):
|
|
|
|
s = 0
|
|
|
|
for j in range(len(xs)):
|
|
|
|
s += pow(p_ij[i, j], 1.0 - xs[j]) * pow(1.0 - p_ij[i, j], xs[j])
|
|
|
|
return s
|
2023-10-01 23:09:50 +00:00
|
|
|
|
2023-10-02 00:24:05 +00:00
|
|
|
# print("===")
|
|
|
|
# for i in priors.keys():
|
|
|
|
# for xs in product([0, 1], repeat=2):
|
|
|
|
# xs = list(xs)
|
|
|
|
# print("xs", xs)
|
|
|
|
# print(i, xs, p_x_given_Ci(xs, i))
|
|
|
|
# print("===")
|
2023-10-01 23:09:50 +00:00
|
|
|
|
2023-10-02 00:24:05 +00:00
|
|
|
posteriors = {}
|
|
|
|
for i in [1, 2]:
|
|
|
|
for xs in product([0, 1], repeat=D):
|
|
|
|
numer = p_x_given_Ci(xs, i) * priors[i]
|
2023-10-01 23:09:50 +00:00
|
|
|
|
2023-10-02 00:24:05 +00:00
|
|
|
def each_denom(k): return p_x_given_Ci(xs, k) * priors[k]
|
|
|
|
denom = sum(map(each_denom, priors.keys()))
|
|
|
|
posteriors[*xs, i] = numer / denom
|
|
|
|
|
|
|
|
print("Priors:", priors)
|
|
|
|
for xs in product([0, 1], repeat=D):
|
|
|
|
print(f"{xs = }")
|
|
|
|
for i in [1, 2]:
|
|
|
|
prob = posteriors[*xs, i]
|
|
|
|
print(f" * C{i}: {prob:0.3f}")
|
|
|
|
print()
|
|
|
|
|
|
|
|
|
|
|
|
def prob_3c():
|
|
|
|
D = 2
|
|
|
|
p_ij = {}
|
|
|
|
p_ij[1, 0] = 0.6
|
|
|
|
p_ij[1, 1] = 0.1
|
|
|
|
p_ij[2, 0] = 0.6
|
|
|
|
p_ij[2, 1] = 0.9
|
|
|
|
|
|
|
|
calc_posterior(0.2, D, p_ij)
|
|
|
|
calc_posterior(0.8, D, p_ij)
|
|
|
|
|
|
|
|
|
|
|
|
# prob_2a()
|
|
|
|
prob_3c()
|