> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# DQN for Robot Navigation

> Deep Q-learning with five steering commands and the full observation.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/reinforcement-learning/robot-navigation/dqn-navigation/index.ipynb)

[Q-learning for Robot Navigation](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/q-learning-navigation/index.md) kept five steering commands and learned a table over 216 coarse states. The table could not tell apart the many situations that share one state. This section keeps the five commands and gives the agent the full 28-number observation of [Robot Navigation as an MDP](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-mdp/index.md): the 24 lidar ranges, the goal's distance and bearing, and the previous command. A neural network takes the place of the table. As in the other navigation sections, the agent treats the observation as if it were the state, although the state is the robot's pose.

The agent is the deep Q-network of [Q-learning with Function Approximation](https://aegean.ai/aiml-common/lectures/reinforcement-learning/value-based-algorithms/control/dqn/dqn.md), with its replay buffer and target network, and Double DQN as a variant. The simulator, reward and episode rules are the ones of Robot Navigation as an MDP.

> [accordion] Code
>
> ```python theme={null}
> import numpy as np
> import matplotlib.pyplot as plt
> from matplotlib.patches import Circle, Rectangle
>
> from cycler import cycler
> from matplotlib_inline.backend_inline import (
>     set_matplotlib_formats,
> )
>
> set_matplotlib_formats("svg")
> FIG_GRAY = "#808080"
> FIG_COLORS = [
>     "#0072B2",
>     "#D55E00",
>     "#009E73",
>     "#cb77a6",
>     "#c28600",
>     "#1d99e0",
>     "#7f7f7f",
> ]
> plt.rcParams.update(
>     {
>         "figure.facecolor": "none",
>         "axes.facecolor": "none",
>         "savefig.facecolor": "none",
>         "savefig.transparent": True,
>         "text.color": FIG_GRAY,
>         "axes.labelcolor": FIG_GRAY,
>         "axes.edgecolor": FIG_GRAY,
>         "xtick.color": FIG_GRAY,
>         "ytick.color": FIG_GRAY,
>         "grid.color": FIG_GRAY,
>         "grid.alpha": 0.25,
>         "legend.facecolor": "none",
>         "legend.edgecolor": FIG_GRAY,
>         "legend.framealpha": 0,
>         "axes.prop_cycle": cycler(color=FIG_COLORS),
>         "svg.hashsalt": "aiml",
>         "svg.fonttype": "path",
>     }
> )
> BLUE, ORANGE, GREEN, PINK, GOLD = FIG_COLORS[:5]
> ```
>
> ```python theme={null}
> # The simulator of Robot Navigation as an MDP and the helpers shared by the navigation
> # sections live in navsim.py, next to the navigation notebooks. Find it, or download it
> # when only this notebook is present.
> import os
> import sys
> import urllib.request
>
> NAVSIM_URL = ("https://raw.githubusercontent.com/pantelis/eng-ai-agents/main/"
>               "notebooks/reinforcement-learning/robot-navigation/navsim.py")
> folders = ["..", ".", "notebooks/reinforcement-learning/robot-navigation"]
> folder = next((f for f in folders if os.path.exists(os.path.join(f, "navsim.py"))), None)
> if folder is None:
>     urllib.request.urlretrieve(NAVSIM_URL, "navsim.py")
>     folder = "."
> sys.path.insert(0, os.path.abspath(folder))
> from navsim import *
> ```
>
> ```python theme={null}
> import copy
> import torch
> import torch.nn as nn
>
> torch.set_num_threads(4)
> ```

## Five commands, a network for the action values

The five commands are the ones of the tabular agent. Each turns at a fixed rate, and the sharper turns drive more slowly:

| Action | 0 | 1 | 2 | 3 | 4 |
| - | - | - | - | - | - |
| $\omega$ (rad/s) | $-1.5$ | $-0.75$ | 0 | 0.75 | 1.5 |
| $v$ (m/s) | 0.10 | 0.18 | 0.26 | 0.18 | 0.10 |

The network maps the 28 numbers to five action values $Q(o, a; \mathbf w)$, one per command, so the greedy action is the argmax of its output.

```python theme={null}
W_ACT = np.array([-1.5, -0.75, 0.0, 0.75, 1.5])   # turn rate of each action (rad/s)
V_ACT = np.array([0.10, 0.18, 0.26, 0.18, 0.10])   # forward speed of each action (m/s)
N_ACTIONS = len(W_ACT)


def q_policy(qnet):
    """Wrap a Q-network as a greedy policy for rollout(): the command of argmax_a Q(o, a)."""

    def policy(env):
        with torch.no_grad():
            a = int(qnet(torch.as_tensor(env.observe())).argmax())
        return V_ACT[a], W_ACT[a]

    return policy
```

## Training

Training follows the DQN section. The agent acts $\epsilon$-greedily, with $\epsilon$ falling from 1 to 0.05 over the first 30% of the 100,000 steps. It stores every transition in a replay buffer, learns from random minibatches of 256 transitions, and computes its targets with a target network that is copied from the trained network every 2,000 steps. The loss is the Huber loss of the TD error. Double DQN changes only the target: the trained network picks the next action, and the target network evaluates it. A goal or a collision ends the target; after a timeout the target still bootstraps, because the robot still has a future.

Every 10,000 steps the code runs the greedy policy on 50 fixed episodes and records three numbers: the success rate, the network's estimate $\max_a Q(s_0, a)$ of the start states, and the discounted return actually collected from them. The return is measured as on the [DDPG](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/ddpg-navigation/index.md) page, by letting each episode run past the timeout, so the two pages can be compared.

> [accordion] Code
>
> ```python theme={null}
> def evaluate_q(qnet, n=50, seed=123, gamma=0.99, horizon=1000):
>     """Greedy success rate, the network's estimate max_a Q(s_0, a) of the start states, and the return obtained.
>
>     As on the DDPG page, the network's targets do not stop at the timeout, so the return keeps
>     summing rewards past it, until a goal, a collision or `horizon` steps. Success counts only
>     goals reached before the timeout.
>     """
>     env = NavEnv(seed=seed)
>     goals, q_est, returns = 0, [], []
>     for _ in range(n):
>         o = env.reset()
>         with torch.no_grad():
>             q_est.append(qnet(torch.as_tensor(o)).max().item())
>         G, k, event = 0.0, 0, None
>         while k < horizon:
>             with torch.no_grad():
>                 a = int(qnet(torch.as_tensor(o)).argmax())
>             o, r, term, trunc, info = env.step(V_ACT[a], W_ACT[a])
>             G, k = G + gamma**k * r, k + 1
>             if event is None and (term or trunc):
>                 event = info["event"]
>             if term:
>                 break
>         goals += event == "goal"
>         returns.append(G)
>     return goals / n, np.mean(q_est), np.mean(returns)
>
>
> def train_dqn(variant="dqn", steps=100_000, gamma=0.99, lr=5e-4, batch=256,
>               warmup=5000, target_every=2000, eps_end=0.05, eps_frac=0.3, seed=0):
>     """Train DQN or Double DQN on the navigation task with the five steering commands.
>
>     Args:
>         variant: "dqn" (the target network picks and evaluates the next action) or "double"
>             (the trained network picks it and the target network evaluates it).
>         steps: environment steps.
>         gamma: discount factor.
>         lr: Adam step size.
>         batch: minibatch size.
>         warmup: steps of random actions before learning starts.
>         target_every: steps between copies of the trained network into the target network.
>         eps_end: final exploration rate; epsilon falls linearly from 1 over eps_frac of training.
>         eps_frac: fraction of training over which epsilon decays.
>         seed: seed of the networks, the buffer and the environment.
>
>     Returns:
>         (qnet, log): the final network and an array of (step, success rate, estimate, return).
>     """
>     torch.manual_seed(seed)
>     rng = np.random.default_rng(seed)
>     env = NavEnv(seed=seed)
>     qnet = mlp(OBS_DIM, N_ACTIONS)
>     qnet_t = copy.deepcopy(qnet)
>     opt = torch.optim.Adam(qnet.parameters(), lr=lr)
>     buf, log = ReplayBuffer(act_dim=1), []
>     o = env.reset()
>     for t in range(steps):
>         eps = max(eps_end, 1.0 - t / (eps_frac * steps))
>         if t < warmup or rng.random() < eps:
>             a = int(rng.integers(N_ACTIONS))
>         else:
>             with torch.no_grad():
>                 a = int(qnet(torch.as_tensor(o)).argmax())
>         o2, r, term, trunc, _ = env.step(V_ACT[a], W_ACT[a])
>         buf.add(o, [a], r, o2, float(term))
>         o = env.reset() if term or trunc else o2
>         if t < warmup:
>             continue
>         O, A, R, O2, TERM = buf.sample(batch, rng)
>         with torch.no_grad():
>             if variant == "dqn":
>                 q_next = qnet_t(O2).max(1).values
>             else:
>                 a_next = qnet(O2).argmax(1, keepdim=True)
>                 q_next = qnet_t(O2).gather(1, a_next).squeeze(1)
>             y = R + gamma * (1 - TERM) * q_next
>         q = qnet(O).gather(1, A.long()).squeeze(1)
>         loss = nn.functional.smooth_l1_loss(q, y)
>         opt.zero_grad()
>         loss.backward()
>         opt.step()
>         if (t + 1) % target_every == 0:
>             qnet_t.load_state_dict(qnet.state_dict())
>         if (t + 1) % 10_000 == 0:
>             log.append((t + 1, *evaluate_q(qnet)))
>     return qnet, np.array(log)
>
>
> nets, logs = {}, {}
> for variant in ("dqn", "double"):
>     nets[variant], logs[variant] = train_dqn(variant)
>     final = logs[variant][-1]
>     print(f"{variant:6s} after {int(final[0])} steps: success {final[1]:.2f}, "
>           f"estimate {final[2]:.1f}, return obtained {final[3]:.1f}")
> ```

```output theme={null}
dqn    after 100000 steps: success 0.72, estimate 3.6, return obtained 5.9
double after 100000 steps: success 0.84, estimate 2.6, return obtained 9.6
```

![Output from cell 6](https://mintcdn.com/aegeanaiinc/OBJGq7jXQhjy7Xzc/aiml-common/lectures/reinforcement-learning/robot-navigation/dqn-navigation/images/cell_6_output_1.svg?fit=max\&auto=format\&n=OBJGq7jXQhjy7Xzc\&q=85\&s=c5ccdbdd0214871640929a7f77334c71)

*Left: greedy success rate on the 50 evaluation episodes. Right: the network's estimate of the start states' value (solid) and the discounted return actually collected from them (dashed).*

Both agents learn the task, and neither collapses the way the DDPG actor does. Double DQN reaches the goal in 60% of the evaluation episodes after 40,000 steps and stays between 70% and 84% from 50,000 steps on. DQN rises later, dips twice, peaks at 90% after 90,000 steps and ends at 72%.

The right panel shows no overestimation in this run. The estimates rise slowly from zero and stay below the returns once the agents reach the goal regularly. At the end they are 3.6 and 2.6, against returns of 5.9 and 9.6. The target network is copied only every 2,000 steps, so after 100,000 steps the bootstrapped values have not yet caught up with the returns. On CartPole, the [DQN section](https://aegean.ai/aiml-common/lectures/reinforcement-learning/value-based-algorithms/control/dqn/dqn.md) shows the same pattern before its estimates overtake the returns. One difference from DDPG is the size of the max: here it runs over five fixed commands, while the DDPG actor searches a continuous range of commands for the critic's highest value.

## Test on the common episodes

The final networks, not the best checkpoints, run on the same 300 test episodes as the go-to-goal controller and the tabular agent.

> [accordion] Code
>
> ```python theme={null}
> print("go-to-goal:", success_rate(go_to_goal))
> for variant in ("dqn", "double"):
>     print(f"{LABELS[variant]} (final network):", success_rate(q_policy(nets[variant])))
> ```

```output theme={null}
go-to-goal: {'goal': 0.26, 'collision': 0.74, 'timeout': 0.0}
DQN (final network): {'goal': 0.7933333333333333, 'collision': 0.20666666666666667, 'timeout': 0.0}
Double DQN (final network): {'goal': 0.84, 'collision': 0.16, 'timeout': 0.0}
```

The final DQN network reaches the goal in 79% of the 300 test episodes and collides in 21%. The final Double DQN network reaches it in 84% and collides in 16%. Neither times out. The tabular agent of [Q-learning for Robot Navigation](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/q-learning-navigation/index.md) reaches the goal in 81% of the same episodes. With only five commands and 100,000 steps of training, the network and the full observation change the result by a few points: Double DQN does a little better than the table, and plain DQN a little worse. [DDPG for Robot Navigation](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/ddpg-navigation/index.md) keeps the network and drops the five commands: its actor outputs any speed and turn rate.

**Key references**: (Mnih et al., 2015; Sutton & Barto, 2018)

## References

* Mnih, V., Kavukcuoglu, K., Silver, D., Rusu, A., Veness, J., et al. (2015). *Human-level control through deep reinforcement learning*. Nature. [DOI](https://doi.org/10.1038/nature14236)
* Sutton, R., Barto, A. (2018). *Reinforcement Learning: An Introduction*. [Link](https://www.andrew.cmu.edu/course/10-703/textbook/BartoSutton.pdf)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/reinforcement-learning/robot-navigation/dqn-navigation).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.