-
Notifications
You must be signed in to change notification settings - Fork 0
/
monte_carlo.py
76 lines (63 loc) · 1.47 KB
/
monte_carlo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import numpy as np;
from grid_world import standard_grid, negative_grid
from iterative_policy_evaluation import print_values, print_policy
SMALL_ENOUGH = 1e-3
GAMMA = 0.9
ALL_POSSIBLE_ACTIONS = ('U', 'D', 'L', 'R')
def play_game(grid, policy):
start_states = list(grid.actions.keys())
start_idx = np.random.choice(len(start_states))
grid.set_state(start_states[start_idx])
s = grid.current_state()
states_and_rewards = [(s, 0)]
while not grid.game_over():
a = policy[s]
r = grid.move(a)
s = grid.current_state()
states_and_rewards.append((s, r))
G = 0
states_and_returns = []
first = True
for s, r in reversed(states_and_rewards):
if first:
first = False
else:
states_and_returns.append((s, G))
G = r + GAMMA * G
states_and_returns.reverse()
return states_and_returns
if __name__ == '__main__':
grid = standard_grid()
print("rewards:")
print_values(grid.rewards, grid)
policy = {
(2, 0): 'U',
(1, 0): 'U',
(0, 0): 'R',
(0, 1): 'R',
(0, 2): 'R',
(1, 2): 'R',
(2, 1): 'R',
(2, 2): 'R',
(2, 3): 'U',
}
V = {}
returns = {}
states = grid.all_states()
for s in states:
if s in grid.actions:
returns[s] = []
else:
V[s] = 0
for t in range(100):
states_and_returns = play_game(grid, policy)
seen_states = set()
for s, G in states_and_returns:
if s not in seen_states:
returns[s].append(G)
V[s] = np.mean(returns[s])
seen_states.add(s)
print("Values:")
print_values(V, grid)
print("Policy:")
print_policy(policy, grid)