Bộ đệm experience replay
Bây giờ bạn sẽ tạo cấu trúc dữ liệu để hỗ trợ Experience Replay, giúp agent học hiệu quả hơn rất nhiều.
Bộ đệm replay này cần hỗ trợ hai thao tác:
- Lưu trữ các trải nghiệm vào bộ nhớ để lấy mẫu trong tương lai.
- "Phát lại" một lô ngẫu nhiên các trải nghiệm trong quá khứ từ bộ nhớ của nó.
Vì dữ liệu được lấy mẫu từ bộ đệm sẽ được đưa vào một neural network, bộ đệm nên trả về các Tensor của torch cho tiện lợi.
Các module torch và random cùng lớp deque đã được import vào môi trường bài tập của bạn.
Bài tập này là một phần của khóa học
Deep Reinforcement Learning bằng Python
Hướng dẫn bài tập
- Hoàn thiện phương thức
push()củaReplayBufferbằng cách thêmexperience_tuplevào bộ nhớ của buffer. - Trong phương thức
sample(), rút một mẫu ngẫu nhiên kích thướcbatch_sizetừself.memory. - Vẫn trong
sample(), mẫu ban đầu là danh sách các bộ; đảm bảo chuyển nó thành một bộ các danh sách. - Chuyển
actions_tensorvề dạng(batch_size, 1)thay vì(batch_size).
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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