PERバッファからのサンプリング
エージェントの学習に Prioritized Experience Buffer クラスを使う前に、.sample() メソッドを実装する必要があります。このメソッドは、取得したいサンプルのサイズを引数に取り、サンプルされた遷移を tensor として、メモリバッファ内でのインデックスおよびそれぞれの重要度重みとともに返します。
容量 10 のバッファがあらかじめ環境に読み込まれており、そこからサンプリングできます。
この演習はコースの一部です
Pythonで学ぶDeep Reinforcement Learning
演習の手順
- 各遷移に対応するサンプリング確率を計算します。
- サンプルに含める遷移に対応するインデックスを抽出します。
np.random.choice(a, s, p=p)は、確率配列pに基づき、配列aからサイズsの復元抽出を行います。 - 各遷移に対応する重要度重みを計算します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
def sample(self, batch_size):
priorities = np.array(self.priorities)
# Calculate the sampling probabilities
probabilities = ____ / np.sum(____)
# Draw the indices for the sample
indices = np.random.choice(____)
# Calculate the importance weights
weights = (1 / (len(self.memory) * ____)) ** ____
weights /= np.max(weights)
states, actions, rewards, next_states, dones = zip(*[self.memory[idx] for idx in indices])
weights = [weights[idx] for idx in indices]
states_tensor = torch.tensor(states, dtype=torch.float32)
rewards_tensor = torch.tensor(rewards, dtype=torch.float32)
next_states_tensor = torch.tensor(next_states, dtype=torch.float32)
dones_tensor = torch.tensor(dones, dtype=torch.float32)
weights_tensor = torch.tensor(weights, dtype=torch.float32)
actions_tensor = torch.tensor(actions, dtype=torch.long).unsqueeze(1)
return (states_tensor, actions_tensor, rewards_tensor, next_states_tensor,
dones_tensor, indices, weights_tensor)
PrioritizedReplayBuffer.sample = sample
print("Sampled transitions:\n", buffer.sample(3))