Reinforcement Learning Basics: Agents, Rewards and Q-learning
Learning by trial and error: the agent–environment loop, Markov decision processes, returns and discounting, policies and value functions, the Q-learning update, and the exploration–exploitation trade-off with ε-greedy.
In Supervised learning someone gives you the right answer for every example. In reinforcement learning (RL) nobody does: an agent acts in an environment, receives a numeric Reward now and then, and must discover by trial and error which behaviour earns the most reward over time. RL taught computers to play Atari and Go, controls robots and data-center cooling, tunes recommendation systems, and — through RLHF — shapes how chatbots like ChatGPT and Claude respond.
The agent–environment loop
- The agent observes the current state sₜ (e.g. its position on a grid).
- It chooses an action aₜ according to its Policy π.
- The environment returns a reward rₜ₊₁ and the next state sₜ₊₁.
- Repeat until a terminal state (goal, pit, game over) ends the episode, or forever in continuing tasks.
The goal is not the next reward but the return: the sum of future rewards, with later rewards shrunk by the Discount factor (γ) γ (gamma) between 0 and 1. Discounting keeps sums finite in endless tasks and expresses a preference for sooner rewards — a reward 10 steps away is worth γ¹⁰ of one received now (0.35 when γ = 0.9).
- Gₜ
- the return: total discounted reward collected from time step t onward
- rₜ₊₁
- the reward received right after acting at time t
- γ
- gamma, the discount factor between 0 and 1 (typically 0.9–0.99)
- γ²
- γ multiplied by itself: the weight of a reward two steps later than the first
- …
- the pattern continues until the episode ends (or forever in continuing tasks)
- Σₖ
- sum over k = 0, 1, 2, …
- γᵏ
- discount applied to the reward k steps after the first one
- rₜ₊ₖ₊₁
- the reward k + 1 steps after time t
▸Worked example
Markov decision processes
RL problems are formalised as a Markov decision process (MDP) (S, A, P, R, γ): a set of states S, actions A, transition probabilities P(s′ | s, a), a reward function R(s, a, s′), and γ. The Markov property says the next state depends only on the current state and action, not on the full history — so the state must contain everything relevant. In a slippery gridworld, P captures that “move right” might actually slide you down. When the agent cannot see the full state (poker, a robot with a limited camera) the problem becomes a *partially observable* MDP[1].
Policies and value functions
A policy π(a | s) maps states to (probabilities of) actions. A Value function predicts how good things are under a policy: the state value V^π(s) is the expected return starting from s; the action value Q^π(s, a) is the expected return after taking action a in s and following π afterwards. If you know the optimal Q*, acting optimally is easy: pick argmaxₐ Q*(s, a). Value functions satisfy the recursive Bellman equations — the value of a state equals the immediate reward plus the discounted value of where you land[4].
- Q*(s, a)
- the optimal action value: expected return of taking action a in state s and acting optimally afterwards
- E[
- expected value (average) over the randomness of the next state and reward
- r
- the immediate reward
- γ
- discount factor (0–1)
- maxₐ′
- the largest value over all possible next actions a′
- s′
- the next state
- a′
- a possible action in the next state
- | s, a
- “given that” the current state is s and the action is a
▸Worked example
Q-learning
Q-learning (Watkins, 1989; convergence proof by Watkins & Dayan, 1992)[2] learns Q* directly from experience, without knowing P or R. It keeps a table Q[s, a]. After each step it computes a target — the reward plus the discounted best Q-value of the next state — and nudges the old estimate toward it by a fraction α (the learning rate). The gap between target and estimate is the temporal-difference (TD) error. Q-learning is off-policy: it learns the value of the greedy policy even while behaving exploratorily. With enough exploration of every state–action pair and a suitably decaying α, it converges to Q*.
- Q(s, a)
- current table entry: estimated return for action a in state s
- ←
- assignment: overwrite the left side with the right side
- α
- alpha, the learning rate (0–1, e.g. 0.1): how far to move toward the target
- r
- the reward just received
- γ
- discount factor
- maxₐ′ Q(s′, a′)
- best estimated value in the next state s′ (greedy, even if the agent explores)
- [
- the bracket contains the TD error: target minus old estimate
▸Worked example
Exploration vs exploitation
If the agent always takes the action with the highest current Q (exploitation), it may lock onto the first decent path and never discover a better one. If it always acts randomly (exploration), it never cashes in on what it learned. This is the Exploration–exploitation trade-off trade-off. The simplest fix is ε-greedy: with probability ε take a random action, otherwise the greedy one. Usually ε starts high (1.0) and decays toward a small floor (0.01–0.1) as the agent learns. Alternatives include optimistic initial values, softmax/Boltzmann exploration, and UCB-style bonuses for rarely tried actions.
- Watch value propagate: reset Q, then run episodes one at a time. The first time the agent reaches the goal, only the cell next to it gets value; with each episode the “warm” region spreads backward toward the start — that is the Bellman update at work.
- ε = 0 from scratch: set ε to 0 and train 200 episodes. The agent often never finds the goal (or sticks to a poor route). Raise ε to 0.2 and train again.
- γ low vs high: with γ = 0.5 values fade quickly away from the goal and far cells stay near zero; with γ = 0.99 the whole grid “knows” where the goal is.
- Risky shortcut: place pits along a short path and build a longer, safe corridor. Q-learning usually still learns the short route right next to the pits (it values the *greedy* policy), even though its random ε-moves during training often drop it into a pit — visible as dips in the return chart.
- α too high: set α near 1 and watch the episode-return chart jump around; lower α smooths learning but slows it down.
- Step cost: compare a step cost of 0 vs −0.04. With no step cost the agent has little reason to hurry (only discounting); a small penalty per step produces shorter paths.
The knobs
- What it is
- How far each Q-value moves toward the new TD target (0 = never learn, 1 = overwrite with the latest target).
- ↑ If you increase it
- Faster learning in deterministic worlds, but in stochastic ones values chase noise and oscillate.
- ↓ If you decrease it
- Smoother, more stable averages, but slow propagation; needs many more episodes.
- Typical values
- 0.05–0.5 for tabular problems; often decayed over time.
- What it is
- Weight on future rewards; sets the effective planning horizon ≈ 1 / (1 − γ) steps.
- ↑ If you increase it
- Far-sighted: values propagate far, the agent plans long routes; learning becomes slower and noisier. γ = 1 only makes sense for tasks that always terminate.
- ↓ If you decrease it
- Myopic: the agent grabs nearby rewards and ignores distant goals; values far from rewards stay ~0.
- Typical values
- 0.9–0.99 (horizon of 10–100 steps).
- What it is
- Probability of taking a random action instead of the greedy one in ε-greedy.
- ↑ If you increase it
- Discovers more of the environment and escapes bad early habits, but collects less reward while training and can wander into hazards.
- ↓ If you decrease it
- Exploits what it knows; with ε too small early on, it can get stuck on a suboptimal path forever.
- Typical values
- Start 1.0, decay (e.g. × 0.995 per episode) to 0.01–0.1.
- What it is
- How many complete trials of experience the agent collects.
- ↑ If you increase it
- More accurate Q-values and a more reliable policy, with diminishing returns once the policy stops changing.
- ↓ If you decrease it
- Faster, but far-away states may still have zero or wrong values and arrows point randomly there.
- Typical values
- Hundreds to thousands for small grids; millions of steps for Atari-scale deep RL.
- What it is
- The numbers the environment gives for each outcome; they define *what* the agent optimises.
- ↑ If you increase it
- A larger step penalty pushes for shorter paths but can make the agent prefer jumping into a pit to end a long, costly episode.
- ↓ If you decrease it
- With no shaping, rewards are sparse and learning is slow; the agent may wander aimlessly.
- Typical values
- Goal +1, pit −1, small step cost (−0.01 to −0.04).
In code: Q-learning with Gymnasium
import gymnasium as gym
import numpy as np
env = gym.make("FrozenLake-v1", map_name="4x4", is_slippery=False)
Q = np.zeros((env.observation_space.n, env.action_space.n))
alpha, gamma = 0.1, 0.99
eps, eps_min, eps_decay = 1.0, 0.05, 0.995
rng = np.random.default_rng(0)
for episode in range(2000):
s, _ = env.reset(seed=episode)
done = False
while not done:
if rng.random() < eps: # explore
a = env.action_space.sample()
else: # exploit
a = int(np.argmax(Q[s]))
s2, r, terminated, truncated, _ = env.step(a)
target = r + gamma * np.max(Q[s2]) * (not terminated)
Q[s, a] += alpha * (target - Q[s, a]) # TD update
s, done = s2, terminated or truncated
eps = max(eps_min, eps * eps_decay)
print("Greedy policy (0=L,1=D,2=R,3=U):")
print(np.argmax(Q, axis=1).reshape(4, 4))▸Go deeper: SARSA vs Q-learning, and dynamic programming
SARSA is the on-policy sibling of Q-learning: its target uses the action a′ the agent will *actually* take next, r + γ·Q(s′, a′), instead of the max. In Sutton & Barto's “cliff walking” example[1], Q-learning learns the optimal path right along the cliff edge but falls off often during ε-greedy training; SARSA learns a safer path one row away because it accounts for its own exploration.
When P and R are known, you do not need trial and error at all: value iteration repeatedly applies the Bellman optimality update to every state until convergence, and policy iteration alternates policy evaluation and greedy improvement. Q-learning can be seen as a sampled, model-free version of value iteration.
Quiz
References
- [1]Reinforcement Learning: An Introduction (2nd ed.)BookSutton & Barto2018incompleteideas.netChapters 3 (MDPs) and 6 (TD learning, Q-learning, SARSA, cliff walking).
- [2]
- [3]Gymnasium documentationDocsFarama Foundationgymnasium.farama.org
- [4]Spinning Up in Deep RL — Part 1: Key Concepts in RLCourseOpenAI (Achiam)spinningup.openai.com