AIMA chapter 17 is about sequential decision problems where the agent’s utility depends on a sequence of decisions. We will implement the key concepts using R for the AIMA 3x4 grid world example.
Note that the code in this notebook defines explicit functions matching the textbook definitions and is for demonstration purposes only. Efficient implementations for larger problems use fast vector multiplications instead.
2 Markov Decision Processes
MDPs are sequential decision problems with
a fully observable, stochastic environment,
a Markovian transition model, and
additive rewards.
MDPs are defined by:
A set of states \(S\) with an initial state \(s_0\).
A set of available \(\mathrm{actions}(s)\) in each state.
A transition model \(P(s'|s,a)\) to define how we move between states depending on actions.
A reward function \(R(s, a, s')\) defined on state transitions and the actions taken.
A policy\(\pi = \{\pi(s_0), \pi(s_1), \dots\}\) defines for each state which action to take. If we assume that under policy \(\pi\), the agent will go through the state sequence \(s_0, s_1, ..., s_\infty\), then the expected utility of being in state \(s_0\) can be calculated as a sum. To incorporate that earlier rewards are more important, a discount factor \(\gamma\) is used.
The goal of solving a MDP is to find an optimal policy that maximizes the expected future utility.
\(\pi^*(s) = \mathrm{argmax}_\pi U^\pi(s)\) for all \(s \in S\)
3 The 4x3 Grid World Example
The used example is the simple 4x3 grid world described in AIMA Figure 12.1 and used again in 22.1 as:
AIMA Figure 17.1: (a) A simple, stochastic \(4 \times 3\) environment that presents the agent with a sequential decision problem. (b) Illustration of the transition model of the environment: the “intended” outcome occurs with probability 0.8, but with probability 0.2 the agent moves at right angles to the intended direction. A collision with a wall results in no movement. Transitions into the two terminal states have reward +1 and -1, respectively, and all other transitions have a reward of -0.04.
In the following, we implement states, actions, the reward function,and the transition model. We also show how to represent a policy and how to estimate the expected utility using simulation.
The MDP will be defined as the following global variables/functions:
S: set of states.
A: set of actions.
actions(s): returns the available actions for state \(s\).
P(sp, s, a): a function returning the transition probability \(P(s' | s, a)\).
R(s, a, s_prime): reward function for the transition from \(s\) to \(s`\) with action a.
Policies are represented as:
Deterministic policies are a vector with the action for each state.
Stochastic policies are a matrix with probabilities where each row is a state and the columns are the actions
Other useful functions:
sample_transition(s, a): returns a \(s'\) sampled using the transition model.
simulate_utilities(pi, s0 = 1, N = 1000, max_t = 100): Estimates the utility of following policy \(\pi\), starting \(N\) episodes in state \(s_0\). The maximal episode length is max_t to ensure that the function finishes also for policies that do not lead to a terminal state.
3.1 States
We define the atomic state space \(S\) by labeling the states \(1, 2, ...\). We convert coordinates (rows, columns) to the state label.
# I use capitalized variables as global constantsCOLS <-4ROWS <-3S =seq_len(ROWS * COLS)LAYOUT <-matrix(S, nrow = ROWS , ncol = COLS)LAYOUT
The complete set of actions is \(A = \{\mathrm{'Up', 'Right', 'Down', 'Left', 'None'}\}\). Not all actions are available in every state. Also, action None is added as the only possible action in an absorbing state.
\(P(s' | s, a)\) is the probability of going from state \(s\) to \(s'\) by when taking action \(a\). We will create a matrix \(P_a(s' | s)\) for each action.
calc_transition <-function(s, action) { action <-match.arg(action, choices = A)if(length(s) >1) return(t(sapply(s, calc_transition, action = action)))# deal with absorbing and illegal stateif(s ==11|| s ==12|| s ==5|| action =='None') { P <-rep(0, length(S)) P[s] <-1return(P) } action_to_delta <-list('Up'=c(+1, 0),'Down'=c(-1, 0),'Right'=c(0, +1),'Left'=c(0, -1) ) delta <- action_to_delta[[action]] dr <- delta[1] dc <- delta[2] rc <-s_to_rc(s) r <- rc[1] c <- rc[2]if(dr !=0&& dc !=0) stop("You can only go up/down or right/left!") P <-matrix(0, nrow = ROWS, ncol = COLS)# UP/DOWNif(dr !=0) { new_r <- r + drif(new_r > ROWS || new_r <1) new_r <- r## can't got to (2, 2)if(new_r ==2&& c ==2) new_r <- r P[new_r, c] <- .8if(c < COLS &!(r ==2& (c +1) ==2)) P[r, c +1] <- .1else P[r, c] <- P[r, c] + .1if(c >1&!(r ==2& (c -1) ==2)) P[r, c -1] <- .1else P[r, c] <- P[r, c] + .1 }# RIGHT/LEFTif(dc !=0) { new_c <- c + dcif(new_c > COLS || new_c <1) new_c <- c## can't got to (2, 2)if(r ==2&& new_c ==2) new_c <- c P[r, new_c] <- .8if(r < ROWS &!((r +1) ==2& c ==2)) P[r +1, c] <- .1else P[r, c] <- P[r, c] + .1if(r >1&!((r -1) ==2& c ==2)) P[r -1, c] <- .1else P[r, c] <- P[r, c] + .1 }as.vector(P)}
Try to go up from state 1 (this is (1,1), the bottom left corner). Note: we cannot go left so there is a .1 chance to stay in place.
Calculate transitions for each state to each other state. Each row represents a state \(s\) and each column a state \(s'\) so we get a complete definition for \(P_a(s' | s)\). Note that the matrix is stochastic (all rows add up to 1).
Create a matrix for each action.
P_matrices <-lapply(A, FUN =function(a) calc_transition(S, a))names(P_matrices) <- Astr(P_matrices)
List of 5
$ Up : num [1:12, 1:12] 0.1 0 0 0.1 0 0 0 0 0 0 ...
$ Right: num [1:12, 1:12] 0.1 0.1 0 0 0 0 0 0 0 0 ...
$ Down : num [1:12, 1:12] 0.9 0.8 0 0.1 0 0 0 0 0 0 ...
$ Left : num [1:12, 1:12] 0.9 0.1 0 0.8 0 0 0 0 0 0 ...
$ None : num [1:12, 1:12] 1 0 0 0 0 0 0 0 0 0 ...
Create a function interface for \(P(s' | s, a)\).
P <-function(sp, s, a) P_matrices[[a]][s, sp]P(2, 1, 'Up')
[1] 0.8
P(5, 4, 'Up')
[1] 0
3.4 Reward
\(R(s, a, s')\) define the reward for the transition from \(s\) to \(s'\) with action \(a\).
For the textbook example we have:
Any move costs utility (a reward of -0.04).
Going to state 12 has a reward of +1
Going to state 11 has a reward of -1.
Note that once you are in an absorbing state (11 or 12), then the problem is over and there is no more reward!
R <-function(s, a, s_prime) {## no more reward when we in 11 or 12.if(a =='None'|| s ==11|| s ==12) return(0)## transition to the absorbing states.if(s_prime ==12) return(+1)if(s_prime ==11) return(-1)## cost for each movereturn(-0.04)}R(1, 'Up', 2)
[1] -0.04
R(9, 'Right', 12)
[1] 1
R(12, 'None', 12)
[1] 0
3.5 Policy
The solution to an MDP is a policy \(\pi\) which defines which action to take in each state.
3.5.1 Deterministic Policies
It can be shown that all MPDs have an optimal deterministic policy with one action per state. We represent deterministic policies as a vector of actions. I make up a policy that always goes up and then to the right once the agent hits the top.
pi_manual <-rep('Up', times =length(S))pi_manual[c(3, 6, 9)] <-'Right'pi_manual
Stochastic policies use probabilities of actions in each state. This is useful to create policies that explore by trying different actions in the same state.
We use as simple table with probabilities where each row is a state and the columns are the actions. Here we create a random \(\epsilon\)-soft policy. Each available has at least a probability of \(\epsilon\).
We can make a deterministic policy soft.
make_policy_soft <-function(pi, epsilon =0.1) {if(!is.vector(pi))stop("pi is not a deterministic policy!") p <-matrix(0,nrow =length(S),ncol =length(A),dimnames =list(S, A))for (s in S) { p[s, actions(s)] <- epsilon /length(actions(s)) p[s, pi[s]] <- p[s, pi[s]] + (1- epsilon) } p }make_policy_soft(pi_random)
create_random_epsilon_soft_policy <-function(epsilon =0.1) {# split total randomly into n numbers that add up to total random_split <-function(n, total) {if (n ==1)return(total) bordersR <-c(sort(runif(n -1)), 1) bordersL <-c(0, bordersR[1:(n -1)]) (bordersR - bordersL) * total } p <-matrix(0,nrow =length(S),ncol =length(A),dimnames =list(S, A))for (s in S) p[s, actions(s)] <- epsilon /length(actions(s)) +random_split(n =length(actions(s)), 1- epsilon) p}set.seed(1234)pi_random_epsilon_soft <-create_random_epsilon_soft_policy()pi_random_epsilon_soft
We can directly estimate the expected utility of a state using a Monte Carlo simulation that follows the policy. For the stochastic transition model, we need to be able to sample the state \(s'\) the system transitions to when using action \(a\) in state \(s\).
We can now simulate the utility for one episode. Note that we use the cutoff max_t in case a policy does not end up in a terminal state before that.
simulate_utility <-function(pi, s0 =1, max_t =100) { s <- s0 U <-0 t <-0while (TRUE) {## get action from policy (matrix means it is a stochastic policy)if (!is.matrix(pi)) a <- pi[s]else a <-sample(A, size =1, prob = pi[s, ])## sample a transition given the action from the policy s_prime <-sample_transition(s, a)## U <- U + GAMMA ^ t *R(s, a, s_prime) s <- s_prime## reached an absorbing state?if (s ==11|| s ==12|| s ==5)break t <- t +1if (t >= max_t)break } U}
The random policy performs really poorly. It most likely always stumbles around for max_t moves at a cost of .04 each. The manually created policy should obviously do much better.
We can use simulation to estimate the expected utility for starting from each state following the policy.
This equation is called the Bellman equation resulting in an equation system with one equation per state \(s\). This system of equations is hard to solve for all \(U(s)\) values because of the nonlinear \(\max()\) operator.
Lets define a function for the expected utility of any possible action \(a\) (not just the optimal one) in a given state \(s\). This is called the (Q-function or state-action value function):
This function is convenient for solving MDPs and can easily be implemented.
Q_value <-function(s, a, U) {if(!(a %in%actions(s))) return(NA)sum(sapply( S,FUN =function(sp)P(sp, s, a) * (R(s, a, sp) + GAMMA * U[sp]) ))}
The issue is that we need to know \(U\) representing the expected utility of a state given optimal decisions is needed. Value iteration uses a simple iterative algorithm to solve this problem by successively updating Q and U.
Note that \(U(s) = \max_a Q(s, a)\) holds and we get:
The goal is to find the unique utility function \(U\) (a vector of utilities, one for each state) for the MDP and then derive the implied optimal policy \(\pi^*\).
Algorithm: Start with a \(U(s)\) vector of 0 for all states and then update (Bellman update) the vector iteratively until it converges. This procedure is guaranteed to converge to the unique optimal solution. The pseudocode from AIMA Figure 17.6.:
AIMA Figure 17.6: The value iteration algorithm for calculating utilities of states.
Stopping criterion:\(||U^\pi - U||_\infty\) is called the policy loss (i.e., the most the agent can loose by using policy \(\pi\) instead of the optimal policy \(\pi^*\) implied in \(U\)). The max-norm \(||x||_\infty\) is defined as the largest component of a vector \(x\).
It can be shown that if \(||U_{i+1} - U_i||_\infty < \epsilon(1-\gamma)/\gamma\) then \(||U_{i+1} - U||_\infty < \epsilon\). This can be used as a stopping criterion with guarantee of a policy loss of less than \(\epsilon\).
value_iteration <-function(eps, verbose =FALSE) { U_prime <-rep(0, times =length(S)) i <-1Lwhile (TRUE) {if(verbose) cat("Iteration:", i)#cat("U:", U_prime, "\n") U <- U_prime delta <-0for (s in S) { U_prime[s] <-max(sapply(actions(s),FUN =function(a)Q_value(s, a, U) )) delta <-max(delta, abs(U_prime[s] - U[s])) }if(verbose) cat(" -> delta:", delta, "\n")if (delta <= eps * (1- GAMMA) / GAMMA)break i <- i +1L }cat("Iterations needed:", i, "\n") U}
For the optimal policy, we choose in each state the action that maximizes the expected utility. This is called the maximum expected utility (MEU) policy. The action that maximizes the utility can be found using the Q-function.
\(\pi^*(s) = \mathrm{argmax}_a Q(s, a)\)
For state 1, 'Up' is the best move
sapply(A, FUN =function(a) Q_value(s =1, a, U = U))
Up Right Down Left None
0.7453082 0.6709332 0.7003082 0.7109332 NA
Calculate the Q-function for all \(S \times A\).
Q_value_vec <-Vectorize(Q_value, vectorize.args =c("s", "a"))QVs <-outer(S, A, FUN =function(s, a) Q_value_vec(s, a, U = U))colnames(QVs) <- AQVs
Up Right Down Left None
[1,] 0.7453082 0.6709332 0.7003082 0.7109332 NA
[2,] 0.8015582 0.7609332 0.7165582 0.7609332 NA
[3,] 0.8171832 0.8515582 0.7771832 0.8065582 NA
[4,] 0.6559189 0.6201941 0.6559189 0.6953082 NA
[5,] NA NA NA NA 0
[6,] 0.8671832 0.9078082 0.8671832 0.8228082 NA
[7,] 0.6325425 0.4375089 0.5934557 0.6514155 NA
[8,] 0.7002740 -0.6470776 0.4551598 0.6811416 NA
[9,] 0.9210274 0.9578082 0.7150000 0.8520548 NA
[10,] -0.7000660 0.2491324 0.4102740 0.4279249 NA
[11,] NA NA NA NA 0
[12,] NA NA NA NA 0
The optimal policy is the greedy policy that always picks the action with the largest Q-value.
Since we know that utility_opt is very close to \(U\), we can estimate the policy loss (i.e., the most the agent can loose by using \(\pi\) instead of \(\pi*\)) of the other policies given by:
\(||U^\pi - U||_\infty\)
Here is the policy loss for the manual policy. The maximum norm is the component with the largest difference. First, we calculate the absolute difference for each state.
This is slightly simpler than the general Bellman equation, since the action in each state is fixed by the policy and there is no non-linear \(\max()\) operator. For small state spaces this can be solved fast using a LP in \(O(n^3)\).
For large state spaces, we can do approximate policy evaluation by performing only a few iterations of a simplified Bellman update:
We implement here approximate policy evaluation with N iterations.
approx_policy_evaluation <-function(pi, U =NULL, N =10) {# start with all 0s if no previous U is givenif (is.null(U)) U <-rep(0, times =length(S))for (i inseq_len(N)) {for (s in S) { U[s] =sum(sapply( S,FUN =function(s_prime) {P(s_prime, s, pi[s]) * (R(s, pi[s], s_prime) + GAMMA * U[s_prime]) } )) } } U}
We will implement modified policy iteration. Modified means that we use the approximate policy evaluation.
policy_iteration <-function(N =10) { U <-rep(0, times =length(S)) pi <-create_random_deterministic_policy()while (TRUE) { U <-approx_policy_evaluation(pi, U, N) unchanged <-TRUEfor (s in S) { actns <-actions(s) a <- actns[which.max(sapply(actns, FUN =function(a) Q_value(s, a, U)))]if (Q_value(s, a, U) >Q_value(s, pi[s], U)) { pi[s] <- a unchanged <-FALSE } }if(unchanged) break } pi}
Rewriting the Bellman equations as an LP formulation requires replacing the non-linear \(\max()\) operation using additional constraints. The LP can be solved in polynomial time. In practice this is too slow for larger problems. The dynamic programming solution above is typically more efficient, but it is also restricted to small problems.
4.5 Approximate Offline Methods
Reinforcement learning is discussed in AIMA Chapter 22.