Self-Driving Cars
Topic 20 · Part 4: Deciding what to do · ⏱ about 3.5 h

Reinforcement Learning: Learning to Drive by Trial and Error

Instead of copying a driver, let the car learn from rewards: states, actions and rewards, Q-learning and exploration, train an agent in your browser that learns to keep its lane, then train a deep Q-network to drive in motorway traffic in Colab, and see why rewards are hard to get right.

Softmaxima Simulator StudioWrite your car in Python, with as many files and trained networks as it needs, and watch it drive. In your browser, nothing to install.Open
Show:
In this topic
Beginner

In plain words

Like training a dog with treats: nobody shows the car what to do. It tries things, gets a reward for good results and a penalty for bad ones, and slowly learns which action pays off in each situation.

By the end of this topic you will be able to explain how an agent learns from rewards, and train one in your browser to keep its lane.

Start with: the demo Try it: learn to keep the lane: train, then watch.

Beginner

Learning from rewards

In imitation learning the car copies an expert. In reinforcement learning (RL) nobody shows it what to do: it tries actions, receives rewards, and learns what leads to high total reward over time. The setting is a loop:

  • The agent sees a state ss (here: how far it is from the lane centre, and its heading error).
  • It picks an action aa (a steering angle).
  • The world moves on and gives a reward rr (here: +1 minus the offset each step, −100 for leaving the lane) and the next state s′s'.

The goal is to maximise the return, the sum of future rewards, with later rewards counted a little less by a discount γ\gamma between 0 and 1.

Beginner

Going deeper

The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.

Intermediate · Maths

Q-learning

Q-learning learns a table Q(s,a)Q(s, a): how much total reward to expect from taking action aa in state ss and acting well afterwards. After every step it nudges the table towards what just happened:

Q(s,a)←Q(s,a)+α [ r+γmax⁡a′Q(s′,a′)−Q(s,a)] Q(s, a) \leftarrow Q(s, a) + \alpha\,\Big[\, r + \gamma \max_{a'} Q(s', a') - Q(s, a) \Big]

The bracket is the surprise: the reward we got plus the best value we now expect, minus what we expected before. α\alpha is the learning rate. Once learned, the policy is simple: in each state, take the action with the highest QQ.

An agent that always takes the best-looking action never discovers better ones. ε-greedy exploration takes a random action with probability ε: high at first to explore, lower later to use what it has learned. This trade-off, exploration versus exploitation, is at the heart of RL.

Try it

Try it: learn to keep the lane

The agent starts knowing nothing. Each press trains 100 episodes of up to 50 seconds on randomly bending roads. The chart shows how long the greedy policy stays in its lane; the table shows the best steering it has learned for each state. Watch it after 100 and after 400 episodes. Try exploration fixed at 0.3: it learns, but it keeps making random mistakes while training.

Interactive: this part runs in your browser.

Code

Code: Q-learning in Python

The same agent and road. It trains in about a second. Notice that progress is not smooth: a policy can get worse for a while before it gets better.

Python · NumPy
import numpy as np

rng = np.random.default_rng(0)
# The task: keep a car in its lane on a winding road at 8 m/s, by steering only.
# The state the agent sees: how far it is from the lane centre, and its heading error, each cut into bins.
DT, V = 0.1, 8.0
STEERS = np.array([-0.15, -0.05, 0.0, 0.05, 0.15])          # actions: steering angles (rad)
Y_BINS = np.array([-1.2, -0.6, -0.25, 0.25, 0.6, 1.2])       # 7 offset bins
H_BINS = np.array([-0.15, -0.05, 0.05, 0.15])                # 5 heading bins

def state(y, h):
    return np.searchsorted(Y_BINS, y) * 5 + np.searchsorted(H_BINS, h)

def episode(Q, eps, learn=True, alpha=0.2, gamma=0.95):
    y, h = rng.uniform(-0.5, 0.5), rng.uniform(-0.05, 0.05)
    bends = rng.uniform(-0.04, 0.04, 5)                       # road curvature changes every 10 s
    s = state(y, h)
    for k in range(500):                                      # at most 50 seconds
        a = rng.integers(5) if rng.random() < eps else int(np.argmax(Q[s]))   # explore, or use what we know
        road_k = bends[k // 100]
        h += (V * np.tan(STEERS[a]) / 2.7 - V * road_k) * DT  # the car turns; the road turns under it
        y += V * np.sin(h) * DT
        off = abs(y) > 1.6                                    # a wheel leaves the lane
        r = -100.0 if off else 1.0 - abs(y)                   # reward: stay near the centre, never leave
        s2 = state(y, h)
        if learn:                                             # Q-learning: move Q towards reward + best future value
            target = r if off else r + gamma * Q[s2].max()
            Q[s, a] += alpha * (target - Q[s, a])
        s = s2
        if off:
            return k + 1
    return 500

Q = np.zeros((7 * 5, len(STEERS)))
for ep in range(1, 801):
    eps = max(0.05, 1.0 - ep / 400)                           # explore a lot at first, less later
    episode(Q, eps)
    if ep in (10, 25, 50, 100, 200, 400, 800):
        test = np.mean([episode(Q, 0.0, learn=False) for _ in range(20)])
        print(f"after {ep} episodes: the greedy policy lasts {test / 10:.0f} s on average (50 s = never leaves the lane)")
Open in playground ↗
Advanced

Deep reinforcement learning

A table works for 35 states. A real car's state (positions and speeds of many cars, or a camera image) has far too many to list. Deep RL replaces the table with a neural network that takes the state and outputs a value for each action: a deep Q-network (DQN) (Mnih et al., 2015, which learned Atari games from pixels). Two tricks make it stable: a replay buffer that trains on random past experiences instead of only the latest, and a slowly updated target network for the max⁡Q(s′,a′)\max Q(s', a') term. Policy-gradient methods such as PPO learn the policy directly instead.

highway-env is a free, open-source set of driving tasks for RL: a motorway with traffic, merging, roundabouts, junctions, parking. Its agent chooses high-level actions (change lane left or right, go faster, go slower, keep going), and the environment's own IDM and MOBIL drivers fill the road around it.

Code

Code: a deep Q-network in motorway traffic (Colab)

Run this in Google Colab. It trains a DQN with the settings recommended in the highway-env documentation, then compares it with random actions and with doing nothing. Training takes about 15–30 minutes.

Python (Colab)
# In Google Colab (a GPU is not needed). Training takes about 15–30 minutes.
!pip install -q highway-env stable-baselines3

import gymnasium as gym
import highway_env
import numpy as np
from stable_baselines3 import DQN

if hasattr(gym, "register_envs"):
    gym.register_envs(highway_env)            # newer Gymnasium versions want environments registered explicitly

env = gym.make("highway-fast-v0")            # a 4-lane motorway with traffic; the agent chooses lane changes and speed
print(env.action_space)                        # Discrete(5): 0 left lane, 1 idle, 2 right lane, 3 faster, 4 slower

model = DQN("MlpPolicy", env,                  # the settings from the highway-env documentation
            policy_kwargs=dict(net_arch=[256, 256]), learning_rate=5e-4, buffer_size=15000,
            learning_starts=200, batch_size=32, gamma=0.8, train_freq=1, gradient_steps=1,
            target_update_interval=50, verbose=0)
model.learn(total_timesteps=20_000)

def evaluate(policy, episodes=20):
    crashes, speeds = 0, []
    for ep in range(episodes):
        obs, info = env.reset(seed=ep)
        done = truncated = False
        while not (done or truncated):
            obs, reward, done, truncated, info = env.step(policy(obs))
            speeds.append(info["speed"])
        crashes += info["crashed"]
    return crashes / episodes, np.mean(speeds)

for name, policy in [("random actions", lambda o: env.action_space.sample()),
                     ("always idle", lambda o: 1),
                     ("trained DQN", lambda o: int(model.predict(o, deterministic=True)[0]))]:
    crash_rate, speed = evaluate(policy)
    print(f"{name:>15}: crashes in {crash_rate:.0%} of episodes, average speed {speed:.1f} m/s")
This code needs Gymnasium, which cannot run inside a web page. To run it, press Copy, then paste it into a new notebook in Google Colab ↗ (free; Runtime → Change runtime type → GPU for deep learning).

In highway-env's default reward, high speed is rewarded and crashing ends the episode. Try changing the reward in the environment's config (for example "collision_reward" and "high_speed_reward") and see how the learned driving style changes.

Beginner

Why RL is hard to use in real cars

  • Rewards are hard to specify. Agents find loopholes (reward hacking): reward progress and an agent may learn to drive in circles across the start line; reward "no crashes" and it may learn to stop forever. Good driving is a careful balance of safety, progress, comfort and rules.
  • It needs enormous amounts of experience, including crashes, so it must be done in simulation, which brings back the sim-to-real gap from Part 2.
  • It is hard to verify. A learned policy may behave strangely in a situation it never met in training.

In practice, RL is used mostly in simulation, often combined with imitation learning (learn from human driving first, then improve with RL), and inside systems that keep explicit safety checks around the learned parts. Part 5 is about those checks: how to test a self-driving car and argue that it is safe.

Check yourself

Quiz

1. What does Q(s, a) estimate?

2. Why use ε-greedy exploration?

3. What does the discount γ do?

4. An agent rewarded for "progress" learns to circle across the start line. This is…

5. What does the replay buffer in DQN do?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready