DQN với prioritized experience replay
Trong bài tập này, bạn sẽ đưa Prioritized Experience Replay (PER) vào để cải thiện thuật toán DQN. Mục tiêu của PER là tối ưu hóa lô các chuyển tiếp được chọn để cập nhật mạng tại mỗi bước.
Tham khảo lại, các tên phương thức bạn đã khai báo cho PrioritizedReplayBuffer gồm:
push()(để đưa các chuyển tiếp vào bộ đệm)sample()(để lấy mẫu một lô chuyển tiếp từ bộ đệm)increase_beta()(để tăng mức trọng số của importance sampling)update_priorities()(để cập nhật độ ưu tiên đã lấy mẫu)
Hàm describe_episode() tiếp tục được dùng để mô tả mỗi episode.
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
- Khởi tạo một Prioritized Experience Replay buffer với dung lượng 10000 chuyển tiếp.
- Tăng dần ảnh hưởng của importance sampling theo thời gian bằng cách cập nhật tham số
beta. - Cập nhật độ ưu tiên của các trải nghiệm đã lấy mẫu dựa trên sai số TD mới nhất của chúng.
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.
# Instantiate a Prioritized Replay Buffer with capacity 10000
replay_buffer = ____(____)
for episode in range(5):
state, info = env.reset()
done = False
step = 0
episode_reward = 0
# Increase the replay buffer's beta parameter
replay_buffer.____
while not done:
step += 1
total_steps += 1
q_values = online_network(state)
action = select_action(q_values, total_steps, start=.9, end=.05, decay=1000)
next_state, reward, terminated, truncated, _ = env.step(action)
done = terminated or truncated
replay_buffer.push(state, action, reward, next_state, done)
if len(replay_buffer) >= batch_size:
states, actions, rewards, next_states, dones, indices, weights = replay_buffer.sample(64)
q_values = online_network(states).gather(1, actions).squeeze(1)
with torch.no_grad():
next_q_values = target_network(next_states).amax(1)
target_q_values = rewards + gamma * next_q_values * (1-dones)
td_errors = target_q_values - q_values
# Update the replay buffer priorities for that batch
replay_buffer.____(____, ____)
loss = torch.sum(weights * (q_values - target_q_values) ** 2)
optimizer.zero_grad()
loss.backward()
optimizer.step()
update_target_network(target_network, online_network, tau=.005)
state = next_state
episode_reward += reward
describe_episode(episode, reward, episode_reward, step)