Coding中等
手撕 DQN(含 target net + replay buffer)
replay buffer 打破时序相关性;
简要回答
replay buffer 打破时序相关性;target net 稳定 bootstrap;target 上必须 detach。
标准答案
考察点:replay buffer 打破时序相关性;target net 稳定 bootstrap;target 上必须 detach。
实现:
import randomfrom collections import deque
import torch
import torch.nn.functional as F
class ReplayBuffer:
def __init__(self, cap): self.buf = deque(maxlen=cap)
def push(self, *t): self.buf.append(t)
def sample(self, n):
s, a, r, s2, d = zip(*random.sample(self.buf, n))
# 一次性堆叠为 batch tensor
return [torch.as_tensor(x).float() if i != 1 else torch.as_tensor(x).long()
for i, x in enumerate([s, a, r, s2, d])]
def dqn_loss(q_net, q_target_net, batch, gamma=0.99):
s, a, r, s2, d = batch
q_sa = q_net(s).gather(1, a.unsqueeze(1)).squeeze(1)
with torch.no_grad(): # target net 不回传梯度
target = r + gamma * q_target_net(s2).max(1).values * (1.0 - d)
return F.smooth_l1_loss(q_sa, target) # Huber 比 MSE 更稳
常见错误
- target 未 detach 导致梯度回灌
- 还加
γV(s') - replay 容量太小样本相关性高。