Learning outcomes

After this lesson, you will be able to:

Core idea. RL trains an agent through the consequences of its actions. The environment returns a reward and a new state, and the agent gradually improves its behaviour strategy.

1. How RL differs from other learning settings

In supervised learning, each training example has a known target. In unsupervised learning, predefined labels are absent and an algorithm searches for structure. In reinforcement learning (RL), an agent interacts with an environment: it selects an action and receives a new state and reward.

The key feature is a sequence of decisions. An action affects not only the immediate reward but also future states and available choices. Long-term outcomes therefore matter.

Agent–environment loopThe agent receives a state and sends an action to the environment. The environment returns a new state and reward.AgentSelects an actionEnvironmentChanges stateAction aₜ →← New state sₜ₊₁ and reward rₜ₊₁Observation → action → consequence → new observation
The interaction loop: the agent selects an action and the environment returns a result. Sometimes the agent receives only an observation, not the full state.

Examples include a robot learning to move, a game agent choosing moves, or a controller learning in simulation to maintain comfortable temperature while limiting energy use.

2. Elements of an RL task

ElementMeaningBuilding example
AgentMakes decisions.Virtual heating controller.
EnvironmentSystem in which decisions take effect.Building, weather, and thermal-inertia model.
State sDescription of the situation.Temperature, time, weather forecast.
Action aAgent’s choice.Increase, decrease, or hold power.
Reward rNumeric feedback about the outcome.Balance of comfort, cost, and constraints.
TransitionRule for state change.Temperature changes with weather and inertia.

A common formalism is a Markov Decision Process (MDP): states S, actions A, reward function R, transition probabilities P, and an initial-state distribution. An episode is a bounded sequence of interactions ending at a terminal condition.

Sequence of states and rewardsThe line shows the direction of time. Filled circles distinguish the current state, action, next state, and a later state; labels sit above the circles and symbols are centered inside them.CurrentActionNext stateLatersₜaₜsₜ₊₁sₜ₊₂Reward is assessed after the action; some consequences appear later.
Evaluation must account for future consequences, not only the immediate reward.

3. Reward, return, and discounting

A reward is a numeric signal returned after an action or transition. It can be positive, zero, or negative. The sum of rewards over a sequence is called the return.

Discounted returnGₜ = rₜ₊₁ + γrₜ₊₂ + γ²rₜ₊₃ + …

The discount factor γ between 0 and 1 sets the relative weight of future rewards. A smaller γ emphasises near-term outcomes; a value closer to 1 gives more weight to distant results.

A reward is not the same as a human goal. If a system is rewarded only for saving energy, it may do so by reducing comfort unacceptably. Safety constraints, permitted ranges, and emergency modes must be defined separately.

4. Policy, value, exploration, and exploitation

Exploration tests actions whose outcomes are not yet well known. Exploitation chooses the action currently estimated to be best. Only exploring wastes experience; exploiting too early can prevent discovery of a better strategy.

Exploration and exploitationExploration tests alternatives; exploitation selects the currently best-known option.ExplorationTry alternativesExploitationChoose the known best optionBalance depends on learning stage and risk
Exploration and exploitation are two aspects of a strategy that must be balanced.

5. Main algorithm families

These categories are not mutually exclusive: deep RL can be value-based, policy-based, or actor–critic. Selection depends on action type, interaction cost, model availability, and stability requirements.

6. Task formulation: a building in simulation

Imagine an agent controlling heating only in a safe simulation. Its state includes indoor and outdoor temperature, time of day, and weather forecast. Actions slightly increase power, decrease it, or hold it. A reward can account for comfort deviation and energy use.

Formulate the task before choosing an algorithm. Define observations, allowed actions, reward, episode termination, and constraints that must never be violated. Do not use a real asset for unsafe exploration.

7. Practice: minimal Q-learning in Python

This one-dimensional toy environment has five states. The agent starts at position 0 and must reach position 4. Actions move left or right. Reaching the goal gives +1; each intermediate step costs −0.02. No external libraries are needed; Python 3.10+ is required.

import random

random.seed(7)
N_STATES = 5
ACTIONS = (-1, 1)  # left, right
Q = [[0.0, 0.0] for _ in range(N_STATES)]
alpha, gamma, epsilon = 0.2, 0.95, 0.2

def step(state, action):
    next_state = max(0, min(N_STATES - 1, state + action))
    done = next_state == N_STATES - 1
    reward = 1.0 if done else -0.02
    return next_state, reward, done

for episode in range(400):
    state = 0
    for _ in range(10):
        if random.random() < epsilon:
            action_index = random.randrange(len(ACTIONS))
        else:
            action_index = max(range(2), key=lambda i: Q[state][i])
        action = ACTIONS[action_index]
        next_state, reward, done = step(state, action)
        best_next = 0.0 if done else max(Q[next_state])
        target = reward + gamma * best_next
        Q[state][action_index] += alpha * (target - Q[state][action_index])
        state = next_state
        if done:
            break

state, path = 0, [0]
for _ in range(10):
    action_index = max(range(2), key=lambda i: Q[state][i])
    state, _, done = step(state, ACTIONS[action_index])
    path.append(state)
    if done:
        break
print(" -> ".join(map(str, path)))

How the code works

Expected output: 0 -> 1 -> 2 -> 3 -> 4. This illustrates Q-learning mechanics, not suitability for real equipment.

8. Limitations and common mistakes

RL does not guarantee safe or optimal control. Testing, independent constraints, monitoring, and the ability to stop or override actions are required.

9. Key takeaways

Independent task

Describe an RL task for a teaching building simulation: list three observations, allowed actions, an example reward, an episode-ending condition, and two hard safety constraints. Explain what undesirable behaviour could occur if the reward only accounts for energy use.