从 PER 缓冲区采样
在使用优先级经验缓冲区(Prioritized Experience Buffer)类训练智能体之前,您还需要实现 .sample() 方法。该方法的参数是您希望抽取的样本大小,返回由 tensors 表示的已采样转移,以及它们在内存缓冲区中的索引和对应的重要性权重。
一个容量为 10 的缓冲区已预先加载到您的环境中,供您进行采样。
本练习是课程的一部分
Python 中的深度强化学习
练习说明
- 计算每个转移对应的采样概率。
- 抽取样本中各转移对应的索引;
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))