Velamuvi AIAcademy

Lesson 1 of 12 · Foundations

Agents, Environments and Rewards

The reinforcement learning loop explained: agents, environments, states, actions, rewards, episodes, returns and discounting, with a Python corridor world.

  • 16 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Describe the reinforcement learning loop: agent, environment, state, action and reward
  • Explain how reinforcement learning differs from supervised and unsupervised learning
  • Build a tiny environment in plain Python and run episodes in it
  • Judge a policy by its average return over many episodes
  • Calculate a discounted return and explain what the discount factor γ does

The idea in plain words

Think about how you learned to ride a bike. Nobody handed you a table of correct handlebar angles. You tried something, wobbled, fell off, tried again, and slowly did more of whatever kept you upright. Reinforcement learning (RL) is this kind of learning for computers: a program acts, sees what happens, receives a score, and changes its behaviour so that it scores more in the future.

You met the idea in Types of Machine Learning, where a learner tried two options and drifted towards the one that paid off more often. This course grows that idea into the methods behind game-playing programs, robot controllers and the fine-tuning of chat assistants. This first lesson sets up the vocabulary that every later lesson uses, and a tiny world to try it in.

The reinforcement learning loop

Every RL problem has two parts. The agent is the learner: the part that decides what to do. The environment is everything else: the world the agent acts in, which reacts to its actions. They take turns, over and over:

               action aₜ
      ┌─────────────────────────────┐
      │                             ▼
  ┌───────┐                  ┌─────────────┐
  │ Agent │                  │ Environment │
  └───────┘                  └─────────────┘
      ▲                             │
      └─────────────────────────────┘
       next state sₜ₊₁ and reward rₜ₊₁
  1. At time step t, the agent observes the state sₜ: a description of the current situation.
  2. It chooses an action aₜ.
  3. The environment moves to a new state sₜ₊₁ and hands back a reward rₜ₊₁: a single number saying how good that step was.
  4. The loop repeats from the new state.

Many tasks have a natural end: a game is won or lost, a robot reaches the door. One run from the start to such an end is an episode. The rewards collected during an episode add up to the return, and the return is what the agent tries to make as large as possible. That's an important difference: a good agent doesn't grab the biggest reward in sight; it chooses actions that lead to the biggest total.

How RL differs from supervised and unsupervised learning

SupervisedUnsupervisedReinforcement
The dataA fixed set of inputs with correct answersA fixed set of inputs, no answersCreated by the agent's own actions, as it goes
The feedback"The right answer was B"None"That was worth 3 points"
When it arrivesWith every example-Often many steps after the action that earned it
The goalPredict answers for new inputsFind structureChoose actions that maximise the return

Three differences make RL hard, and each one returns later in this course:

  • Rewards grade, they don't teach. A label tells a classifier the correct answer. A reward only says how good the chosen action turned out; it never says what the best action would have been. The agent has to find that out by trying alternatives.
  • Rewards are often delayed. A chess program learns whether it won only at the end of the game. Which of its 40 moves deserve the credit? This is the credit assignment problem.
  • The agent's actions decide its data. A supervised model learns from whatever dataset you give it. An agent that never tries an action never learns what it does, so it must balance trying new things against using what it knows: Exploration vs Exploitation is about exactly that.

A tiny environment in plain Python

Real environments can be video games or physics simulators, but the loop is the same for a world small enough to see at a glance. Here is a corridor of 7 cells. A coin worth 1 point lies in cell 0, a treasure worth 10 points lies in cell 6, and the agent starts in cell 2. Each step, it moves one cell left or right, and the episode ends when it reaches either end.

 cell:   0     1     2     3     4     5     6
       [ C ] [   ] [ A ] [   ] [   ] [   ] [ T ]
       coin        start                 treasure
        +1                                 +10

The environment is just a function: it takes the current state (the cell number) and an action, and returns the next state, the reward and whether the episode is over. The agent below uses a random policy, flipping a coin to choose each move:

Try it yourselfPython
import numpy as np

# The environment: a corridor of 7 cells, numbered 0 to 6.
# A coin (+1) waits in cell 0 and a treasure (+10) in cell 6. The agent starts in cell 2.
START = 2

def step(state, action):
    """Move left (action 0) or right (action 1). Returns next_state, reward, done."""
    next_state = state + 1 if action == 1 else state - 1
    if next_state == 0:
        return next_state, 1, True      # found the coin: the episode is over
    if next_state == 6:
        return next_state, 10, True     # found the treasure: the episode is over
    return next_state, 0, False         # an empty cell: no reward yet

# The agent: a random policy, left or right with equal chance
rng = np.random.RandomState(0)
state, done, total, t = START, False, 0, 0
while not done:
    action = rng.randint(2)
    next_state, reward, done = step(state, action)
    print(f"t={t}: in cell {state}, goes {['left ', 'right'][action]} -> cell {next_state}, reward {reward}")
    total += reward
    state, t = next_state, t + 1
print("Episode over after", t, "steps. Total reward:", total)
Output
t=0: in cell 2, goes left  -> cell 1, reward 0
t=1: in cell 1, goes right -> cell 2, reward 0
t=2: in cell 2, goes right -> cell 3, reward 0
t=3: in cell 3, goes left  -> cell 2, reward 0
t=4: in cell 2, goes right -> cell 3, reward 0
t=5: in cell 3, goes right -> cell 4, reward 0
t=6: in cell 4, goes right -> cell 5, reward 0
t=7: in cell 5, goes right -> cell 6, reward 10
Episode over after 8 steps. Total reward: 10

Every line is one turn of the loop: a state, an action, a new state and a reward. Seven of the eight rewards were 0, and the only feedback came at the very end. That's typical of RL, and it's the credit assignment problem in miniature: the last step earned the 10, but the steps to the right before it deserve some of the credit. Change the seed to 3 and the agent stumbles into the coin after just 2 steps.

A random policy and its total reward

One episode tells you little, because a random agent might be lucky. To judge a policy, run many episodes and average their returns. The program below compares the random policy with two fixed ones over 2,000 episodes each:

Try it yourselfPython
import numpy as np

START = 2

def step(state, action):
    next_state = state + 1 if action == 1 else state - 1
    if next_state == 0:
        return next_state, 1, True       # coin
    if next_state == 6:
        return next_state, 10, True      # treasure
    return next_state, 0, False

def run_episode(policy, rng):
    """Play one episode. Returns the total reward and the number of steps."""
    state, done, total, steps = START, False, 0, 0
    while not done:
        state, reward, done = step(state, policy(state, rng))
        total, steps = total + reward, steps + 1
    return total, steps

policies = {
    "random":       lambda state, rng: rng.randint(2),
    "always left":  lambda state, rng: 0,
    "always right": lambda state, rng: 1,
}
rng = np.random.RandomState(0)
for name, policy in policies.items():
    results = np.array([run_episode(policy, rng) for _ in range(2000)])
    totals, steps = results[:, 0], results[:, 1]
    print(f"{name:<12}  average total reward {totals.mean():5.2f}   "
          f"treasure in {np.mean(totals == 10):4.0%} of episodes   average length {steps.mean():4.1f} steps")
Output
random        average total reward  4.16   treasure in  35% of episodes   average length  7.9 steps
always left   average total reward  1.00   treasure in   0% of episodes   average length  2.0 steps
always right  average total reward 10.00   treasure in 100% of episodes   average length  4.0 steps

The average of many returns estimates the policy's expected return, the long-run average from Expected Value. For the random policy the exact answer is 4: a random walk that starts 2 cells from one end and 4 from the other reaches the far end first with probability 2/6 = 1/3, so the expected return is 1/3 × 10 + 2/3 × 1 = 4. The simulation's 4.16 and 35% are close to that. "Always right" is clearly the best of the three, and finding a policy like it without being told is what the rest of this course is about.

Discounting: sooner is better than later

So far, a reward counted the same whether it arrived at step 1 or step 100. Most RL methods instead discount future rewards, multiplying each one by a factor γ (the Greek letter gamma, between 0 and 1) for every step of delay:

return G = r₁ + γ·r₂ + γ²·r₃ + γ³·r₄ + …

γ = 1      every reward counts in full, however late it comes
γ = 0.9    a reward one step later is worth 0.9 as much, two steps later 0.81, ten steps later 0.35
γ = 0      only the very next reward counts

There are good reasons for it. A reward now is more certain than a reward later, in the same way that money today is worth more than the same amount next year. Discounting makes the agent prefer quicker routes to the same reward. And, as the next lesson shows, it keeps the return finite in tasks that never end. Drag the slider to see what a treasure of 10 is worth today if it arrives k steps from now:

value today = 10 × 0.9^k
051015200246810
value today
With γ = 0.9 the treasure keeps about a third of its value after 10 steps. With γ = 0.5 it is worth almost nothing after 5.

γ changes which policy is best. In the corridor, going left reaches the coin after 2 steps and going right reaches the treasure after 4:

Try it yourselfPython
def discounted_return(rewards, gamma):
    """r1 + gamma * r2 + gamma**2 * r3 + ..."""
    return sum(gamma ** k * r for k, r in enumerate(rewards))

left = [0, 1]             # always left: one empty cell, then the coin
right = [0, 0, 0, 10]     # always right: three empty cells, then the treasure

print("gamma   always left   always right   prefers")
for gamma in [1.0, 0.9, 0.5, 0.3, 0.1]:
    g_left, g_right = discounted_return(left, gamma), discounted_return(right, gamma)
    print(f"{gamma:5.1f} {g_left:13.2f} {g_right:14.2f}   {'right' if g_right > g_left else 'left'}")
Output
gamma   always left   always right   prefers
  1.0          1.00          10.00   right
  0.9          0.90           7.29   right
  0.5          0.50           1.25   right
  0.3          0.30           0.27   left
  0.1          0.10           0.01   left

With γ = 0.9, the treasure 4 steps away is still worth 10 × 0.9³ = 7.29 today, far more than the coin. Below γ ≈ 0.32, the agent becomes so short-sighted that the small, quick coin wins. A useful rule of thumb: an agent with discount factor γ looks about 1 ÷ (1 − γ) steps ahead, so about 10 steps for γ = 0.9 and 100 steps for γ = 0.99. Choose γ so that this horizon covers the delays that matter in your task.

The same loop in a real library

Researchers test agents on standard environments from libraries such as Gymnasium. Its step returns the same three things as our corridor, plus two extras: truncated, which is True when an episode is cut off by a time limit rather than ending naturally, and info, a dictionary of extra details. This example needs a local install (pip install gymnasium); it doesn't run in the browser:

import gymnasium as gym

env = gym.make("FrozenLake-v1", is_slippery=False)   # a small grid world
state, info = env.reset(seed=0)
total, done = 0, False
while not done:
    action = env.action_space.sample()                # a random policy
    state, reward, terminated, truncated, info = env.step(action)
    total += reward
    done = terminated or truncated                    # a real end, or the time limit
print("total reward:", total)

This course builds its environments from scratch in NumPy instead, so that you can see every moving part and run everything in the browser.

Common mistakes

Practice

Practice exercise

Write discounted_return(rewards, gamma), which adds up a list of rewards with each reward discounted by how late it arrives. Then print the discounted return, with γ = 0.9, of four episodes: the three corridor routes (the zigzag steps back once before heading for the treasure) and an imaginary episode that earns 1 point at each of five steps.

Your solutionPython
def discounted_return(rewards, gamma):
    # Return r1 + gamma * r2 + gamma**2 * r3 + ... for the list of rewards
    return 0.0

episodes = {
    "always left": [0, 1],
    "always right": [0, 0, 0, 10],
    "zigzag": [0, 0, 0, 0, 0, 10],
    "coin chain": [1, 1, 1, 1, 1],
}
for name, rewards in episodes.items():
    print(f"{name}: {discounted_return(rewards, 0.9):.2f}")
Knowledge check

A classifier learns from labels. What does a reinforcement learning agent get instead?

Summary

  • In RL, an agent repeatedly observes a state, takes an action, and receives a reward and a new state from the environment. Its policy is its rule for choosing actions.
  • Unlike supervised learning, rewards grade rather than teach, often arrive late, and depend on the data the agent's own actions produce.
  • An episode runs from the start to an end, and the return is its total reward. Judge a policy by its average return over many episodes.
  • Discounting with γ between 0 and 1 makes later rewards count less: G = r₁ + γ·r₂ + γ²·r₃ + …, with a horizon of about 1 ÷ (1 − γ) steps.

Next: Markov Decision Processes.

Finished reading? Tick it off to track your progress.