AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
↻Reinforcement Learning
  1. Reinforcement Learning Basics: Agents, Rewards and Q-learning
  2. Deep Reinforcement Learning: DQN, Policy Gradients and PPO
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Reinforcement Learning

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.

Intermediate~26 min·4 references
Key terms
Reinforcement learning (RL)Markov decision process (MDP)RewardPolicyValue functionQ-learningε-greedyDiscount factor (γ)Exploration–exploitation trade-off

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.

≈
Analogy: a new ojek driver learning the city
A new ojek driver does not get a map with “correct” routes. Each trip they choose turns (actions) at intersections (states); at the end they see how long it took and how much they earned (reward). Some shortcuts look bad at first but pay off later — and a driver who *only* uses the first route that worked will never find the faster one. Over weeks they build an intuition of “how good is it to be at this intersection heading this way” — that intuition is a value function.

The agent–environment loop

  1. The agent observes the current state sₜ (e.g. its position on a grid).
  2. It chooses an action aₜ according to its Policy π.
  3. The environment returns a reward rₜ₊₁ and the next state sₜ₊₁.
  4. Repeat until a terminal state (goal, pit, game over) ends the episode, or forever in continuing tasks.
Loading interactive…
The agent–environment loop with a tabular learner inside the agent. Press Walk through to follow one time step, or tap a block (e.g. Learning update) for details. Notice that the agent never sees P or R directly — only the action it sends out and the state and reward that come back.

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ₜ = rₜ₊₁ + γ·rₜ₊₂ + γ²·rₜ₊₃ + … = Σₖ γᵏ · rₜ₊ₖ₊₁
The discounted return the agent tries to maximise.
In words: “the return from time t = the next reward, plus the reward after that shrunk by γ, plus the one after that shrunk by γ², and so on”. Rewards further in the future count less, so the agent prefers getting good things sooner.
Symbols(hover a symbol in the formula)
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
Gridworld: rewards −0.04, −0.04, +1 (goal on the 3rd step), γ = 0.9 Gₜ = −0.04 + 0.9 · (−0.04) + 0.9² · 1 = −0.04 − 0.036 + 0.81 = 0.734 Same rewards with γ = 0.5: Gₜ = −0.04 − 0.02 + 0.25 = 0.19 → the far-away goal matters much less.

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) = E[ r + γ · maxₐ′ Q*(s′, a′) | s, a ]
Bellman optimality equation for action values.
In words: “the best achievable value of doing a in s = the reward you get now plus the discounted value of acting optimally from wherever you land, averaged over where you might land”. It defines Q* recursively in terms of itself.
Symbols(hover a symbol in the formula)
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
In s, action a costs r = −0.04 and slips: 80% → s′₁ with maxₐ′ Q* = 0.8, 20% → s′₂ with maxₐ′ Q* = 0.2. γ = 0.9 E[max Q*(s′, ·)] = 0.8 · 0.8 + 0.2 · 0.2 = 0.68 Q*(s, a) = −0.04 + 0.9 · 0.68 = −0.04 + 0.612 = 0.572

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) ← Q(s, a) + α · [ r + γ · maxₐ′ Q(s′, a′) − Q(s, a) ]
The bracket is the TD error. For terminal s′, the target is just r.
In words: “new estimate = old estimate + a fraction α of the surprise”. The surprise (TD error) is the target r + γ·max Q(s′, ·) minus what you predicted. Repeated over many steps, the table converges to Q*.
Symbols(hover a symbol in the formula)
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
Q(s, a) = 0.2, r = 0, maxₐ′ Q(s′, a′) = 0.6, γ = 0.9, α = 0.5 target = 0 + 0.9 · 0.6 = 0.54 TD error = 0.54 − 0.2 = 0.34 Q(s, a) ← 0.2 + 0.5 · 0.34 = 0.37

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.

Loading interactive…
Real tabular Q-learning on an editable gridworld. The heatmap shows maxₐ Q(s, a) per cell and the arrows show the current greedy policy.
  • 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

knobα (learning rate)
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.
knobγ (discount factor)
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).
knobε (exploration rate)
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.
knobnumber of episodes
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.
knobreward design (step cost, goal/pit values)
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

python
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))
Gymnasium's step() returns terminated (real end) and truncated (time limit) separately — only bootstrap from s′ if the episode did not terminate[3].
!
Common pitfalls
Reward hacking: the agent optimises the reward you wrote, not the one you meant — e.g. circling to farm a bonus instead of finishing the race. Never-explored states: a greedy agent with ε = 0 and zero-initialised Q can loop forever. Treating time-limit truncation as a terminal state makes the agent think time running out is a real outcome. Tables do not scale: FrozenLake has 16 states, chess ~10⁴⁴; beyond toy problems you need function approximation (deep RL, next lesson). Single-seed conclusions: RL results vary a lot between random seeds — compare averages over several runs.
▸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

1.
With γ = 0.9, what weight does the reward rₜ₊₄ get in the return Gₜ?
2.
Q(s, a) = 2, α = 0.5, γ = 0.9, the agent receives r = 1 and maxₐ′ Q(s′, a′) = 4. What is the new Q(s, a)?
3.
You train a tabular agent with ε = 0 from a zero-initialised Q table. What is the most likely result?
4.
Why is Q-learning called off-policy?
5.
You lower γ from 0.99 to 0.5 in a large gridworld with a single distant goal. What happens?
Score: 0/5

References

  1. [1]
    Reinforcement Learning: An Introduction (2nd ed.)
    BookSutton & Barto2018incompleteideas.net
    Chapters 3 (MDPs) and 6 (TD learning, Q-learning, SARSA, cliff walking).
  2. [2]
    Q-learning
    PaperWatkins & Dayan1992doi.org
    Machine Learning 8, convergence proof.
  3. [3]
    Gymnasium documentation
    DocsFarama Foundationgymnasium.farama.org
  4. [4]
    Spinning Up in Deep RL — Part 1: Key Concepts in RL
    CourseOpenAI (Achiam)spinningup.openai.com
← Previous
3D: NeRF, Gaussian Splatting and Text-to-3D
Next →
Deep Reinforcement Learning: DQN, Policy Gradients and PPO