Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

Deep Learning (4): Reinforcement Learning Explained with Intuitive Examples

Reinforcement Learning is a machine learning paradigm where AI agents learn optimal decision-making by interacting with an environment, receiving rewards, and learning from trial and error. This article uses easy-to-understand examples like riding a bicycle and racing cars to explain core concepts such as value functions, discount factors, and policies, helping readers build a strong intuitive understanding of reinforcement learning.

reinforcement learningdeep learningAI agentsvalue functiondiscount factor

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

Original Article: https://developer.nvidia.com/blog/deep-learning-nutshell-reinforcement-learning/

Author: Tim Dettmers

Publication Date: September 8, 2016

This chapter is the fourth installment in the Deep Learning in a Nutshell series. Here we will take a deep dive into reinforcement learning. Reinforcement learning is one of the paradigms and methodologies of machine learning. It is used to describe and solve the problem of how an AI agent can learn a policy through interaction with its environment in order to maximize the total reward (or return) it receives.

The Deep Learning in a Nutshell series provides a high-level overview of the fundamental concepts in deep learning. Its goal is to build intuition about the core ideas rather than to delve into mathematical and theoretical details. Although mathematical terminology is sometimes necessary and helpful for deeper understanding, this chapter uses analogies and visualizations as much as possible to make the material accessible, forming an intuitive overview of the field of deep learning. Previous articles in the series have covered Core Concepts of Deep Learning, Deep Learning: Training and History, and Sequence Learning.

Reinforcement Learning

Do you remember how you learned to ride a bicycle? There was probably an adult standing behind you or walking alongside, encouraging you to take the first push and helping you get back on when you stumbled or fell. But explaining to a child how to ride a bike is extremely difficult. No matter how good the explanation is, it means almost nothing to someone who has never ridden before — you simply have to experience it yourself. So if you can’t explain how to ride a bike, how do you actually learn it? In reality, you learn by constantly trying things out. You are likely to fall, or at the very least come to a sudden stop and have to regain control. You keep falling and wobbling — until one day you suddenly get the hang of it and manage to ride several meters before falling again.

In this learning process, the feedback signal based on our performance is either a punishment (“Ouch! I fell! That hurt! Next time I’ll avoid doing whatever caused that!”) or a reward (“Wow! I’m riding a bike! This feels amazing! I just need to keep doing what I’m doing right now!”).

Learning to ride a bicycle requires trial and error — just like reinforcement learning. (Video courtesy of Mark Harris, who says he is “learning reinforcement” as a parent.)

In reinforcement learning, we assume there is an AI agent that tries to maximize the total reward it can receive by making decisions.

Therefore, an agent that obtains the maximum possible reward can be considered to have taken the optimal action in a given state. Here, the “agent” refers to an abstract entity — it can be any object or subject that performs actions: a self-driving car, a robot, a human, a customer-support chatbot, or a Go player. The state of the agent refers to its position and condition within an abstract environment — for example, a location in a virtual reality world, inside a building, on a chessboard, or the position and speed of a car on a racetrack.

To simplify both the reinforcement learning problem and its solution, the environment is often abstracted so that the agent only perceives the details that are important for decision-making, ignoring everything else. As in the bicycle-riding example, a reinforcement learning algorithm has only two sources of feedback to learn from: punishment (the pain of falling) and reward (the thrill of riding a few meters). If we treat punishment as negative reward, the entire learning problem becomes one of exploring the environment, moving from one state to another, and trying to maximize the total reward the agent receives until it reaches a goal state (driving autonomously from A to B, winning a chess game, or resolving a customer issue through conversation). In short, this is reinforcement learning.

Value Function

Reinforcement learning is an algorithm that learns how to select actions that produce the maximum cumulative reward through positive and negative rewards (punishments or pain). To find these actions, we first need to identify which states in the current environment are the most valuable. For example, on a racetrack, the finish line is the most valuable state (essentially the step just before you sprint to meet the deadline—this state is definitely the most valuable), meaning it carries the highest reward. States on the track are more valuable than those off the track. (This embodies recursive thinking: once you find the most valuable state, you only need to figure out how to reach that state.)

Once we determine which states are valuable, we can assign “reward” values to different states. For instance, give negative rewards to all states where the car deviates from the track; give a positive reward for completing a lap; give another positive reward when the car beats the current best lap time; and so on. We can treat states and rewards as a discrete function. For example, the racetrack can be represented as a 1×1 meter grid. Rewards on the grid are represented by numbers: the goal state might have a reward of 10, off-track states might have a reward of -2, and all other states have a reward of 0. If we imagine this function in three dimensions, we can picture that the best actions are those that make the function’s value as high as possible (i.e., actions that maximize the reward).

For every state, there exist intermediate states that may not have any immediate reward (reward = 0), yet they are necessary steps on the path to a rewarding state. For example, you must get through the first corner to complete a lap, or you must finish a full lap before you can improve your lap time.

The value function, once trained or fitted, assigns local reward values to these intermediate states. Completing the second lap becomes more valuable than the first because it is closer to the next goal state. The value function helps the AI agent make correct decisions by providing these intermediate rewards, making it easier for the agent to decide which state to move to next.

Figure 1: Building a value function through value iteration over all states. Each grid cell represents a state: S is the starting state, G is the goal state, T cells are traps, and black cells are inaccessible. In value iteration, we initialize the rewards (for traps and the goal state), and these reward values propagate over time until equilibrium is reached. Depending on the penalty values of the traps and the reward value of the goal, different reward settings may produce different solutions. The last two diagrams show two distinct solutions.

This framework implies that the value of any given state is influenced by the values of its surrounding states. Figure 1 shows an example world where each square is a state. S and G are the starting and goal states respectively, T squares are traps, and black squares are inaccessible (like large rocks blocking the way). The objective is to move from state S to state G. If we imagine this as our racetrack, over time we would create a “slope” from the starting state to the goal state, so that we only need to move in the steepest direction. This is the core idea of the value function: it provides an estimate of the value of each state so we can make incremental decisions until we obtain the reward.

The value function can also capture the nuances of a problem. For example, the penalty for a race car being on the edges of the track is not as severe as being completely off the track; however, this alone does not effectively guide the car back to the center of the track, preventing it from achieving the desired lap times (since the car cannot turn at high speed). Therefore, safety and speed cannot always be optimized simultaneously. The value function will find the most appropriate fast yet safe path on the track. The final solution can be adjusted by changing the reward values. For instance, if higher rewards are given for shorter lap times, the value function will assign higher values to states that are riskier but allow shorter times.

Figure 2: Different racing lines at a corner. Each racing line has different distances, possible speeds, and levels of tire wear. A value function optimized for lap time will solve this problem by finding the state transitions that minimize time spent in the corner.

Discount Factor

Although the value function determines the magnitude of rewards, it also depends on a parameter called the discount factor, which limits how much an agent is influenced by more distant states. (In a running race, a state far from the finish line could yield a very large reward simply by moving toward the goal — but this is clearly unreasonable.) Each time the state changes, the immediate reward is multiplied by the discount factor before being added to the value function. Therefore, with a discount factor of 0.5, the original reward shrinks to one-eighth of its initial value after just three state transitions. As a result, the agent tends to prioritize rewards from nearby states. The discount factor thus acts as a weighting parameter that controls whether the value function favors cautious or greedy behavior.

For example, a very fast racing car might receive a high reward. A discount factor close to zero would lead to an increasingly greedy strategy of simply accelerating. However, a more cautious agent understands that accelerating faster and faster is a bad idea when a sharp turn lies ahead. Slowing down at the right moment may result in a shorter lap time later, ultimately yielding a higher overall reward. To possess this kind of foresight, the agent needs to defer the reward of high speed; in such cases, a discount factor close to 1 is often better.

The discount factor in the value function ensures that distant rewards diminish proportionally with distance or number of steps. It is typically set to a value that places high importance on long-term rewards without overemphasizing them (for instance, decaying the reward by 5% with each state transition).

The learning process begins by initializing the reward value of every state to 0 or some specific value. It then examines all possible next states reachable from the current state (each transition having an associated probability) and evaluates the reward obtained in those next states. In this way, the agent learns the unique local reward value for each state. If a (partial) reward is obtained in the next state, that reward is accumulated into the current state’s value. This process is repeated until the partial rewards within every state no longer change — meaning that all possible transitions and the reward values of every state have been taken into account. You can see the process of the value iteration algorithm in Figure 1.

At first glance, this may seem inefficient, but techniques related to dynamic programming make it far more efficient. Dynamic programming solves higher-order problems once subproblems have been solved: the reward from B to C can be reused to compute the chained rewards for both A→B→C and D→B→C.

In summary, the value function and value iteration provide a decision map of partial rewards. Based on this map, the agent can move toward states where the reward value increases, thereby obtaining an optimal policy for each state.

Policy Function

Given a value function, the policy function represents a strategy that selects the action expected to produce the highest (long-term) return. Among all possible next actions, there is often no single obvious winner. For example, an agent must choose to move into one of four states—A, B, C, or D—with reward values of A=10, B=10, C=5, and D=5. Both A and B are strong immediate choices, but over time the path following state A may yield far greater rewards than B, or the action leading to C may ultimately prove to be the best option. Searching through all possibilities during training is worthwhile, yet relying solely on immediate rewards can lead to suboptimal choices. So how do we strike a balance between exploring paths that offer the highest immediate rewards and exploring paths that yield lower short-term returns but may deliver much higher rewards in the long run?

A clever approach is to select states randomly in proportion to their reward values. In this example, the probability of choosing A is 33% (10/(10+10+5+5)), while B, C, and D have probabilities of 33%, 16%, and 16%, respectively. This stochastic selection property of the policy function is crucial for learning a good strategy. Some effective—and even critical—strategies may seem counterintuitive at first.

For instance, if you train a racing car solely to drive as fast as possible, it will aggressively cut corners at the highest possible speed. However, if you introduce competing cars into its environment, that strategy is no longer optimal. The agent will learn to account for opponents slowing down in turns, thereby avoiding the risk of being overtaken or, worse, colliding. Another scenario is that high-speed cornering may wear out tires faster, forcing an unscheduled pit stop and wasting valuable time.

Note that the policy function and the value function are interdependent. Given a particular value function, different policies lead to different choices; conversely, given a specific policy, the agent may assign different values to actions. In a chess game with a “win the match at all costs” strategy, the value function will assign high value to moves that increase the probability of winning (sacrificing pieces to gain a winning advantage would be highly valued). But if the objective is “win by a large margin,” the policy function will learn actions that maximize the score in a given game (never sacrifice pieces).

These are just two of many possible examples. If we want to achieve a specific outcome, we can use the policy function and value function to guide the agent in learning a good strategy to reach that outcome. This is what makes reinforcement learning so versatile and powerful.

We train the policy function through the following steps:

  1. Randomly initialize the policy—for example, by making the probability of selecting each state proportional to its reward value—and initialize the value function with those reward values; that is, set the value of all states without an immediate reward to zero (e.g., a reward of 10 for reaching the track goal, a penalty of -2 for going off-track, and zero reward for all on-track states).

  2. Train the value function until it converges (see Figure 1).

  3. For a given state (state A), increase the probability of the action that leads to the largest increase in reward (moving from A to B). This move may have a lower or even negative immediate reward compared to moving from A to C (such as sacrificing a piece), yet it may align with the overall strategy for winning the game.

  4. Repeat from step 1 until the policy no longer changes.

Q Function

We have already seen that the policy function and the value function are highly interdependent: our policy depends largely on what we value, and what we value determines our actions. So perhaps we can combine the value function and the policy function? We can, and this combination is called the Q function (also known as the action-state value function).

The Q function takes into account the current state (as in the value function) and the next action (as in the policy function), and returns the partial reward for a state-action pair (that is, the Q function takes the agent’s state and action as input and maps them to possible rewards). For more complex use cases, the Q function may also combine additional states to predict the next state. For example, if movement direction matters, at least two states are typically required to predict the next state, because precise direction usually cannot be inferred from a single state (such as a still image). We can also pass the input state to the Q function to obtain the partial reward value for every possible action. We can then, for instance, randomly select the next action based on the proportion of those local reward values (a method called exploration), or simply take the action with the highest value (a method called exploitation).

However, the real essence of the Q function lies elsewhere. Imagine a self-driving car: there are so many possible “states” that building a value function covering all of them is impossible. Every possible speed and position on every road on Earth is simply too vast; computing all the local reward values is practically infeasible. Instead, the Q function:

(1) only looks at all possible next states within a one-step horizon, and
(2) finds the best possible action based on the current state and the next state.

Therefore, for each next state, the Q function explores one step forward (rather than exploring all steps until termination, as the value function does). These forward explorations are represented as state-action pairs. For example, state A may have 4 possible actions, giving us the action pairs A→A, A→B, A→C, and A→D. With four actions per state and a 10×10 grid of states, the entire Q function can be represented as four 10×10 matrices, or a single 10×10×4 tensor.

See Figure 3 for an example of a Q function representing the solution to a grid-world problem (a 2D world where an agent can move to adjacent states), with the goal located in the bottom-right corner.

Figure 3: Q function for a grid-world problem with blocked states (black), where the goal is in the bottom-right corner. The four matrices show the rewards (or Q-values) for all four possible actions in each state. Darker green indicates higher Q-values. The agent will choose darker states with higher probability, or, in a greedy policy, will always select the action with the highest Q-value. This behavior guides the agent to the goal as quickly as possible, regardless of its starting position.

In some cases, we need to model an essentially infinite number of states. For example, in self-driving cars, “states” are typically represented as continuous functions using neural networks. These networks take all state variables—such as the car’s speed and position—as input and output a Q-value for each possible action.

Why is it helpful to only use information from some states? Many states are highly correlated, so taking the same action in two different but similar states can often both be successful. For instance, every turn on a racetrack is different, yet what you learn from each left turn (when to start turning, how to adjust speed, etc.) is valuable for the next left turn. Therefore, over time, a racing agent can learn increasingly better techniques for left turns—even on tracks it has never seen before.

Q-Learning

To train the Q-function, we initialize all Q-values for every state-action pair to zero and set the state reward values to the given values as the initial values for each state. Since the agent initially has no idea how to obtain rewards (the agent can only see the Q-values of the next state, which are all zero), the agent may explore many states before discovering a reward. Therefore, we define a training length for the Q-function (e.g., 100 steps), or train until certain states are reached (such as completing a lap on a racetrack). This ensures we do not get stuck learning useless state-action pairs that, no matter how many iterations are performed, will never yield any meaningful reward.

Figure 4: Q-Learning in a grid world, where S is the starting state, G is the goal state, T squares are traps, and black squares are blocked states. During Q-Learning, the agent gradually explores the environment and initially fails to find the goal state G. Once a chain from the goal state to the vicinity of the starting state is established, the algorithm quickly converges to a solution and then further refines it to discover the optimal policy for the problem.

Q-Learning works backwards from the outcome (reward) to the beginning (the first state). Figure 4 illustrates the grid world example from Figure 1 using Q-Learning. Assume the objective is to reach the goal state G in the fewest possible steps. Initially, the agent makes random moves until it (by chance) reaches either a trap or the goal state. Since traps are closer to the starting state, the agent is more likely to encounter a trap first. However, once the agent stumbles upon the goal state, this pattern is broken. From that iteration onward, the states immediately preceding the goal state (one step forward in exploration) are assigned local reward values. Because these rewards are now closer to the starting point, the agent is more likely to reach such rewarding states. In this way, we build a chain of local reward values from the goal back to the starting state. The more frequently the agent encounters states with local rewards, the faster those local reward values converge (see Figure 4).

Deep Q-Learning

A self-driving car may need to consider many different states: every possible combination of speed and position constitutes a distinct state. However, most of these states are similar. Is it possible to group similar states together so that they share similar Q-values? This is where deep learning comes into play.

We can feed the driver’s current view — a single image — into a convolutional neural network (CNN) and train it to predict the reward for the next possible action. Because images of similar states look alike (many left turns appear similar), they will also produce similar actions. For example, the neural network will generate many left-turn behaviors and take appropriate actions even on left turns it has never encountered before. Just as a CNN trained on images of many different objects can accurately recognize those objects, a network trained on numerous variations of left turns can fine-tune its speed and position adjustments for every distinct left-turn scenario.

However, to successfully apply deep Q-learning, we cannot simply use the rule described earlier to train the Q-function. If we apply the Q-learning rule blindly, the network will learn to perform left turns well, but at the same time it will start forgetting how to perform right turns. This happens because all actions in the neural network share the same weights; adjusting the weights for left turns makes the network perform worse in other situations. The solution is to store every input image and output action as an “experience”: that is, to save the state, action, and reward together.

After running the training algorithm for a while, we randomly sample from all the experiences collected so far and create an averaged update for the neural network weights. This update maximizes the Q-value (reward) for every action that occurred during those experiences. In this way, we can teach our neural network to perform both left and right turns effectively. Since early driving experiences on the track are less important — they come from a time when our AI agent was inexperienced or even a complete beginner — we only keep a fixed number of recent experiences and forget the rest. This process is known as experience replay.

The following video shows a deep Q-learning algorithm learning to play Breakout at an expert level. (Thanks to Károly Zsolnai-Fehér for allowing us to embed this video. You may also be interested in his 2-minute YouTube channel, where he explains important scientific work in plain language in just two minutes.)

Video link: https://youtu.be/V1eYniJ0Rnk

Experience replay is a biologically inspired technique. The hippocampus in the human brain serves as the reinforcement learning center for each hemisphere. It stores all of our daytime experiences, but its memory capacity is limited. Once that limit is reached, learning becomes much harder (think of cramming too much the night before an exam). At night, the memory buffer in the hippocampus is cleared into the cortex through widespread neural activity. The cortex acts as the brain’s “hard drive,” where almost all memories are ultimately stored. Memories of hand movements are kept in the “hand area,” auditory memories in the “auditory area,” and so on. This characteristic neural activity spreading outward from the hippocampus is known as sleep spindles. Although there is currently no strong evidence, many sleep researchers believe that we dream in order to help the hippocampus integrate the day’s collected experiences with our existing memories in the cortex, forming a coherent picture.

As you can see, storing memories and then writing them back in some coordinated manner is an important process not only for deep reinforcement learning, but also for human learning. This biological similarity gives us a bit more confidence that our theories about the brain may be correct — and that the algorithms we design are on the right path toward intelligence.

AlphaGo

AlphaGo, developed by Google DeepMind, became the first computer program to defeat a human professional Go player in 2016, creating a major sensation. It then went on to defeat one of the world’s top Go players, Lee Sedol, with a score of 4–1. AlphaGo combines many of the elements discussed earlier in this article: (1) a value neural network and (2) a policy neural network. These represent (1) the value function of the current board position in a game of Go, which predicts the relative value of each move, and (2) the policy function, which indicates which moves should be chosen to win the game. Both networks are convolutional neural networks that treat the 19×19 Go board as an input “image” (one pixel per board position).

Since we already have extensive records of Go games, it is useful to train the policy network using existing data from professional matches. The policy network is trained on this data to predict the next move a Go champion would make in a given board position.

(Image credit: Linh Nguyen/Flickr)

Once the supervised training phase is complete, reinforcement learning comes into play. Here, AlphaGo plays against itself and attempts to refine its move-selection policy (the policy network) while also improving its ability to evaluate who will win (the value network). Even when only the policy network is trained, it already performs far better than the most famous previous Go algorithm, Pachi, which relied on tree search and heuristics. However, with the addition of the value network, the performance of the deep learning approach improves dramatically.

When the value network is trained across entire games, it tends to generalize poorly. Due to the highly correlated nature of board positions, the network often learns to recognize specific historical matches (e.g., “if this is the A vs. B game from Beijing in 1978, then A wins”) rather than learning to identify good moves. To overcome this problem, DeepMind generated a large amount of self-play data from AlphaGo playing against itself, then sampled several positions from each game to train the value network. This approach is similar to experience replay: instead of looking at long sequences of moves in isolation, the network is trained on highly diverse combinations of states and actions.

The value network achieves performance comparable to Monte Carlo search trees that use rollout policies. However, AlphaGo further improves results by combining deep learning with Monte Carlo tree search (MCTS). So what exactly is a Monte Carlo search tree with a rollout policy? Imagine a tree of game positions where each action is an edge and each node represents a different board state. For example, from your current position you may have 200 possible moves—meaning 200 child nodes connected to your current node. When you choose one action (traversing one edge to a new node), a new subtree with 199 possible continuations is generated. This tree can never be fully expanded because it grows exponentially and would take far too long to evaluate completely. Therefore, in Monte Carlo tree search, we only follow a single path down the tree to a certain depth, making evaluation much more efficient.

In the rollout policy, we look at the current state, use the policy network to select the next action in the tree, and then repeat this process for both players until the game ends and a winner is determined. This provides a fast, greedy way to estimate the value of an action. These insights can also be used to improve the accuracy of the value network. With a more accurate value function, we can further improve our policy function: knowing more precisely whether an action is good or bad allows us to develop better strategies based on moves that are genuinely strong or were previously thought to be weak. In other words, AlphaGo is able to discover and execute strategies that humans could never have imagined—yet still win the game.

AlphaGo also uses Monte Carlo tree search during training. The tree maintains three values for each action that are updated in every iteration: the Q-value (action value), visit count (N), and prior probability (P). Initially, all Q-values, visit counts, and prior probabilities are zero. In each iteration, actions are selected based on these three parameters. For example, to decide whether playing at E5 is a good move, the new board state after that action is evaluated using two components:

(1) The policy network, which assigns an initial prior probability to that action;
(2a) The value network, which assigns a value to that action; (2b) Monte Carlo rollout, which assigns another value to that action.

Steps (2a) and (2b) are combined with a weighting parameter to update the Q-value. The Q-value and visit count (N) are then updated based on the average evaluation along that path (increasing the Q-value if the action is on average relatively good, and decreasing it otherwise).

The value of the same action is slightly reduced with each additional visit (as N increases), which increases the probability of exploring new actions. This ensures a balance between exploration and exploitation. At the same time, we obtain increasingly accurate estimates for the actions we have already taken. Over time, the tree assigns higher Q-values to the most powerful moves. Through this training process, AlphaGo learns to select better actions with each iteration, ultimately learning which moves lead to victory. At that point, creating a Go-playing system superior to human experts became simply a matter of computational power and time.

Conclusion

In this article, we have seen that reinforcement learning is a general framework for training AI agents to exhibit highly complex behaviors. We explored the core components of reinforcement learning, including value functions and policy functions, and built upon them to implement deep reinforcement learning. Deep reinforcement learning holds the promise of becoming an extremely general learning paradigm capable of acquiring useful behaviors from very limited feedback. It is an exciting yet challenging field that is certain to play a major role in the future of artificial intelligence. You may also be interested in Training Reinforcement Learning Agents in OpenAI Gym.

If you would like to read the rest of this series, please check out Part 1: Deep Learning in a Nutshell: Core Concepts, Part 2: Deep Learning in a Nutshell: Training and History, and Part 3: Sequence Learning. I hope you enjoyed the series!

If you have any questions, please leave them in the comments section below and I will do my best to answer them.

Acknowledgments

I would like to thank Mark Harris for helping me refine this blog series through his thoughtful editing and valuable suggestions. I would also like to thank Allison Rands and Stephen Jones for making this series possible.