Pytorch中的torch.distributions库怎么使用(pytorch,开发技术)

时间:2024-05-05 16:42:21 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

Pytorch torch.distributions库

包介绍

torch.distributions包包含可参数化的概率分布和采样函数。 这允许构建用于优化的随机计算图和随机梯度估计器。

不可能通过随机样本直接反向传播。 但是,有两种主要方法可以创建可以反向传播的代理函数。

这些是

评分函数估计量 score function estimato
似然比估计量 likelihood ratio estimator
REINFORCE
路径导数估计量 pathwise derivative estimator
REINFORCE 通常被视为强化学习中策略梯度方法的基础,

路径导数估计器常见于变分自编码器的重新参数化技巧中。

虽然评分函数只需要样本 f(x)的值,但路径导数需要导数 f'(x)。

本文重点讲解Pytorch中的 torch.distributions库。

pytorch 的 torch.distributions 中可以定义正态分布:

importtorchfromtorch.distributionsimportNormalmean=torch.Tensor([0,2])normal=Normal(mean,1)

sample()就是直接在定义的正太分布(均值为mean,标准差std是1)上采样:

result=normal.sample()print("sample():",result)

输出:

sample(): tensor([-1.3362, 3.1730])

rsample()不是在定义的正太分布上采样,而是先对标准正太分布 N(0,1) 进行采样,然后输出: mean + std × 采样值

result=normal.rsample()print("rsample():",result)

输出:

rsample: tensor([ 0.0530, 2.8396])

log_prob(value) 是计算value在定义的正态分布(mean,1)中对应的概率的对数,正太分布概率密度函数是:

Pytorch中的torch.distributions库怎么使用

对其取对数可得:

Pytorch中的torch.distributions库怎么使用

这里我们通过对数概率还原其对应的真实概率:

print("resultlog_prob:",normal.log_prob(result).exp())

输出:

result log_prob: tensor([ 0.1634, 0.2005])

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Pytorch中的torch.distributions库怎么使用的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:C语言函数调用底层实现原理是什么下一篇:

5 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18