离散分布的使用
您很快就会使用随机策略:在给定状态下,用对动作的概率分布来表示智能体行为的策略。
PyTorch 可以使用 torch.distributions.Categorical 类来表示离散分布,接下来您将对其进行试验。
您会看到,作为输入提供的数字其实不必像概率那样相加为 1;因为它们会被自动归一化。
本练习是课程的一部分
Python 中的深度强化学习
练习说明
- 实例化一个分类概率分布。
- 从该分布中采样 1 次。
- 指定 3 个正数,和为 1,作为概率。
- 指定 5 个正数;Categorical 会在内部将其归一化为概率。
交互式实操练习
通过完成这段示例代码来试试这个练习。
from torch.distributions import Categorical
def sample_from_distribution(probs):
print(f"\nInput: {probs}")
probs = torch.tensor(probs, dtype=torch.float32)
# Instantiate the categorical distribution
dist = ____(probs)
# Take one sample from the distribution
sampled_index = ____
print(f"Taking one sample: index {sampled_index}, with associated probability {dist.probs[sampled_index]:.2f}")
# Specify 3 positive numbers summing to 1
sample_from_distribution([.3, ____, ____])
# Specify 5 positive numbers that do not sum to 1
sample_from_distribution([2, ____, ____, ____, ____])