Entropy 操作練習場
如果你之前沒有接觸過 entropy(熵),用一個小範例來建立直覺會很有幫助。
你將撰寫一個函式 plot_probabilities,輸入為一個機率清單。它會計算熵,並用長條圖繪出各機率。
在實際操作中,你會發現:當機率分佈更分散、覆蓋更多動作時,熵會更高。
torch.distribution.Categorical 類別已在環境中以 Categorical 載入;此類別有一個 .entropy() 方法,會回傳以 nat 為單位的熵。
本練習屬於課程
Python 的深度強化學習
練習說明
- 取得該機率分佈以 nat 為單位的熵。
- 為了方便,比較後將熵從 nat 轉換為 bit。
- 嘗試用另一個清單作為函式的輸入。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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(____)