開始使用免費開始

操作離散機率分佈

接下來你會使用隨機性策略(stochastic policy):在給定狀態下,策略以對各個動作的機率分佈來描述代理人的行為。

PyTorch 可以用 torch.distributions.Categorical 類別來表示離散分佈,你現在就要實際操作看看。

你會發現,作為輸入的數字其實不需要像機率那樣相加為 1;它們會自動被正規化。

本練習屬於課程

Python 的深度強化學習

檢視課程

練習說明

  • 建立一個類別型(categorical)的機率分佈。
  • 從該分佈取一個樣本。
  • 指定 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, ____, ____, ____, ____])
編輯並執行程式碼