经验回放缓冲区
现在,您将创建用于支持经验回放(Experience Replay)的数据结构,这将使智能体的学习效率大幅提升。
该回放缓冲区需要支持两个操作:
- 将交互经验存入其内存,以便后续采样。
- 从其内存中随机采样一批过往经验并"回放"。
由于从回放缓冲区采样的数据将用来输入神经网络,为了方便,应返回 torch 张量。
本练习环境中已导入 torch、random 模块以及 deque 类。
本练习是课程的一部分
Python 中的深度强化学习
练习说明
- 完成
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