7 概率

1.概率

import torch
from torch.distributions import multinomial #torch关于概率的库
from d2l import torch as d2l

fair_probs = torch.ones([6])/6
fair_probs
<frozen importlib._bootstrap>:219: RuntimeWarning: numpy.ufunc size changed, may indicate binary incompatibility. Expected 216 from C header, got 232 from PyObject





tensor([0.1667, 0.1667, 0.1667, 0.1667, 0.1667, 0.1667])
#创建一个多项式 相当于投掷10次色子,6个面出现的次数 ,总共做500次实验
counts = multinomial.Multinomial(10,fair_probs).sample((500,))
counts,counts.shape

(tensor([[3., 0., 3., 0., 1., 3.],
         [2., 4., 1., 0., 2., 1.],
         [0., 2., 2., 0., 2., 4.],
         ...,
         [2., 1., 3., 2., 0., 2.],
         [3., 0., 1., 4., 2., 0.],
         [0., 2., 3., 1., 2., 2.]]),
 torch.Size([500, 6]))
#按0轴累加
cum_counts = counts.cumsum(dim=0)
estimates = cum_counts/cum_counts.sum(dim=1,keepdims=True)#按1轴求和
estimates
tensor([[0.3000, 0.0000, 0.3000, 0.0000, 0.1000, 0.3000],
        [0.2500, 0.2000, 0.2000, 0.0000, 0.1500, 0.2000],
        [0.1667, 0.2000, 0.2000, 0.0000, 0.1667, 0.2667],
        ...,
        [0.1697, 0.1661, 0.1635, 0.1657, 0.1679, 0.1673],
        [0.1699, 0.1657, 0.1633, 0.1661, 0.1679, 0.1669],
        [0.1696, 0.1658, 0.1636, 0.1660, 0.1680, 0.1670]])
#色子递进过程可视化 逐渐逼近fair_probs
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("Extimated probability")
d2l.plt.legend()
<matplotlib.legend.Legend at 0x243fd4b63d0>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值