Markov Decision Process
local graph
Chapter 9 — Markov Decision Process
Section titled “Chapter 9 — Markov Decision Process”In this chapter, we will talk about another application of HMMs known as Markov Decision Process (MDP). In the case of MDPs, we introduce a reward to our model, and any sequence of states taken by the process results in a specific reward. We will also introduce the concept of discounts, which will allow us to control how short-sighted or far-sighted we want our agent to be. The goal of the agent would be to maximize the total reward that it can get.
In this chapter, we will be covering the following topics:
- Reinforcement learning
- The Markov reward process
- Markov decision processes
- Code example
Reinforcement learning is a different paradigm in machine learning where an agent tries to learn to behave optimally in a defined environment by making decisions/actions and observing the outcome of that decision. So, in the case of reinforcement learning, the agent is not really from some given dataset, but rather, by interacting with the environment, the agent tries to learn by observing the effects of its actions. The environment is defined in such a way that the agent gets rewards if its action gets it closer to the goal.
Humans are known to learn in this way. For example, consider a child in front of a fireplace where the child is the agent and the space around the child is the environment. Now, if the child moves its hand towards the fire, it feels the warmth, which feels good and, in a way, the child (or the agent) is rewarded for the action of moving its hand close to the fire. But if the child moves its hand too close to the fire, its hand will burn, hence receiving a negative reward. Using these rewards, the child is able to figure out the optimal distance to keep its hand from the fire. Reinforcement learning tries to imitate exactly this kind of system in order to train the agent to learn to optimize its goal in the given environment.
Making this more formal, to train an agent we will need to have an environment which represents the world in which the agent should be able to take actions. For each of these actions, the environment should return observations which contain information about the reward, telling it how good or bad the action was. The observation should also have information regarding the next state of the agent in the environment. And, based on these observations, the agent tries to figure out the optimal way to reach its goal. Figure 1 shows the interaction between an agent and an environment:

The thing that makes reinforcement learning fundamentally different from other algorithms is that there is no supervisor. Instead, there is only a reward signal giving feedback to the agent about the action it took. Another important thing to mention here is that an environment can be constructed in such a way that the reward is delayed, which can make the agent wander around before reaching its goal. It is also possible that the agent might have to go through a lot of negative feedback before reaching its goal.
In the case of supervised learning, we are given the dataset, which basically tells our learning algorithm the right answers in different situations. Our learning algorithm then looks over all these different situations, and the solutions in those cases, and tries to generalize based upon it. Hence, we also expect that the dataset given to use is independent and identically distributed (IID). But in the case of reinforcement learning the data is not IID, the data generated depends on the path the agent took, and, hence, it depends on the actions taken by the agent. Hence, reinforcement learning is an active learning process in which the actions taken by the agent influence the environment which in turn influences the data generated by the environment.
We can take a very simple example to better understand how a reinforcement learning agent and environment behave. Consider an agent trying to learn to play Super Mario Bros:
- The agent will receive the initial state from the environment. In the case of Super Mario, this would be the current frame of the game.
- Having received the state information, the agent will try to take an action. Let’s say the action the agent took is to move to the right.
- When the environment receives this action it will return the next state based on it. The next state would also be a frame, but the frame could be of a dying Mario if there was an enemy next to Mario in the previous state. Otherwise, the frame would just have shown Mario to have moved one step to the right. The environment will also return the rewards based on the action. If there was an enemy on the right of Mario the rewards could be, let’s say -5 (since the action killed Mario) or could be +1 if the Mario moved towards finishing the level.
The whole concept of reinforcement learning is based on something called reward hypothesis. According to reward hypothesis, all goals can be defined by the maximization of the expected cumulative reward.
At any given time t, the total cumulative reward can be given by:
But, in reality, the rewards which are closer to the current state are more probable that the ones which are further away. To deal with this, we would introduce another term called the discount rate,. The value of the discount rate is always between 0 and 1. A large value of means a smaller discount, which make the agent care more about the long-term rewards, whereas, for smaller values of, the agent cares more about the short-term rewards. With the discount rate term, we can now define our cumulative reward as:
As we saw earlier, the agent interacts with the environment at intervals of time t = 0, 1, 2, 3,.., and, at each time instance, the agent gets the state of the environment S t based on which it takes an action A t and gets a reward R t+1. This sequence of state, action and rewards over time is known as the history of the agen t and is given as:
Ideally, we would like the action taken by the agent to be based on its total history, but it is generally unfeasible because the history of the agent can be huge. Therefore, we define the state in a way such that it is a summary of all the history of the agent:
Basically, we are defining the state to be a function of the history of the agent. It’s important to notice that the environment state is the state that the environment uses to determine its next state, based on the action, and give out rewards. Also, it is private to the environment.
On the other hand, the agent state is the state that the agent uses to decide on the next action. The agent state is its internal representation, and can be any function of the history as mentioned before.
We use a Markov state to represent an agent’s state, which basically means that the current state of the agent is able to summarize all the history, and the next action of the agent will depend only on the current state of the agent. Hence,
In this chapter, we will only be considering the case when the agent is directly able to observe the environment’s state. This results in the observation from the environment to be both the current state of the agent as well as the environment. This special case is also commonly known as MDP.
In this section, we will formally define the different kinds of components that an agent can have.
- Policy: It is a conditional over the action given the state. Based on this conditional distribution, the agent chooses its action at any given state. It is possible for the policy to be deterministic: a = π(s) or stochastic:.
- Value function: The value function tries to predict the reward to expect on taking a given action in a given state. It is given as: . where E is the expectation and is the discount factor.
- Model: The model is the agent’s representation of the environment. It is defined using a transition function P which predicts the next state of the environment: . and a reward function which predicts the reward associated with any given action at a given state:.
Based on these components, agents can be classified into the following five categories:
- Value-based agents: Have an implicit policy and the agent takes decisions for actions based on the value function
- Policy-based agents: Have an explicit policy and the agent searches for the most optimal action-value function
- Actor-critic agents: Combination of both value-based and policy-based agents
- Model-based agents: Try to build a model based on the environment
- Model-free agents: Don’t try to learn the environment, rather they try to learn the policy and value function
In the previous section, we gave an introduction to MDP. In this section, we will define the problem statement formally and see the algorithms for solving it.
An MDP is used to define the environment in reinforcement learning and almost all reinforcement learning problems can be defined using an MDP.
For understanding MDPs we need to use the concept of the Markov reward process (MRP). An MRP is a stochastic process which extends a Markov chain by adding a reward rate to each state. We can also define an additional variable to keep a track of the accumulated reward over time. Formally, an MRP is defined by where S is a finite state space, P is the state transition probability function, R is a reward function, and is the discount rate:
where denotes the expectation. And the term R s here denotes the expected reward at the state s.
In the case of MRPs, we can define the expected return when starting from a state s as:
where G t is the cumulative gain as we had defined in the previous section:
Now, for maximizing the cumulative reward, the agent will try to get the most expected sum of rewards from every state it goes into. To do that we need to find the optimal value function. We will see the algorithm for doing that in the next section.
Using the Bellman equation, we decompose our value function into two separate parts, one representing the immediate reward and the other term representing the future rewards. From our previous definitions, the immediate reward is represented as R t+1 and the future rewards by where:
Let’s now unroll G t and substitute G t+1 in it:
Now, since we know that:
Using this identity we have:
And this gives us the Bellman equation for MRPs:
Now that we have a basic understanding of MRPs, we can move on to MDPs. An MDP is an MRP which also involved decisions. All the states in the environment are also Markov, hence the next state is only dependent on the current state. Formally, an MDP can be represented using where S is the state space, A is the action set, P is the state transition probability function, R is the reward function, and is the discount rate. The state transition probability function P and the reward function R are formally defined as:
We can also formally define a policy π as:
Since the states in the MDP are considered to be Markov, the MDP policies depend only on the current state, which means that the policies are stationary that is,. This means that whenever the agent falls into the same state, it will take the decision based on the same policy it had decided before. The decision function can be made stochastic so that the agent doesn’t keep on taking the same decisions and hence is able to explore the environment.
Now, since we want to use the Bellman Equation in the case of MDP, we will recover an MRP from the MDPs. Given an MDP, and a policy the state sequence S 1, S 2,… is a Markov Process (S,P) on the policy π. The state and reward sequence S1, R1, S2, R2,… is also an MRP given by where:
We can similarly formulate our reward function as:
And, since we know that the state-value function Vπ(s) of an MDP is the expected return starting from state S and then following the policy π, the value function is given as:
Also, the action-value function can be given as:
Having these values, we can again derive the Bellman expectation equation in the case of MDPs. We again start by decomposing the state-value function into immediate reward and future rewards:
And similar to the case of MRPs, the action-value function can also be decomposed as:
And as we have multiple actions from each state S and the policy defines the probability distribution over the actions, we will need to average over it to get the Bellman expectation equation:
We can also average over all the possible action-values to know how good being in a given state S is:
In the following code example we implement a simple MDP:
import numpy as npimport random
class MDP(object): """ Defines a Markov Decision Process containing:
- States, s - Actions, a - Rewards, r(s,a) - Transition Matrix, t(s,a,_s)
Includes a set of abstract methods for extended class will need to implement.
"""
def __init__(self, states=None, actions=None, rewards=None, transitions=None, discount=.99, tau=.01, epsilon=.01): """ Parameters: ----------- states: 1-D array The states of the environment
actions: 1-D array The possible actions by the agent.
rewards: 2-D array The rewards corresponding to each action at each state of the environment.
transitions: 2-D array The transition probabilities between the states of the environment.
discount: float The discount rate for the reward. """ self.s = np.array(states) self.a = np.array(actions) self.r = np.array(rewards) self.t = np.array(transitions)
self.discount = discount self.tau = tau self.epsilon = epsilon
# Value iteration will update this self.values = None self.policy = None
def getTransitionStatesAndProbs(self, state, action): """ Returns the list of transition probabilities """ return self.t[state][action][:]
def getReward(self, state): """ Gets reward for transition from state->action->nextState. """ return self.r[state]
def takeAction(self, state, action): """ Take an action in an MDP, return the next state
Chooses according to probability distribution of state transitions, contingent on actions. """ return np.random.choice(self.s, p=self.getTransitionStatesAndProbs(state, action))
def valueIteration(self): """ Performs value iteration to populate the values of all states in the MDP.
"""
# Initialize V_0 to zero self.values = np.zeros(len(self.s)) self.policy = np.zeros([len(self.s), len(self.a)])
policy_switch = 0
# Loop until convergence while True:
# To be used for convergence check oldValues = np.copy(self.values)
for i in range(len(self.s)-1):
self.values[i] = self.r[i] + np.max(self.discount * \ np.dot(self.t[i][:][:], self.values))
# Check Convergence if np.max(np.abs(self.values - oldValues)) <= self.epsilon: break
def extractPolicy(self): """ Extract policy from values after value iteration runs. """
self.policy = np.zeros([len(self.s),len(self.a)])
for i in range(len(self.s)-1):
state_policy = np.zeros(len(self.a))
state_policy = self.r[i] + self.discount* \ np.dot(self.t[i][:][:], self.values)
# Softmax the policy state_policy -= np.max(state_policy) state_policy = np.exp(state_policy / float(self.tau)) state_policy /= state_policy.sum()
self.policy[i] = state_policy
def simulate(self, state):
""" Runs the solver for the MDP, conducts value iteration, extracts policy, then runs simulation of problem.
NOTE: Be sure to run value iteration (solve values for states) and to extract some policy (fill in policy vector) before running simulation """
# Run simulation using policy until terminal condition met
while not self.isTerminal(state):
# Determine which policy to use (non-deterministic) policy = self.policy[np.where(self.s == state)[0][0]] p_policy = self.policy[np.where(self.s == state)[0][0]] / \ self.policy[np.where(self.s == state)[0][0]].sum()
# Get the parameters to perform one move stateIndex = np.where(self.s == state)[0][0] policyChoice = np.random.choice(policy, p=p_policy) actionIndex = np.random.choice(np.array(np.where(self.policy[state][:] == policyChoice)).ravel())
# Take an action, move to next state nextState = self.takeAction(stateIndex, actionIndex)
print "In state: {}, taking action: {}, moving to state: {}".format( state, self.a[actionIndex], nextState)
# End game if terminal state reached state = int(nextState) if self.isTerminal(state):
# print "Terminal state: {} has been reached. Simulation over.".format(state) return stateUsing this MDP, we can now code up a simple betting game:
class BettingGame(MDP):
""" Defines the Betting Game:
Problem: A gambler has the chance to make bets on the outcome of a fair coin flip. If the coin is heads, the gambler wins as many dollars back as was staked on that particular flip - otherwise the money is lost. The game is won if the gambler obtains $100, and is lost if the gambler runs out of money (has 0$). This gambler did some research on MDPs and has decided to enlist them to assist in determination of how much money should be bet on each turn. Your task is to build that MDP!
Params:
pHead: Probability of coin flip landing on heads - Use .5 for fair coin, otherwise choose a bias [0,1]
"""
def __init__(self, pHeads=.5, discount=.99, epsilon=.1, tau=.0001):
MDP.__init__(self,discount=discount,tau=tau,epsilon=epsilon) self.pHeads = pHeads self.setBettingGame(pHeads) self.valueIteration() self.extractPolicy()
# Edge case fix: Policy for $1 self.policy[1][:] = 0 self.policy[1][1] = 1.0
def isTerminal(self, state): """ Checks if MDP is in terminal state. """ return True if state is 100 or state is 0 else False
def setBettingGame(self, pHeads=.5):
""" Initializes the MDP to the starting conditions for the betting game.
Params: pHeads = Probability that coin lands on head - .5 for fair coin, otherwise choose bias
"""
# This is how much we're starting with self.pHeads = pHeads
# Initialize all possible states self.s = np.arange(102)
# Initialize possible actions self.a = np.arange(101)
# Initialize rewards self.r = np.zeros(101) self.r[0] = -5 self.r[100] = 10
# Initialize transition matrix temp = np.zeros([len(self.s),len(self.a),len(self.s)])
# List comprehension using tHelper to determine probabilities for each index self.t = [self.tHelper(i[0], i[1], i[2], self.pHeads) for i,x in np.ndenumerate(temp)] self.t = np.reshape(self.t, np.shape(temp))
for x in range(len(self.a)):
# Remember to add -1 to value it, and policy extract # Send the end game states to the death state! self.t[100][x] = np.zeros(len(self.s)) self.t[100][x][101] = 1.0 self.t[0][x] = np.zeros(len(self.s)) self.t[0][x][101] = 1.0
def tHelper(self, x, y, z, pHeads):
""" Helper function to be used in a list comprehension to quickly generate the transition matrix. Encodes the necessary conditions to compute the necessary probabilities.
Params: x,y,z indices pHeads = probability coin lands on heads
"""
# If you bet no money, you will always have original amount if x + y is z and y is 0: return 1.0
# If you bet more money than you have, no chance of any outcome elif y > x and x is not z: return 0
# If you bet more money than you have, returns same state with 1.0 prob. elif y > x and x is z: return 1.0
# Chance you lose elif x - y is z: return 1.0 - pHeads
# Chance you win elif x + y is z: return pHeads
# Edge Case: Chance you win, and winnings go over 100 elif x + y > z and z is 100: return pHeads
else: return 0
return 0In this chapter, we started with a short introduction to Reinforcement Learning. We talked about agents, rewards and our learning goals in reinforcement learning. In the next section, we introduced MRP which is one of the main concepts underlying MDP. Having an understanding of MRP we next introduce the concepts of MDP along with a code example.