Foundation of Reinforcement learning(IV)

Introduction

In the previous posts, we have introduced the MDP and its solution. But in practice, we often do not have the simulation of the environment, which means we cannot directly apply our knowledge of MDP to solve the problem. There is indeed a method to simulate the environment, which is called model-based Reinforcement learning. However, in this post, we will focus on the model-free Reinforcement learning, which does not require the simulation of the environment and the construction of MDPs.

Estimating Value Functions

In mode-based RL, value functions can be computed by DP methods as follows:

However, in model-free RL, we cannot directly access the and , but we have some ways to estimate the value function from episodes of experience.

Why we estimate the value function?
Because we can use the value function to derive the optimal policy, which is our ultimate goal. Besides value function can help us to reuse historical experience to make better decisions in the future, which is the essence of Reinforcement learning.

Here is a graph to introduce some methods to estimate the value function:

value estimation(Slide credit: David Silver)

Monte Carlo methods

Target: Learn from episodes of experience.

Review: accumulate reward function:

Review: value function is the expected return:
The Monte Carlo method use empirical mean cumulative reward instead of expected return to estimate the value function.

First-visit Monte Carlo method

The first-visit Monte Carlo method estimates the value function by averaging the returns following the first time a state is visited in an episode. The algorithm is as follows:

  1. Initialization:
    • For any ,, .
    • For any ,.
  2. Loop for each episode:
    • Generate an episode following policy : .
    • For t = T-1, T-2, …, 0:
      • If is the first time in the episode:
        • Append to .
        • .

The reason why we call it ‘first-visit’ is that we only update the value function for the first time we visit a state in an episode. Thus we can avoid the bias caused by multiple visits to the same state in an episode. However, this method may have high variance because it only uses one return for each state in an episode.

Incremental Monte Carlo method

The first-visit Monte Carlo method takes a lot of memory to store the returns for each state, which is not efficient. The incremental Monte Carlo method uses an incremental update rule to estimate the value function without storing all the returns. The algorithm is as follows:

  1. Initialization:
    • For any ,, , .
  2. Loop for each episode:
    • Generate an episode following policy : .
    • For t = T-1, T-2, …, 0:
      • If is the first time in the episode:
        • .

Interesting, online softmax also takes the same update rule as the incremental Monte Carlo method. Great job.

Besides, incremental MC provides more design space for us to tackle some problems in practice. For example, we can use a constant step size instead of to update the value function, which is called constant step size MC method. It is useful when the environment is non-stationary, which means the reward function and transition probability may change over time. In this case, we want to give more weight to recent returns than old returns, which can be achieved by using a constant step size :

Some properties of Monte Carlo methods

  1. Monte Carlo methods are model-free, which means they do not require the knowledge of the environment’s dynamics (transition probabilities and reward function).
  2. Monte Carlo methods take the simpliest approach to estimate the value function, which is to average the returns following the policy. However, this method may have high variance because it only uses one return for each state in an episode.
  3. One key to note is that Monte Carlo methods can only be applied to finite MDPs, which means the state space and action space must be finite.

Importance sampling

Let’s try to estimate a custom distribution ‘s expectation.
Then we reassign the importance sampling weight , we can rewrite the above equation as:

Off-policy Monte Carlo methods via Importance Sampling

We can use the cumulative reward function of policy to justify policy , and then weight the cumulative reward function by the importance ratio between and to estimate the value function of policy . The algorithm is as follows:

Every episode would be mutified by the importance sampling ratio:

So we then update the value function by:

Sample by importance sampling will significantly increase the variance of the return, which is because the importance sampling ratio can be very large when and are very different.

Temporal-Difference Learning

Temporal-Difference (TD) is a method combining the MC method and DP method, which name comes from the fact that it uses the diff of estimated value function at two consecutive time steps to update the value function. There are two key ideas in TD learning: TD error and TD target.

For state value funtion , after a transition from state to state with reward , the TD error is defined as:
The TD target is defined as:

As for the TD in Bellman expectation equation, the TD error is used in estimating the expect part.

Some details of TD learning

The simpliest TD learning algorithm is called TD(0), which updates the value function by the TD error at each time step. The key equation of TD(0) is as follows:

Why we update like this?
The Bellman expectation equation is rewritten as:


That’s all. We want to make the TD error as small as possible, which means we want to make the estimated value function as close as possible to the true value function. Thus, we can use the TD error to update the value function.

The TD method introduce the bootstrapping idea, which means we use the estimated value function to update the value function. This is different from the MC method, which uses the actual return to update the value function. The bootstrapping idea can significantly reduce the variance of the return, but it may introduce bias because we are using an estimated value function to update the value function.

Contrast between TD and MC methods

They have the same goal: Learn the value function from episodes of experience. However, they have different approaches to achieve this goal. The MC method uses the actual return to update the value function, which can have high variance but no bias. The TD method uses the estimated value function to update the value function, which can have low variance but may introduce bias.

TD method MC method
update value function like update value function like

The object of TD is , which is called TD target, while the object of MC is , which is the actual return. The TD method’s error is called TD error, which is defined as , while the MC method’s error is defined as .

The strengths and limitations of TD learning and MC learning

TD method can learn until the end of an episode:

  • After each step in an episode, TD method can update the value function use the former value function, which means it can learn until the end of an episode. However, MC method can only update the value function after the end of an episode, which means it cannot learn until the end of an episode.
  • TD method can learn from incomplete episodes, which means it can learn from episodes that are not terminated. However, MC method can only learn from complete episodes, which means it cannot learn from episodes that are not terminated.

Tradeoff between bias and variance

Estimator Bias Variance
MC Unbiased: Higher
TD (real) Unbiased: Lower
TD (actual) Biased: Lower

Note: The real TD target uses the true , which is unknown in practice. The actual TD target uses the current estimate , introducing bias. Despite the bias, TD typically has lower variance than MC because it bootstraps from a single step rather than a full trajectory.

Multi-step TD learning

The TD(0) method only uses the immediate reward and the estimated value of the next state to update the value function, which may not be sufficient to capture the long-term dependencies in the environment. The multi-step TD learning method uses the rewards and estimated values of multiple future states to update the value function, which can better capture the long-term dependencies in the environment. We will introduce it by leading into n-step cumulate reward function and n-step TD target.

N-step cumulate reward function

Consider the following n-step cumulate reward function:
It seems make sense to use the n-step cumulate reward function to update the value function, which is called n-step TD learning. The key equation of n-step TD learning is as follows:

N-step mean cumulate reward function

Can we take up the information of different n-step cumulate reward function to update the value function? The answer is yes.
We can use a weighted average of different n-step cumulate reward functions to update the value function, which is called n-step mean TD learning. The key weight figure of weighted average is as follows:

lambda weight

So the n-step mean cumulate reward function is defined as:
Then we can update the value function by:

This is called TD() method, which is a generalization of TD(0) and MC methods. When , TD() reduces to TD(0) method, and when , TD() reduces to MC method. Thus, by adjusting the value of , we can control the bias-variance tradeoff in the estimation of the value function.

Conclusion about TD(λ) method

  • Unless the is 0, TD() mothod is unbiased, because it’s a weighted average of unbiased n-step TD targets.

  • The variance of TD() method is lower than that of MC method, because it uses bootstrapping to update the value function, which can reduce the variance of the return. However, the variance of TD() method is higher than that of TD(0) method, because it uses more rewards and estimated values to update the value function, which can increase the variance of the return.

  • Empirically is not quite commom because fast credit assignment for a given action is preferred. So MC or TD(0) is more commonly used in practice. However, TD() method can be useful when we want to balance the bias-variance tradeoff in the estimation of the value function, which can be achieved by adjusting the value of .

So TD() use as variable while n-step TD use as variable. TD() is a generalization of n-step TD, which can be seen as a weighted average of infin-step TD targets. By adjusting the value of , we can control the bias-variance tradeoff in the estimation of the value function, which can be useful in practice when we want to balance the bias and variance in the estimation of the value function.

Conclusion

In this post, we have introduced the model-free Reinforcement learning, which does not require the simulation of the environment and the construction of MDPs. We have introduced two methods to estimate the value function from episodes of experience: Monte Carlo methods and Temporal-Difference learning. We have also introduced the n-step TD learning method, which uses the rewards and estimated values of multiple future states to update the value function, which can better capture the long-term dependencies in the environment. Finally, we have discussed the bias-variance tradeoff in the estimation of the value function, which can be controlled by adjusting the value of in TD() method.

Foundation of Reinforcement learning(III)

Introduction

In the previous post, we have introduced the Bellman equation and the linear programming formulation for MDP. In this post, we will discuss the model-based Reinforcement learning, which is a method to solve the MDP when we do not have the model of the environment.

The Settings of RL

Typically, RL is framed as MDP, exploring the enviroment and learning the optimal policy.
Generally, we can only observe the episodes and usually, we do not have the model of the environment.

So we need to introduce the model into our RL project. Model-based RL actually is a method to solve the MDP.

Dynamic Programming Based RL

Dynamic Programming for finite MDP

Our objective function is simple, just the expected return, which is defined as:

In the first episode of the series, we introduced Backward induction, which we can start from the last step and then recursively solve the problem. However, this method is not efficient for large state space, and it requires the state transition.

But meanwhile, we can also use the Bellman equation of value function to tackle the problem:

Optimal Value Function

For a state , we can define the optimal value function as the maximum value function over all policies:
So the optimal value function is as follows:

So the best policy can be derived from the optimal value function as:

for any state and policy , there is:

Obviously, the value function relates to the policy, so we can iterate the optimal value function and the optimal policy until convergence. They are called Value Iteration and Policy Iteration respectively.

Value Iteration

For an MDP which is finite in both state and action space, we can use the value iteration to solve the problem. The value iteration is as follows:

  1. Initialize for all
  2. For each state , update the value function as:
  3. Repeat step 2 until convergence.

NOTE: There isn’t any specific order to update the value function, we can update the value function in any order. But the convergence rate may be different.

Sync & Async Value Iteration

Sync value iteration need to store two copies of value funtion:

  1. For any state , we update the value function as:
  2. After updating all states, we copy the new value function to the old value function:

Async value iteration only need to store one copy of value function:

Policy Iteration

The assumption of MDP is the same as the value iteration, which is finite in both state and action space. The policy iteration is as follows:

  1. Randomly initialize a policy and a value function for all
  2. Repeat the following steps until convergence:
  3. Policy Evaluation: For each state , update the value function as:
  4. Policy Improvement: For each state , update the policy as:

Obviously, the Policy Iteration will be more expensive than the Value Iteration, since it needs to evaluate the policy in each iteration. However, the Policy Iteration can converge faster than the Value Iteration, since it can update the policy in each iteration.

Let’s contrast the two methods:

Method Value Iteration Policy Iteration
Update Value function Policy and value function
uses Bellman optimality equation Bellman expectation equation

NOTE:

  1. Value iteration is a greedy method, we always use the best.
  2. Update the value function by Bellman equation in Policy Iteration is expensive.
  3. For smaller space MDP, Policy Iteration is faster than Value Iteration, but for larger space MDP, Value Iteration is faster than Policy Iteration.
  4. If there isn’t any state transition circle, the value iteration is better.

Bellman operators

In fact, we have introduced the Bellman operators in the previous post, but we haven’t discussed it in detail.

Why Policy Iteration and Value Iteration can converge to the optimal value function? The key is that Bellman operators are contraction mappings.

Bellman operator is the collection of below functions:

  1. Bellman expectation operator, usually denoted as , which is defined as:

  2. Bellman optimality operator, usually denoted as or , which is defined as:

They can be used on the state value function and action value function:

  • expectation operator is used in the policy iteration, used for computing
    the value function of a given policy, while is the inner loop of the policy iteration.
  • optimality operator is used in the value iteration, used for computing the optimal value function, while is the main loop of the value iteration.

Both the Bellman expectation operator and the Bellman optimality operator can be defined on the action value function and the state value function:

  1. Bellman expectation operator on V-function:

  1. Bellman optimality operator on V-function:

  1. Bellman expectation operator on Q-function:

  1. Bellman optimality operator on Q-function:

Due to the contraction property of the Bellman operators, we can guarantee the convergence of the value iteration and policy iteration to the optimal value function.

Model RL

In the above sections, our objective environment is a known MDP, all our methods are based on the assumption that we have the model of the environment, which is the transition probability and the reward function. However, in many real-world scenarios, we do not have the model of the environment, so we need to learn the model from the data.

There are two basic thoughts to learn the model of the environment:

  1. learn the state transition probability:

    where is the number of times we have observed the transition from state to state when taking action , and is the number of times we have observed taking action in state .

  2. learn the reward function :

    where is the number of times we have observed taking action in state , and is the average reward we have observed when taking action in state .

The simple simulate algorithm is as follows:

  1. randomly initialize a policy
  2. repeat the following steps until convergence:
  3. collect data by executing the policy in the environment, and store the transition data in a replay buffer.
  4. learn the model of the environment from the replay buffer, which includes learning the state transition probability and the reward function.
  5. solve the MDP with the learned model to get the optimal policy .

Other method to solve this is not learning the MDP, instead we learn the value function directly from the data, which is called model-free RL, we will discuss it in the next post.

Conclusion

In this post, we have introduced the model-based Reinforcement learning, which is a method to solve the MDP when we do not have the model of the environment. We have discussed the value iteration and policy iteration, which are two basic methods to solve the MDP. We have also introduced the Bellman operators, which are the key to guarantee the convergence of the value iteration and policy iteration. Finally, we have introduced the simple simulate algorithm, which is a method to learn the model of the environment and solve the MDP with the learned model. In the next post, we will discuss the model-free Reinforcement learning, which is a method to learn the value function directly from the data without learning the model of the environment.

Foundation of Reinforcement learning(II)

Introduction

Given the former post where we have introduced the MDP and some basic properties, we are now ready to discuss the MDP-based Reinforcement learning. But first, we need to introduce the solution of MDP.

Bellman Equation

If we have learned the previous post, we will know that there are two types of value function, state value function and action value function. Their mathematical definitions are as follows:

Instinctively, the state value function is the expected return when we start from state and follow policy . Similarly, the action value function is defined as:

Here, it represents the expected return when we start from state , take action , and then follow policy thereafter.

On the other hand, we have a accumulate reward function, which is defined as:
It can be recursively defined as:

So, we can rewrite the state value function as:
Above is the Bellman expectation equation for the state value function. Now, our question is to choose the best policy to maximize the value function. We can define the optimal state value function as:

Due to the Principle of Optimality: Each stage of an optimal policy must be optimal for the remaining stages, we can derive the Bellman optimality equation for the state value function as:

Above is the Bellman optimality equation for the state value function.

Linear Programming for MDP

We have a key observation that the Bellman optimality equation can be rewritten as a linear programming problem. The linear programming formulation for MDP is as follows:

Proof:
The first part is to show that the optimal value function is a feasible solution to the above linear programming problem. We can see that for any state and action , we have:
Thus, satisfies the constraints of the linear programming problem.
The second part is to show that any feasible solution satisfying the constraints must be greater than or equal to .
Given that the optimal policy choose one action for each state , LP constraints imply that for any state :
Let’s write them in matrix form:
while the is the reward vector under policy , and is the transition matrix under policy . We can rearrange the above inequality as:
Since , we can conclude that is invertible, and we can get its inverse as:
Obviously, the above inverse is a non-negative matrix. Thus, we can multiply both sides of the inequality by to get:
Since , we can conclude that .
So, we have shown that any feasible solution is greater than or equal to , and the optimal value function is a feasible solution. Thus, the optimal solution to the linear programming problem is .

Given we have the , we can easily derive the optimal policy as:

Here I asked claude to give me a simple explanation of the equivalence between this greedy like policy decision and the optimal policy. The formal proof may be need to use the fixed point theorem, but it is beyond the scope of this post. We just need to remember that the optimal policy can be derived from the optimal value function by choosing the action that maximizes the expected return.

The Dual Linear Programming for MDP

The dual linear programming formulation for MDP is as follows:

If the initial state distribution for all , then let
, the target function means the expected accumulated reward represented by the occupancy measure, and the constraints means the flow conservation constraints.

Assume that the optimal solution is , we can derive the optimal policy from Theorem 2 as:

Comparison between the Primal and Dual Linear Programming for MDP

Dimension Primal LP Dual LP
variable state value function occupancy measure
objective minimize maximize
constraints Bellman optimality constraints flow conservation constraints
explanation state value action frequency

Summary

At the beginning of this post, I tried to introduce the MDP-based Reinforcement learning, but I found that the solution of MDP takes a lot of space, so I just introduce the Bellman equation and the linear programming formulation for MDP. In the next post, I will introduce the value iteration and policy iteration algorithms for solving MDP, which are based on the Bellman equation.

Foundation of Reinforcement learning(I)

The category of decision making problem

dimension single step multi step
one person optimization problem RL, to the best situation
multi person static game dynamic game, MARL.etc

Dynamic programming

Dynamic program is used to solve the Sequential decision making problem, feature of this problem is that it’s decision making process is sequential, and the decision at one step will affect the next step, and the reward is received at the end of decision making process, not at each step.

For an example, given a maze like problem below, the agent need to find a way from Position A to Position B, and the time of each way is different. Agent need to find the way with the least time. A simple way to solve this is to list all the possible paths, but if there is a circle, if the map is large, this will be unfeasible.

A better way to solve this is Backward induction, we start from the end point, and for evey point we calculate the time to reach the end point, then we regart the selected point as the new end point, and repeat this process until we reach the start point. This is a dynamic programming method, and it can solve the problem in polynomial time. But due to we need find a backward path, this method is only suitable for DAG, if there is a circle, this method will fail.

maze

The example is just a introduction, we can summarize the features of dynamic programming as follows:

  • it start from the end, and caculate the best action for each state.
  • it traverse all the states, and for each state, it calculate the best action, and the value of this state.
  • it need to define the state, path(state transition), time(online reward)

So it lead to the Principle of Optimality:

An optimal policy has the property that whatever the initial state and initial decision are, the remaining decisions must constitute an optimal policy with regard to the state resulting from the first decision.

Markov Decision Process

Stochastic Process

A stochastic process is a collection of random variables, which can be used to describe the evolution of a system over time. It’s mathematical definition is as follows:
This means that the probability of the next state depends on the current state and all the previous states .

Markov Process

Compared to stochastic process, Markov process has a stronger assumption, which is “the future is independent of the past given the present”. Mathematically, it’s definition is as follows:
This means that the probability of the next state only depends on the current state , and is independent of all the previous states .

Trying to understand it’s property is that the current state contains all the information about the past, so we can make decision based on the current state without worrying about the past.

Markov Decision Process

Markov Decision Process (MDP) provides a mathematical framework for modeling decision making in situations where the outcome is partly random, partly under the control of a decision maker. An MDP is defined by the following components:

  • State space (S): A set of all possible states in the environment.
  • Action space (A): A set of all possible actions that the agent can take
  • Transition function (P): A function that defines the probability of transitioning from one state to another given a specific action. It is denoted as , which represents the probability of transitioning to state from state after taking action .
  • Reward function (R): A function that defines the reward received after transitioning from one state to another given a specific action. It is denoted as , which represents the reward received after taking action in state . Sometimes only relates to the State.
  • Discount factor (γ): A factor that determines the importance of future rewards. It is a value between 0 and 1, where a value closer to 0 makes the agent prioritize immediate rewards, while a value closer to 1 makes the agent consider future rewards more heavily.

The dynamic feature of MDP

The whole process of MDP is dynamic as follows:

  1. The agent observes the current state .
  2. The agent selects an action based on its policy , which is a mapping from states to actions.
  3. The agent gets a reward .
  4. The MDP transitions to a new state according to the transition function .

The total reward that the agent receives over time is often defined as the discounted sum of rewards:

Markov Policy

In the context of MDP, a policy is a function that depends on the history:

But a Markov policy is a special type of policy that only depends on the current state:


In the RL setting, we usually assume that the policy is a Markov policy. Why?

The MDP has Markov property, which means the future is independent of the past given the present, so there is no special information in the history that can help us make better decision, so we can just use the current state to make decision.More informally, for any policy relying on the history, we can find a Markov policy that at least performs as well as it does, so we can just focus on Markov policy without loss of generality.proof(the 26th and 27th slides of the lecture)


The category of MDP Policy

At the time demension, we can categorize the policy into two types:

  • Stationary policy: A policy that does not change over time. It is defined as , which means the action taken in state is the same at any time step.
  • Non-stationary policy: A policy that can change over time. It is defined as , which means the action taken in state can be different at different time steps.

At the probability distribution demension, we can categorize the policy into two types:

  • Deterministic policy: A policy that always selects the same action for a given state. It is defined as , which means the action taken in state is always .
  • Stochastic policy: A policy that selects actions according to a probability distribution. It is defined as , which means the action taken in state is selected according to the probability

In the RL setting, we usually assume that the policy is a stationary policy. Why?
Typically, we consider the infinite horizon setting. There is also a proof that for any non-stationary policy, we can find a stationary policy that at least performs as well as it does, so we can just focus on stationary policy without loss of generality. proof(the 29th and 32th slides of the lecture)


The best policy for MDP

There is a theorem:

In a situation that the discount factor , while the state and action space are finite and the horizon is infinite, there exists a deterministic
and stationary policy that is optimal, which means for any policy , we have .

Proof: Puterman, Martin L. Markov decision processes: discrete stochastic dynamic programming. John Wiley & Sons, 2014.

The goal of MDP

Our goal is to choose the action to maximize the expected reward, which is defined as follows:

So we can define the value function for a policy as follows:
This means the expected reward that the agent can get starting from state and following policy .

Occupancy Measure

In MDP context, the occupancy measure is a way to represent the discounted state-action expectation under a policy , also known as state-action visitation distribution. It is defined as follows:

while the means the state transition, which is defined as follows:

On the other hand, the state occupancy measure is defined as follows:

How to compute the occupancy measure?

State occupancy measure

We assume that the initial state distribution is , then we can compute the state occupancy measure as follows:

then we can solve the fomula:

State-action occupancy measure

We can compute the state-action occupancy measure as follows:

Pay attention that the whole process is flow conservation. Because the state-action occupancy measure is the expected discounted number of times that the agent takes action in state , so the total flow into state must equal the total flow out of state . This is why we have the flow conservation constraint in the computation of occupancy measure.

Some Properties of Occupancy Measure

Obviously, from the definition of the measures:

We have two important theorems about the occupancy measure:

  • Theorem 1: For two policies and interacting with the same dynamic environment, if , then .
  • Theorem 2: Given a Occupancy measure , the only policy that can generate this occupancy measure is .

Accumulated reward for a policy

As we have defined the occupancy measure, we can compute the accumulated reward for a policy as follows:

Value function and Q function

The value function is used to evaluate a state or a state-action pair, given a policy .

The state value function is usually know as value function, which is defined as follows:

The state-action value function is usually know as Q function, which is defined as follows:


Obviously, we have the relationship between the value function and the Q function:
And we can also compute the value function and Q function using the occupancy measure as follows:


Summary

  • MDP provides us a simple but powerful mathematical framework to model the sequential decision making problem.

  • The five-tuple of MDP is defined as , which represents the state space, action space, transition function, reward function and discount factor respectively.

  • Markov poverty is the key assumption of MDP, which means the future is independent of the past given the present.

  • Policy is the function to choose the action, usually is a conditional probability distribution over actions given states, and we usually assume that the policy is a stationary policy.

  • Occupancy measure is a way to represent the discounted state-action expectation under a policy, which can be used to compute the accumulated reward for a policy.

  • State value function and state-action value function are used to evaluate a state or a state-action pair, given a policy, and they can be computed using the occupancy measure.