1. Home
  2. Explore
  3. Computer Science
  4. Reinforcement Learning Overview

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Reinforcement Learning Overview

Reinforcement Learning: The Third Paradigm of Machine Learning

Introduction to Machine Learning Paradigms

Machine learning is broadly divided into three paradigms:

  • Supervised learning: Learning from labeled data — classification and regression using algorithms like KNN, Naïve Bayes, and neural networks.

  • Unsupervised learning: Finding natural groupings in unlabeled data — clustering algorithms like K-Means.

  • Reinforcement learning (RL): Learning through sparse reward signals that may occur sporadically, inspired by operant conditioning in psychology.

Key idea: In RL, sequences of actions leading to good results are reinforced to occur more frequently, while sequences leading to bad results are discouraged. The agent learns the best sequence of actions that maximizes cumulative reward.

RL differs from supervised learning because there are no correct labels per step — the agent must discover good behavior by trial and error.

The Grid World Environment

A classic RL toy problem is a 4×4 grid where an agent (e.g., a robot named Wally) navigates toward a goal while avoiding a trap.

Environment Properties

The environment is characterized by several key properties:

  • Episodic: The problem has a clear beginning and end. Each round of execution is called an episode. When the agent reaches a terminal state (reward or punishment), the episode ends and the agent resets to the start.

  • Discrete: There are 16 possible states (each square is a state). States are finite and countable.

  • Fully observable: The agent knows exactly which state it is in — no hidden information.

  • Deterministic (initially): Every action has a guaranteed outcome. Moving up from a square always goes to the square above (or stays if at a wall). No randomness in transitions.

Goal and Rewards

  • The agent starts in the lower-left corner.

  • The goal is the upper-right corner: the agent receives +100 reward and the episode ends.

  • A trap exists one row below the goal: stepping there yields -100 punishment and the episode ends.

  • All other squares give 0 reward for entering.

The Q-Learning Algorithm

Q-Learning is a model-free RL algorithm that learns the value of taking a given action in a given state.

Q-Values (Quality Values)

For each state, the agent stores a Q-value for each possible action (up, down, left, right). Initially all Q-values are set to 0. The Q-value represents the expected total reward the agent will accumulate from that state onward if it chooses that action and then follows the optimal policy.

Important distinction: Q-values are expectations of cumulative future reward, not immediate rewards. The +100 and −100 are immediate rewards, not expectations.

Imagine a table with 16 rows (states) and 4 columns (actions), initially all zeros.

Learning Process Step by Step

  1. The agent starts in the initial state.

  2. In each state, it selects the action with the highest Q-value. If multiple actions are tied, it randomly chooses among them to avoid getting stuck.

  3. It executes the action, observes the resulting state and the reward.

  4. It updates the Q-value of the previous state-action pair using the observed reward (or the next state's maximum Q-value).

Updating with immediate rewards: When the agent reaches a terminal state (reward or punishment), it copies that reward value into the Q-value of the action that led there. For example, if the agent moves up from a square into the trap (−100), the Q-value for "up" in that square becomes −100. Now the agent knows to avoid that action.

Backpropagation of values: When the agent reaches a non-terminal state with an existing learned Q-value, the maximum Q-value from the next state is used to update the previous state. Effectively, the value propagates backward from the goal. For instance, if the square before the goal has a Q-value of 100 for "right", the square before that will learn that moving right leads to that 100, and so on. This builds a path from the start to the goal.

Policy

A policy is a function that maps each state to the action the agent should take. In Q-learning, the policy is to choose the action with the highest Q-value in each state. The learned policy can be visualized as arrows on the grid showing the optimal direction from each cell.


Challenges and Solutions in Q-Learning

Challenge 1: Discovering Better Paths (Exploration vs. Exploitation)

Problem: Once the agent learns one path to the reward, it always chooses the action with the highest Q-value. This means it may never discover a shorter or equally good path that exists elsewhere on the map. This is the exploration vs. exploitation dilemma.

Solution: Epsilon-Greedy Exploration

  • Exploitation: Always pick the best action (maximizing immediate reward based on current knowledge).

  • Exploration: Occasionally pick a random action to discover new states and rewards.

The algorithm uses a parameter ϵ\epsilonϵ (e.g., 0.1 = 10% chance). At each step:

  • With probability ϵ\epsilonϵ, choose a random action.

  • With probability 1−ϵ1 - \epsilon1−ϵ, choose the best action.

This ensures the agent continues to explore even after learning a good path. In the grid world, the agent will sometimes go right instead of up, eventually discovering the second reward in the lower-right corner.

Challenge 2: Distant Rewards (Temporal Discounting)

Problem: Without discounting, all paths to the reward seem equally valuable. Q-values become 100 everywhere (except traps). The agent cannot distinguish between a direct, short path and a long, winding one.

Solution: Discount Factor γ\gammaγ

Key insight: Future rewards are worth less than immediate rewards. The discount factor γ∈[0,1]\gamma \in [0,1]γ∈[0,1] reduces the value of rewards that are farther away.

When updating the Q-value of a previous state, multiply the next state's maximum Q-value by γ\gammaγ before adding it to the reward. A common value is γ=0.9\gamma = 0.9γ=0.9.

With discounting, the Q-values along the shortest path remain higher than those along longer paths. For example, the state immediately before the goal gets 100×0.9=90100 \times 0.9 = 90100×0.9=90, the next state gets 90×0.9=8190 \times 0.9 = 8190×0.9=81, and so on. The agent now prefers actions that lead to the reward faster.

Challenge 3: Non-Deterministic Environments (Stochasticity)

Problem: Real-world environments are often non-deterministic — an action might not always have the same outcome. For example, the agent might "trip" and slide to a neighboring square. If a good action accidentally leads to a trap (due to randomness), the Q-value might incorrectly become negative.

Solution: Learning Rate α\alphaα

The learning rate α∈(0,1]\alpha \in (0,1]α∈(0,1] controls how quickly the Q-value adapts to new information. Instead of overwriting the old Q-value with the new target (which could be noisy), we move the old value toward the target gradually.

The update formula becomes:

Q(s,a)←Q(s,a)+α[r+γ⋅max⁡a′Q(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha \left[ r + \gamma \cdot \max_{a'} Q(s', a') - Q(s, a) \right]Q(s,a)←Q(s,a)+α[r+γ⋅maxa′​Q(s′,a′)−Q(s,a)]

where:

  • Q(s,a)Q(s, a)Q(s,a) is the current Q-value for state sss and action aaa

  • α\alphaα is the learning rate

  • rrr is the immediate reward received

  • γ\gammaγ is the discount factor

  • max⁡a′Q(s′,a′)\max_{a'} Q(s', a')maxa′​Q(s′,a′) is the maximum Q-value in the resulting state s′s's′

Example: An action that usually leads to +100 but sometimes to −100 will gradually settle at an intermediate value (e.g., 60 with α=0.2\alpha=0.2α=0.2) that reflects the expected outcome. This prevents catastrophic unlearning.

The Complete Q-Learning Update Formula

The general formula for updating Q-values:

Qt+1(s,a)=Qt(s,a)+α[rt+γ⋅max⁡a′Qt(s′,a′)−Qt(s,a)]Q_{t+1}(s, a) = Q_t(s, a) + \alpha \left[ r_t + \gamma \cdot \max_{a'} Q_t(s', a') - Q_t(s, a) \right]Qt+1​(s,a)=Qt​(s,a)+α[rt​+γ⋅maxa′​Qt​(s′,a′)−Qt​(s,a)]
  • ttt is the current time step (before the action)

  • t+1t+1t+1 is the next time step (after the action)

  • sss is current state, aaa is action taken

  • rtr_trt​ is reward received for taking action aaa in state sss

  • s′s's′ is the resulting state

  • max⁡a′Qt(s′,a′)\max_{a'} Q_t(s', a')maxa′​Qt​(s′,a′) is the expected future reward from s′s's′ under the optimal policy

This formula is simple arithmetic but uses Greek letters for parameters, which are constants set by the programmer.

Implementation Considerations

Terminal States

When the agent reaches a terminal state (e.g., +100 or −100), there is no future. The Q-value of that state for any action is implicitly 0. Therefore, the update for the preceding state-action pair should not include the future expectation term. The formula becomes:

Q(s,a)←Q(s,a)+α[r−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha \left[ r - Q(s, a) \right]Q(s,a)←Q(s,a)+α[r−Q(s,a)]

This prevents the agent from thinking there is additional reward after the episode ends (the "afterlife" problem).

Optimistic Initialization

Instead of initializing all Q-values to 0, they can be set to a high positive value (e.g., 100). This encourages exploration because the agent will try actions it hasn't taken, expecting high reward. As it experiences the actual outcomes, Q-values decrease to realistic levels. Optimistic initialization can serve as a built-in exploration mechanism, potentially reducing the need for epsilon-greedy.

Code Structure (Python with Classes)

The implementation separates the environment (the grid world) from the agent (Q-learning). Key components:

  • Environment class (mapinha):

    • __init__: sets width, height, stumble probability

    • reset: returns agent to start (lower-left corner)

    • act: applies an action (up, right, down, left) with possible stumbling, returns new state, reward, and whether it's terminal

    • Walls: actions cannot move outside the grid

  • Agent class (QLearn):

    • __init__: stores parameters (ϵ\epsilonϵ, α\alphaα, γ\gammaγ, initial Q-value, map size)

    • reset: initializes Q-table (3D array: rows × columns × actions)

    • get_max_q: returns the highest Q-value for a given state

    • get_best_action: returns the action with the highest Q-value; if ties, randomly chooses among them

    • get_action: implements epsilon-greedy (random action with probability ϵ\epsilonϵ, else best action)

    • update: applies the Q-learning update formula

Pseudocode

Initialize Q(s,a) arbitrarily (e.g., 0)
For each episode:
    s = initial state
    For each step of episode (until terminal or max steps):
        Choose a from s using epsilon-greedy policy
        Take action a, observe r and s'
        Update Q(s,a) using formula
        s = s'
        if s is terminal: break

Handling Ties

When multiple actions have the same Q-value (e.g., all zeros initially), the agent must randomly pick one to avoid getting stuck repeating the same action (e.g., always going left into a wall).

Episode Step Limit

To prevent infinite loops (e.g., when the agent is stuck), limit the number of steps per episode, e.g., to the number of states in the grid.

Advanced Topics and Extensions

  • Exploration beyond epsilon-greedy: More sophisticated methods exist for handling large state spaces (e.g., intrinsic motivation, count-based exploration).

  • Deep Reinforcement Learning: Combines deep neural networks with Q-learning to handle continuous state spaces (e.g., images) — a hot research area.

  • Other RL algorithms: SARSA (on-policy), Monte Carlo methods, and policy gradients.

  • Performance monitoring: Plotting cumulative reward per episode to see learning progress over time.

  • Generalization: Implement the environment more flexibly (e.g., arbitrary reward/trap placements, larger maps, different termination conditions).


Summary of Key Concepts

  • Reinforcement learning = learning from sparse rewards via trial and error.

  • Q-learning = model-free algorithm that learns Q-values (expected future reward) for each state-action pair.

  • Policy = mapping from states to optimal actions (the agent's learned behavior).

  • ϵ\epsilonϵ-greedy = simple exploration strategy: with probability ϵ\epsilonϵ, take a random action.

  • Discount factor γ\gammaγ = how much future rewards are worth relative to immediate ones (closer to 1 = more farsighted).

  • Learning rate α\alphaα = how quickly Q-values adapt to new information (helps smooth out noise in stochastic environments).

  • Optimistic initialization = starting Q-values high to encourage exploration naturally.

  • Terminal states have no future expectation; their Q-values are effectively 0 for updates.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent