For model free prediction, we have
- An environment that can be represented by a MDP
- But we dont know the MDP
- But we still want to be able to compute the value functiion for this MDP.
———Model free prediction methods to discover value function ———–
| |
V V
Monte Carlo Learning Temporal Difference Learning Sample a full trajectory and estimate Go one step and estimate return
the value by sample return. (more efficient in practice)
| |
V V
TD($\lambda$)
unification for any number of steps.
- In previous chapters, given a policy, we solved for value function for a known MDP. This is called policy evaluation.
- In this lecture, we will estimate the value function of an unknown MDP for a given poliy.
- In the next lecture, we will find the policy that the model free prediction estimates
MONTE CARLO POLICY EVALUATION
- Only works for episodic learning, ie, episodes must always terminate.
- Sample full trajectories, and average sample returns, under the policy \pi.
- Sampled trajectory is:
$S1 , A1 , R2 , S2 , A2 , R3 ,…, S_{T−1} , A_{T−1} , R_T , S_T \sim \pi $ (ie, sampled from a policy)
where $S_T$ is terminal and $A_t \sim π(⋅∣S_t)$
- Sample return for a policy \pi from the time step t onwards is
$G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \ldots + \gamma^{T-t-1} R_T$
- Expected return for a policy \pi from the time step t onwards is
$v_\pi (S) = E_\pi [G_t | S_t = S ]$
MC estimates this expectation using a sample average, denoted .
- Empirical mean return for a policy \pi from the time step t onwards is the average of many sample returns.
MC can be done in two ways: First visit and every visit. The trick is to do it without “rewinding.”
Example for first visit / every visit MC: Consider the episodic MDP: In the pseudocode below:
- first_visit_mc = 1 → first-visit MC policy evaluation.
- first_visit_mc = 0 → every-visit MC policy evaluation.
For every state x:
V(x) ← 0
N(x) ← 0
sum(x) ← 0
first_visit_mc =1 # 0 if every visit mc.
Repeat for many episodes {
state ← chose a start state randomly
episode ← empty list
# Generate one complete episode
While state is not final: {
Choose action according to policy π
Observe next_state and reward(state, next state) from the environment
Append ( state, reward(state, next_state) ) to episode
state ← next_state
}
# Calculate returns backwards
G ← 0
For t from last step of episode down to first step {
(state, reward) ← episode[t]
G ← reward + G # γ = 1
If (first_visit_mc = 0) OR ( state does not appear among the states of the episode at indices 0 through t−1) {
sum(state) ← sum(state) + G
N(state) ← N(state) + 1
}
}
}
for every state x
if N(x)>0
V(x) ← sum(x)/N(x)
Note that
- Every state, including terminal states, starts with \(V(x)=0\).
- The episode stores the state before each transition, so the terminal state is never added as a state to update.
- Therefore, terminal-state values remain zero.
The reward for entering a terminal state is still included in the return. A terminal state has value zero because there are no further rewards after reaching it.
MONTE CARLO POLICY EVALUATION EXAMPLE: BLACKJACK
Simplified of Blackjack from David Silver
Only one player and one dealer. No double downs or splits. There is no choice of bet size, but there are three outcomes: win, draw, and loss.
- Card values: 2–10 have their face values; J, Q, K count as 10. An ace counts as 11 when possible without busting, otherwise as 1.
- Initial deal: In the standard textbook setup, both receive two cards; the player sees only one of the dealer’s cards.
- Player actions: Only:
- HIT: Receive another card. Busting ends the episode with reward ; otherwise the immediate reward is .
- STAY: Stop drawing and let the dealer finish. No splitting or doubling.
If the player’s hand is below 12, he must automatically hit. Decisions are therefore restricted to totals 12–21.
- Dealer actions: In the standard Sutton–Barto version, the dealer hits below 17 and stays on 17 or above, including soft 17.
- Result: If the player has not busted, a dealer bust or a higher player total gives ; equal totals give ; a lower player total gives . No variable betting is involved.
The RL state is: (player total (from 12 to 21), dealer’s visible card, do the player have a usable ace?) =10x10x2 = 200 states
the player total includes all cards currently in the hand, including cards received through hits.
An ace counts as 11 if that does not cause a bust; otherwise, 1.
If the player holds an ace, this will complicate the future calculation. Assume the player holds a 14. If this is an A+3, and if he hits a K, then he may count A=1 and keep his hand at 14, remaining in the game. But if he holds 9+5, hitting a K will throw him to 24, busting him.
This is precisely why the current total alone is insufficient to describe the state: we must also record whether the player has a usable ace.
Note that how we draw cards during hits matter. Consider the state (18,7,0). If we draw without replacement, (18, 7, 0) does not contain enough information to be a Markov state. The two player hands,
remove different cards from the deck. Consequently, the probabilities of the next card during a hit will differ, despite the player is playing from the same recorded state. Drawing with replacement will remove this problem. In that case (18,7,0) will be a markov state. With replacement, previous draws do not change future card probabilities. The three-component representation is then sufficient for the simplified game.
MC Policy evaluation pseudocode for simplified Blackjack
Here is first-visit MC evaluation of Silver’s policy:
It ignores both the dealer’s visible card and whether the player has a usable ace. Those variables still affect the value of the state, even though this policy does not use them to choose an action.
Use independent card draws with replacement, so the 200-state representation is Markov. Set .
State = (player total, dealer’s visible card, usable ace?)
======================code==============================
For every state s:
V(s) ← 0
N(s) ← 0
Repeat for many episodes:
Deal two cards to the player
Deal two cards to the dealer, one visible
# Automatically hit below 12
While Total(player) < 12:
Give player another card
VisitedStates ← empty list
# Player’s turn
Loop:
s ← ( Total(player), dealer’s visible card, HasUsableAce(player) )
append s to VisitedStates
If Total(player) ≥ 20:
Break # STAY
Give player another card # HIT
If Total(player) > 21:
Break # Player busts
# Determine the episode’s final reward
If Total(player) > 21:
final_reward ← −1
Else:
# Dealer hits below 17 and stays on both hard 17 and soft 17
While Total(dealer) < 17:
Give dealer another card
If Total(dealer) > 21:
final_reward ← +1
Else if Total(player) > Total(dealer):
final_reward ← +1
Else if Total(player) = Total(dealer):
final_reward ← 0
Else:
final_reward ← −1
# First-visit MC evaluation
Seen ← empty set
For each state s in VisitedStates, in chronological order:
If s is not in Seen:
Add s to Seen
G ← final_reward
N(s) ← N(s) + 1
V(s) ← V(s) + [G − V(s)] / N(s)
#returns the value of the hand, taking into account the ace.
Total(hand):
total ← sum of card values, counting every ace as 1
If hand contains an ace AND total + 10 ≤ 21:
total ← total + 10
Return total
# returns true or false.
# A usable ace can be counted as 11, without making the hand exceed 21.
# The case in which the player has two aces is also covered. The code first counts both aces as 1: 1+1=2.
#Since 2+10 <= 21, it adds 10 once, effectively counting one ace as 11:
HasUsableAce(hand):
total ← sum of card values, counting every ace as 1
Return (hand contains an ace AND total + 10 ≤ 21)
=======================end of code====================================
Here every visited state has the same sampled return:
because intermediate rewards are zero and . Thus no backward return calculation is necessary.
For every-visit MC, simply remove the “Seen test” and update on every recorded visit.
This pseudocode uses the simplified total-comparison game: an initial two-card 21 has no special priority or bonus.
The results can be printed as a two 3D plots: player total (from 12 to 21), dealer’s visible card (A-10) -> value (-1,…,1) for usable ace and no usable ace. Note that the “usable ace” plot is more noisy as that case is rarer.
APPENDIX: FULL RULES OF BLACKJACK
There is a dealer and 1-7 players.
Each player plays against the dealer. Players do not play against each other.
Cards 2-10 scored their face value. J, Q, K are 10. An ace counts as 11 if this does not cause a bust; otherwise it counts as 1. Its value can change when additional cards are drawn.
An ace and a J, Q , K or 10 is called a blackjack (with some exceptions listed below). Note that blackjack can only be formed in the original two cards.
Other 21’s (10+7+4) is not counted as a blackjack.
- Every player makes a bet and is given two open cards. The dealer gets one open and one closed card.
- Any player whose cards sum to exactly 21 (happens when a player has a blackjack) stops playing and awaits the dealer’s result. The rest remain in the game.
- Dealer blackjack check: In the common American version, the dealer checks if he has a blackjack before players act when his open card is an ace or ten-value card. If the dealer has blackjack, player blackjacks push and all other hands lose.
- After the cards are distributed, The first player—the one on the dealer’s left—plays his entire hand. He can STAY, DOUBLE DOWN, SPLIT, HIT.
- STAY: Do nothing and keep the current total. The hand’s turn ends, and he turn passes to the next hand (due to splits, a player may have more than one hand. When all hands od a player ends, the game passes to the next player in table order. )
- DOUBLE DOWN: Immediately after receiving his first two cards, the player can double his original bet. After that, he is given one more card by the dealer. If his hand sums to 21 he stops and awaits the dealer’s result, if it exceeds 21, he loses, or if he remains below 21, he STAYS.
Some tables restrict which two-card totals may be doubled.
- SPLIT: If the first two cards form an eligible pair, such as two 7s, the player may SPLIT them, forming two hands. He also places an additional bet equal to the original bet.Then the dealer gives Hand 1 another card. The player plays that hand until he finishes. Then the dealer gives Hand 2 another card, and the player plays that hand.
Each hand is played separately, ie, the player may DOUBLE DOWN or HIT on any of the hands. If any of the newly formed hands form a pair again, he can SPLIT them again.
Splits are very complicated, and each casino has its own rules.
Some casinos do not allow DOUBLING DOWN after SPLIT or SPLITting after SPLIT. When resplitting is allowed, the table limits the total number of hands.
Split aces are usually an exception: Each split ace normally receives exactly one additional card automatically. No further hits or doubling downs are allowed..
An ace plus a ten-value card obtained after splitting normally counts as ordinary 21, not blackjack.
- HIT: a player may ask for a single additional card. After that
- If his cards sum to exactly 21 he stops and awaits the dealer’s result.
- If his cards cards sum to more than 21 automatically loses.
- He may HIT as many times as he likes, as long as his total is below 21, or he chooses to STAY..
- If the player hasnt lost, he may choose to stop hitting and STAYS
- As soon as the first hand STAYS, reaches 21, loses or doubles down, the turn passes to the next hand on the table order. That hand also plays exactly like the first hand, and as soon as he STAYS, reaches 21, doubles down or loses, it is the turn of the next hand on the table order. This goes on till all hand are played. Recall again that due to splits a player may have many hands, and the game does not progree to the next player unless all the hands of the current player are finished.
- Then it is the dealer’s turn. Dealer opens his closed card. If his hand is
- 16 or less: Must hit.
- 17 or more: Must stand, except that some casinos require hitting with soft 17—a total of 17 with an ace counted as 11. If he hits with soft 17, he can use his ace as 1 later.
- More than 21: The dealer busts. All players who have not already busted win.
If the dealer does not bust, each remaining hand is compared with the dealer’s:
- Higher total wins.
- Lower total loses.
- Equal totals normally produce a push: the player’s bet is returned.
A two-card blackjack—an ace plus a ten-value card—beats an ordinary 21 made with three or more cards. Players who already busted lose even if the dealer later busts.