Skip to main content
LearnMLAcademy
Beginner10 min read

Reinforcement Learning

Understand reinforcement learning agents, reward signals, and Q-learning, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Reinforcement Learning in Simple Words

Reinforcement Learning (RL) means learning by trying actions and seeing what happens. There is no answer sheet telling the learner the correct move every time. Instead, the learner receives a reward when an action is useful and a penalty or smaller reward when an action is poor. Over many attempts, it learns which actions usually lead to better results.

The basic idea

1. Try an Action

Choose what to do next.

2. Receive Feedback

Get a reward or penalty.

3. Improve the Next Choice

Remember what worked better.

Try → Feedback → Learn → Try again

A Simple Example: A Robot Finding the Exit

Imagine a small robot inside a simple maze. It can move left, right, forward, or backward. It does not initially know the correct path to the exit.

What the robot doesFeedbackWhat it learns
Hits a wall−2 pointsAvoid this move in this situation
Moves closer to the exit+1 pointThis direction may be useful
Reaches the exit+10 pointsRemember this successful route

After many attempts, the robot does not simply memorize one move. It learns a strategy for choosing useful moves in different situations. That strategy is called a policy.

Technical Definition

Reinforcement learning is a behavioral machine learning model where an algorithm learns to make decisions by performing actions in an environment to maximize a cumulative reward. The system learns through repeated interaction and trial and error, modifying its behavior based on the rewards (positive feedback) or penalties (negative feedback) it receives over time.

How Reinforcement Learning Works

Imagine training a puppy. When the puppy successfully performs a trick (like "Sit"), you give it a treat (Positive Reward). When it misbehaves, you withhold the treat or scold it (Negative Reward). The puppy doesn't speak your language, but over time, it mathematically optimizes its behavior to figure out which specific actions lead to the highest amount of treats.

Reinforcement Learning uses this exact same concept but applies it to software algorithms navigating complex digital or physical spaces.

The Five Key Concepts

  • Agent: The AI program or entity that is actually learning and making decisions (e.g., a self-driving car algorithm, or a chess bot).
  • Environment: The world or system in which the agent interacts (e.g., the highway, or the chessboard).
  • State (s): The current situation or condition of the environment at any given moment.
  • Action (a): A specific move, choice, or decision made by the agent.
  • Reward (r): The feedback score given by the environment immediately after the agent takes an action.

The Continuous RL Interaction Loop

The Agent takes an Action, modifying the Environment. The Environment then returns the new State and a Reward.

Agent (AI)
Action (a)
State & Reward
Environment

Reinforcement Learning vs Supervised Learning

A common beginner question is: how is reinforcement learning different from supervised learning? The key difference is the kind of feedback the learner receives.

QuestionSupervised LearningReinforcement Learning
FeedbackCorrect labels/answers are providedRewards or penalties arrive after actions
How learning happensLearns from prepared examplesLearns by interacting and trying
Simple examplePredict whether an email is spamLearn how to move through a maze
Main goalPredict the correct outputMaximize long-term total reward

The Ultimate Goal of RL

The ultimate goal of the Agent is to discover a strong Policy (π). A policy is the strategy the agent uses to decide which action to take in a given state so that it can maximize Cumulative Reward over time. This means the agent may sometimes accept a smaller reward now if that choice can lead to a better total reward later.

A First Look at the Q-Learning Calculation

Q-learning gives each state-action pair a value called Q. A useful first step is to calculate a target value: immediate reward plus the discounted value of the best action available next.

Target = r + γ · max Q(s', a')
  • r = reward received immediately after the action.
  • γ (gamma) = discount factor between 0 and 1; it controls how much future reward matters.
  • max Q(s', a') = value of the best known action from the next state.

Solved Numerical Example — Step by Step

Suppose our robot makes a move and receives a reward of 2. From the next position, the best known future Q-value is 6. Let the discount factor be γ = 0.5.

Step 1: Write the values

r = 2, γ = 0.5, max Q = 6

We simply collect the immediate reward, discount factor, and best future value.

Step 2: Substitute them into the target formula

Target = 2 + (0.5 × 6)

Future reward is multiplied by gamma because future rewards are usually given less weight than an immediate reward.

Step 3: Multiply

Target = 2 + 3

Step 4: Add

Target = 5

So, based on the immediate reward and the best future opportunity, this action has a target value of 5.

Going one small step deeper

In full Q-learning, the old Q-value is not usually replaced instantly by 5. It is moved toward this target using a learning rate α. You will study that update in the advanced Reinforcement Learning lesson.

The Exploration vs. Exploitation Trade-off

One of the biggest philosophical and mathematical challenges in Reinforcement Learning is the Exploration vs. Exploitation dilemma:

  • Exploration: The agent tries entirely new, random actions to discover potentially better strategies that it doesn't know about yet. (e.g., trying a brand new restaurant you've never been to).
  • Exploitation: The agent uses its current established knowledge to choose the best known action to get a guaranteed high reward. (e.g., going to your favorite restaurant because you know it's good).

A successful RL algorithm must mathematically balance both; exploring early on to map the environment, and exploiting later to maximize its final score.

ChoiceSimple meaningExample
ExploreTry something not well known yetTry a new route that might be shorter
ExploitUse the best option currently knownTake the route that has worked well before

Modern Trend: RLHF (Reinforcement Learning from Human Feedback)

Traditional RL relies on a mathematically defined environment (like a video game score). But how do you train an AI to be "helpful" or "polite"? You cannot write a mathematical formula for politeness.

RLHF uses human preferences to create a useful reward signal. For example, humans may compare two AI responses and indicate which one is better. That preference data can be used to train a reward model, which estimates how well a response matches the preferred behavior. The reward signal can then help guide further training toward responses people judge as more helpful or appropriate.

Real-World Applications of Reinforcement Learning

Reinforcement learning is most useful when a system must make a sequence of decisions and learn from the consequences of those decisions.

DomainReal-World Application Examples
Gaming & AIAlphaGo defeating world champions, AI mastering complex multiplayer games like Dota 2 and StarCraft through millions of simulated matches.
RoboticsTeaching robotic arms to grasp delicate objects, or teaching mechanical quadruped dogs to walk and balance over unpredictable, rough terrain.
Autonomous VehiclesSelf-driving cars learning advanced braking, steering, and highway lane-changing policies in dynamic traffic environments.

Frequently Asked Questions

Is reinforcement learning supervised or unsupervised?

Neither. Reinforcement learning is normally treated as a separate learning paradigm because the agent learns from rewards received after actions rather than from a fixed set of labelled answers.

What is a reward in reinforcement learning?

A reward is a numerical feedback signal telling the agent how useful the result of an action was. The agent tries to maximize its total reward over time.

Why does an RL agent need exploration?

If the agent only repeats what already seems best, it may never discover a better action. Exploration allows it to test alternatives and learn more about the environment.

Does reinforcement learning always use deep learning?

No. Simple RL methods such as tabular Q-learning can work without neural networks. Deep reinforcement learning combines RL with neural networks for much larger or more complex problems.

Continue when you are ready for more depth

Later in the curriculum, continue with Advanced Reinforcement Learning and Multi-Armed Bandits to study more detailed decision-making strategies.

Glossary of Key Terms

Agent

The entity or algorithm that makes decisions and takes actions within an environment in reinforcement learning.

Environment

The dynamic world, simulation, or system with which the agent interacts, explores, and learns from.

Reward

The mathematical feedback signal given to the agent after taking an action, which the agent aims to maximize over time.

Policy

The core strategy or mapping from states of the environment to actions that the agent learns to optimize.

Final Summary

Reinforcement Learning is the closest digital mimic to how biological beings learn through consequences. While heavily computationally expensive and notoriously difficult to train, RL algorithms are the leading force behind breakthroughs in creating autonomous, intelligent agents capable of making complex, long-term decisions without human intervention.

Most Important Insight to Remember:

Unlike Supervised Learning (which learns from a static answer key), Reinforcement Learning learns actively by doing. The algorithm must literally experience the world, make mistakes, suffer the penalties, and continuously update its strategy to survive and maximize its score over time.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Reinforcement Learning"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • An agent acts in an environment and receives rewards or penalties.
  • The objective is cumulative return, not necessarily the largest immediate reward.
  • A policy describes which action the agent chooses from a state.
  • Exploration tests uncertain actions; exploitation uses current knowledge.
  • Credit assignment connects delayed outcomes to earlier actions.
  • RL suits interactive sequential decisions, not ordinary labelled prediction.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
What are the three core components of any reinforcement learning problem?
Question 2 of 4
An RL agent plays 10 moves in a chess game and then loses. How does it know which moves were mistakes?
Question 3 of 4
Why is reinforcement learning almost never used to predict house prices?
Question 4 of 4
What is the exploration-exploitation dilemma?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What are the three core components of any reinforcement learning problem?▼

Correct Answer: Agent, environment, and reward signal

RL is defined by an agent that takes actions in an environment and receives reward signals. Unlike supervised learning, there is no pre-existing dataset — the agent generates experience through interaction.

2An RL agent plays 10 moves in a chess game and then loses. How does it know which moves were mistakes?▼

Correct Answer: This is the credit assignment problem — determining which of the 10 past actions caused the eventual loss. Techniques like temporal difference learning address this

The credit assignment problem is fundamental to RL. When a reward (or penalty) arrives after many steps, it's unclear which actions deserve blame. This is one of the central challenges that RL algorithms are designed to solve.

3Why is reinforcement learning almost never used to predict house prices?▼

Correct Answer: There is no natural environment to interact with or reward signal to define — supervised regression with labelled historical data is far simpler and more reliable

RL is powerful when you need to learn through interaction with an environment. For predicting house prices, you already have labelled historical records — there's no reason to design an environment and reward signal when supervised learning is straightforward.

4What is the exploration-exploitation dilemma?▼

Correct Answer: Balancing between trying new actions to discover better strategies (exploration) versus repeating actions already known to give good rewards (exploitation)

Too much exploitation: the agent settles for a suboptimal strategy and never discovers something better. Too much exploration: the agent never capitalises on what it has already learned. Balancing these is central to RL algorithm design.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next