概率
一、基本概率论——模拟骰子
1、导入必要包
# matplotlib inline jupyter常用于生成画布 %matplotlib inline import torch from torch.distributions import multinomial from d2l import torch as d2l
2、相对概率做真实概率
# 进行500组实验,每组抽取10个样本
# 数据将存在一个500*6的矩阵中
counts = multinomial.Multinomial(10, fair_probs).sample((500,))
print(counts)
# dim=0,逐行相加
# cumsum保持维度
cum_counts = counts.cumsum(dim=0)
print(cum_counts)
# keepdims=True非降维
# 生成只有500*1的矩阵(只有一列)
# print(cum_counts.sum(dim=1, keepdims=True))
# 计算相对频率模拟真实概率
estimates = cum_counts / cum_counts.sum(dim=1, keepdims=True)
print(estimates)
# figsize: 指定figure的宽和高,单位为英寸
d2l.set_figsize((6, 4.5))
for i in range(6):
d2l.plt.plot(estimates[:, i].numpy(), label=("P(die=" + str(i + 1) + ")"))
d2l.plt.axhline(y=0.167, color='black', linestyle='dashed')
d2l.plt.gca().set_xlabel('Groups of experiments')
d2l.plt.gca().set_ylabel('Estimated probability')
d2l.plt.legend();
#输出结果
tensor([[2., 1., 1., 1., 3., 2.],
[1., 3., 3., 1., 1., 1.],
[2., 0., 3., 1., 4., 0.],
...,
[3., 1., 3., 0., 0., 3.],
[3., 1., 2., 1., 1., 2.],
[3., 1., 1., 1., 2., 2.]])
tensor([[ 2., 1., 1., 1., 3., 2.],
[ 3., 4., 4., 2., 4., 3.],
[ 5., 4., 7., 3., 8., 3.],
...,
[803., 782., 860., 829., 857., 849.],
[806., 783., 862., 830., 858., 851.],
[809., 784., 863., 831., 860., 853.]])
tensor([[0.2000, 0.1000, 0.1000, 0.1000, 0.3000, 0.2000],
[0.1500, 0.2000, 0.2000, 0.1000, 0.2000, 0.1500],
[0.1667, 0.1333, 0.2333, 0.1000, 0.2667, 0.1000],
...,
[0.1612, 0.1570, 0.1727, 0.1665, 0.1721, 0.1705],
[0.1615, 0.1569, 0.1727, 0.1663, 0.1719, 0.1705],
[0.1618, 0.1568, 0.1726, 0.1662, 0.1720, 0.1706]])
绘图略
二、概率论公理
1、样本空间:也称结果空间。在处理骰子掷出时,我们将集合 S={1,2,3,4,5,6}称为样本空间
2、样本空间中每个元素称为结果
3、事件是来自样本空间的一组结果
4、联合概率: P(A=a,B=b):表示事件A和事件B同时发生的概率
5、条件概率:P(B=b∣A=a):表示在事件A发生的前提下,事件B发生的概率
6、贝叶斯定理 :
P(A,B)=P(B∣A)P(A)
P(A,B)=P(A∣B)P(B)

1、随机变量X的期望(或平均值)

2、函数f(x)的期望

3、随机变量X的方差:衡量随机变量X与期望值的偏差

4、函数f(x)的方差

浙公网安备 33010602011771号