Experience replay バッファ
これから、Experience Replay を支えるデータ構造を作成します。これにより、エージェントははるかに効率的に学習できるようになります。
この replay バッファは次の 2 つの操作をサポートする必要があります。
- 将来のサンプリングに備えて、経験をメモリに保存する。
- メモリから過去の経験をランダムにバッチ抽出して「再生」する。
replay バッファからサンプルされたデータはニューラルネットワークに入力されるため、利便性のために torch の Tensor を返すようにします。
torch と random モジュール、および deque クラスは演習環境にインポート済みです。
この演習はコースの一部です
Pythonで学ぶDeep Reinforcement Learning
演習の手順
ReplayBufferのpush()メソッドを完成させ、experience_tupleをバッファのメモリに追加します。sample()メソッドでは、self.memoryからサイズbatch_sizeのランダムサンプルを取得します。- 同じく
sample()で、最初はタプルのリストとして取得されるサンプルを、リストのタプルに変換します。 actions_tensorの形状を(batch_size)ではなく(batch_size, 1)に変換します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
class ReplayBuffer:
def __init__(self, capacity):
self.memory = deque([], maxlen=capacity)
def push(self, state, action, reward, next_state, done):
experience_tuple = (state, action, reward, next_state, done)
# Append experience_tuple to the memory buffer
self.memory.____
def __len__(self):
return len(self.memory)
def sample(self, batch_size):
# Draw a random sample of size batch_size
batch = ____(____, ____)
# Transform batch into a tuple of lists
states, actions, rewards, next_states, dones = ____
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)
# Ensure actions_tensor has shape (batch_size, 1)
actions_tensor = torch.tensor(actions, dtype=torch.long).____
return states_tensor, actions_tensor, rewards_tensor, next_states_tensor, dones_tensor