熵的游乐场
如果您之前没有接触过熵的概念,通过一个示例来理解会很有帮助。
您将编写一个函数 plot_probabilities,接收一个概率列表作为参数。它会计算熵,并以柱状图绘制这些概率。
在尝试不同的概率分布时,您会发现:当概率分布更「分散」到多个动作上时,熵会更高。
环境中已将 torch.distribution.Categorical 类以 Categorical 名称加载;该类有一个 .entropy() 方法,会返回以纳特(nats)为单位的熵。
本练习是课程的一部分
Python 中的深度强化学习
练习说明
- 获取该概率分布以纳特为单位的熵。
- 为了方便,将熵从纳特转换为比特。
- 尝试使用另一个列表作为该函数的输入。
交互式实操练习
通过完成这段示例代码来试试这个练习。
def plot_probabilities(probs):
dist = Categorical(torch.tensor(probs))
# Obtain the entropy in nats
entropy = dist.____
# Convert the entropy to bits
entropy = entropy / math.log(____)
print(f"{'Probabilities:':>15} {[round(prob, 3) for prob in dist.probs.tolist()]}")
print(f"{'Entropy:':>15} {entropy:.2f}\n")
plt.figure()
plt.bar([str(x) for x in range(len(dist.probs))], dist.probs, color='skyblue', edgecolor='black')
plt.ylabel('Probability'); plt.xlabel('Action index'); plt.ylim(0, 1)
plt.show()
plot_probabilities([.25, .25, .25, .25])
plot_probabilities([.1, .15, .2, .25, .3])
# Try with your own list
plot_probabilities(____)