概率入门
用事件、条件概率、全概率和可复现采样区分理论概率与频率。
学完这一章,你能够
- 用事件、条件概率、全概率和可复现采样区分理论概率与频率。
先写样本空间,再算事件
公平六面骰的样本空间是 {1,2,3,4,5,6}。偶数事件包含 2、4、6,因此概率是 1/2。概率介于 0 和 1。在有限的等可能空间中,空事件概率为 0,整个空间概率为 1;连续模型的某个单点也可能概率为 0。
若给定事件 B 有正概率,P(A|B)=P(A∩B)/P(B)。已知骰子点数至少为 4,只在 {4,5,6} 中计数,其中有两个偶数,条件概率为 2/3。分母为零时该比值无定义。
全概率公式把不同分组的条件概率乘以各组权重再相加。各组应互不相交并覆盖样本空间。以点数小于 4 和至少为 4 两组为例,偶数的两条概率路径是 1/6 与 1/3,合计 1/2。
用频率观察理论概率
在独立同分布的公平投掷中,样本频率随次数增加趋向 0.5。有限次实验仍可能偏离,逐次增加样本也可能使误差暂时变大。本站用固定生成器种子记录同一串投掷的四个前缀,并按样本数比较误差。
三门游戏中,奖品和初选各自等可能,主持人知道奖品位置,每轮打开另一扇空门并允许换门。初选命中时留门获胜,否则换门获胜。枚举九种奖品与初选组合,留门赢三种,换门赢六种。模拟使用同一批对局比较两种动作。
模型概率、校准和随机动作
Softmax 将同一组类别 logits 变为总和为 1 的概率。校准需要比较独立样本上的预测置信度与实际频率。例如十个都报 0.8 的预测只对了六个,这一小组的观测频率是 0.6。
生成场景常把采样和确定性变换组合。VAE 生成时可以从潜变量先验采样再解码,重构时可从编码器的近似后验抽样。GAN 通常先抽随机潜变量再映射,扩散模型通常从噪声开始进行多步反向更新,是否每一步再采随机量取决于采样器。
随机策略给各个动作分配概率,例如左 0.7、右 0.3。给不同动作正概率可增加探索机会,实际覆盖还与状态访问、策略概率和采样次数有关。
枚举主持人规则并复跑投掷实验
"""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()
- 三门游戏的理论留门与换门胜率分别是 1/3 和 2/3。固定种子的模拟接近理论值。
所需环境:Windows、Python 3.12.14。numpy 2.5.4。
当前源码 SHA256:5081c4a5033594bd3afcae1df6c4c417fc2d609a7bcc0613df5173da94587b6d
复跑实验
解压后按 README 运行自编程序。
所需环境:Windows、Python 3.12.14。numpy 2.5.4。
ZIP SHA256:7d53d0c72c64b29a340be75b725018b80dee99a9673b805c3529c1dc12016e8d
常见错误与边界
- 写清样本是否等可能。
- 核对条件事件和模拟规则。
练习与解答
若主持人可能打开有奖品的门,能否直接沿用 2/3?
展开参考解答
应先重新给出主持人的行为概率,再计算相应条件概率。