"""Use exact event counts and reproducible random experiments."""
from fractions import Fraction as F
from itertools import product
import json
from math import log
import platform
import numpy as np
def conditional(event,given):
if not given:
raise ValueError("conditioning event has zero mass")
return F(len(event & given),len(given))
def main():
cases = []
def check(name,inputs,expected,actual,operation):
assert expected == actual,(name,expected,actual)
cases.append(dict(name=name,input=inputs,operation=operation,expected=expected,actual=actual,passed=True))
faces = set(range(1,7))
even = {2,4,6}
high = {4,5,6}
low = faces-high
check("conditional_die", {"event":sorted(even),"given":sorted(high)}, "2/3",
str(conditional(even,high)), "restrict the fair die sample space")
try:
conditional(even,set())
except ValueError:
zero_raised = True
else:
zero_raised = False
check("conditioning_zero", [], True, zero_raised, "observe error at a zero-mass event")
terms = [conditional(even,group)*F(len(group),len(faces)) for group in (low,high)]
check("law_of_total_probability", [sorted(low),sorted(high)], ["1/6","1/3","1/2"],
list(map(str,[*terms,sum(terms)])), "sum weighted probabilities for a partition")
seed = 6127
generator = np.random.default_rng(seed)
sizes = [10,100,1000,10000]
tosses = generator.integers(0,2,size=sizes[-1])
counts = [int(tosses[:n].sum()) for n in sizes]
error = [abs(n_good/n-.5) for n_good,n in zip(counts,sizes,strict=True)]
assert all(0<=n_good<=n for n_good,n in zip(counts,sizes,strict=True))
check("seeded_coin_prefixes", {"seed":seed,"sizes":sizes,"counts":counts,"absolute_error":error},
[True,True], [abs(counts[-1]/10000-.5)<.025,error[-1]<error[0]],
"compare a reproducible run at four sample sizes with the fair probability")
cases[-1]["observed_counts"]=counts
exact_stay = sum(car==first for car,first in product(range(3),repeat=2))
check("monty_exact", {"equally_likely_pairs":9}, [3,6], [exact_stay,9-exact_stay],
"door-switch wins exactly when the initial choice misses under the standard host rule")
trials = 10000
all_doors = {0,1,2}
staying = switching = 0
for car,first in generator.integers(0,3,size=(trials,2)):
shown = int(generator.choice(sorted(all_doors-{car,first})))
replacement, = all_doors-{first,shown}
staying += first==car
switching += replacement==car
observed = [int(staying),int(switching)]
check("monty_seeded_matches_exact", {"seed":seed,"trials":trials}, [True,True,True],
[sum(observed)==trials,abs(observed[0]/trials-1/3)<.025,abs(observed[1]/trials-2/3)<.025],
"simulate a host that always opens an unchosen goat door and offers a switch")
cases[-1]["observed_counts"]=observed
logits = np.log([.8,.15,.05])
weights = np.exp(logits-logits.max())
probabilities = weights/weights.sum()
frequency = (np.array([0]*6+[1]*4)==0).mean()
check("normalized_scores_can_be_miscalibrated", {"logits":logits.tolist(),"correct":6,"total":10},
[.8,.15,.05,1.,.6], [*np.round(probabilities,12).tolist(),round(float(probabilities.sum()),12),float(frequency)],
"normalize scores and compare a toy group with a different observed frequency")
action = generator.choice(2,size=10000,p=[.7,.3])
check("categorical_policy_sampling", {"policy":[.7,.3],"draws":10000}, True,
abs(float(action.mean())-.3)<.025, "draw actions from an explicit categorical policy")
cases[-1]["observed_action_one_count"]=int(action.sum())
noise = generator.standard_normal((10000,2))
check("sample_latent_prior", {"distribution":"N(0,I)","size":[10000,2]}, [True,True],
[(np.abs(noise.mean(axis=0))<.035).all().item(),(np.abs(noise.var(axis=0)-1)<.05).all().item()],
"draw two independent latent coordinates and observe their moments")
print(json.dumps(dict(version=platform.python_version(),library_versions={"numpy":np.__version__},cases=cases)))
if __name__ == "__main__":
main()
本例需在 Windows、Python 3.12.14。numpy 2.5.4。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。numpy 2.5.4。
入口文件:projects/ai-math-probability-basics-lab/probability-lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
probability-lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。numpy 2.5.4。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a78.zip