这是indexloc提供的服务,不要输入任何密码
Skip to content

Added support for clipping to DQNPolicy. #642

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 18, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion tianshou/policy/modelfree/dqn.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ class DQNPolicy(BasePolicy):
:param bool reward_normalization: normalize the reward to Normal(0, 1).
Default to False.
:param bool is_double: use double dqn. Default to True.
:param bool clip_loss_grad: clip the gradient of the loss in accordance
with nature14236; this amounts to using the Huber loss instead of
the MSE loss. Default to False.
:param lr_scheduler: a learning rate scheduler that adjusts the learning rate in
optimizer in each policy.update(). Default to None (no lr_scheduler).

Expand All @@ -44,6 +47,7 @@ def __init__(
target_update_freq: int = 0,
reward_normalization: bool = False,
is_double: bool = True,
clip_loss_grad: bool = False,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
Expand All @@ -62,6 +66,7 @@ def __init__(
self.model_old.eval()
self._rew_norm = reward_normalization
self._is_double = is_double
self._clip_loss_grad = clip_loss_grad

def set_eps(self, eps: float) -> None:
"""Set the eps for epsilon-greedy exploration."""
Expand Down Expand Up @@ -168,7 +173,14 @@ def learn(self, batch: Batch, **kwargs: Any) -> Dict[str, float]:
q = q[np.arange(len(q)), batch.act]
returns = to_torch_as(batch.returns.flatten(), q)
td_error = returns - q
loss = (td_error.pow(2) * weight).mean()

if self._clip_loss_grad:
y = q.reshape(-1, 1)
t = returns.reshape(-1, 1)
loss = torch.nn.functional.huber_loss(y, t, reduction="mean")
else:
loss = (td_error.pow(2) * weight).mean()

batch.weight = td_error # prio-buffer
loss.backward()
self.optim.step()
Expand Down