-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcliffwalking.py
208 lines (162 loc) · 5.27 KB
/
cliffwalking.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import gymnasium as gym
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
from gymnasium.wrappers import RecordEpisodeStatistics
from collections import defaultdict
from tqdm import trange
# from plotting import plot_results
env = gym.make("CliffWalking-v0")
class QLearner:
def __init__(
self,
learning_rate: float,
initial_epsilon: float,
epsilon_decay: float,
final_epsilon: float,
discount_factor: float = 0.95,
):
self.lr = learning_rate
self.epsilon = initial_epsilon
self.epsilon_decay = epsilon_decay
self.final_epsilon = final_epsilon
self.gamma = discount_factor
self.q_vals = defaultdict(lambda: [0] * env.action_space.n)
self.training_error = []
def epsilon_greedy(self, state):
if np.random.random() < self.epsilon:
return env.action_space.sample()
else:
return np.argmax(self.q_vals[state])
def greedy(self, state):
return np.argmax(self.q_vals[state])
def learn(self, state, action, reward, terminated, next_state):
next_q_val = (not terminated) * max(self.q_vals[next_state])
temporal_difference = (
reward + self.gamma * next_q_val - self.q_vals[state][action]
)
self.q_vals[state][action] += self.lr * temporal_difference
self.training_error.append(temporal_difference)
def decay_epsilon(self):
self.epsilon = max(self.final_epsilon, self.epsilon - self.epsilon_decay)
class SARSALearner:
def __init__(
self,
learning_rate: float,
initial_epsilon: float,
epsilon_decay: float,
final_epsilon: float,
discount_factor: float = 0.95,
):
self.lr = learning_rate
self.epsilon = initial_epsilon
self.epsilon_decay = epsilon_decay
self.final_epsilon = final_epsilon
self.gamma = discount_factor
self.q_vals = defaultdict(lambda: [0] * env.action_space.n)
self.training_error = []
def epsilon_greedy(self, state):
if np.random.random() < self.epsilon:
return env.action_space.sample()
else:
return np.argmax(self.q_vals[state])
def greedy(self, state):
return np.argmax(self.q_vals[state])
def learn(self, state, action, reward, terminated, next_state):
next_action = self.epsilon_greedy(next_state)
next_q_val = (not terminated) * self.q_vals[next_state][next_action]
temporal_difference = (
reward + self.gamma * next_q_val - self.q_vals[state][action]
)
self.q_vals[state][action] += self.lr * temporal_difference
self.training_error.append(temporal_difference)
def decay_epsilon(self):
self.epsilon = max(self.final_epsilon, self.epsilon - self.epsilon_decay)
# hyperparameters
learning_rate = 0.1
n_episodes = 1_000
start_epsilon = 1
epsilon_decay = 0.05
final_epsilon = 0.1
discount_factor = 0.95
Qagent = QLearner(
learning_rate,
start_epsilon,
epsilon_decay,
final_epsilon,
discount_factor,
)
Sagent = SARSALearner(
learning_rate,
start_epsilon,
epsilon_decay,
final_epsilon,
discount_factor,
)
# train Q
envQ = RecordEpisodeStatistics(env, deque_size=n_episodes)
for episode in trange(n_episodes):
state, info = envQ.reset()
done = False
while not done:
action = Qagent.epsilon_greedy(state)
next_state, reward, terminated, truncated, info = envQ.step(action)
Qagent.learn(state, action, reward, terminated, next_state)
Qagent.decay_epsilon()
done = terminated or truncated
state = next_state
envQ.close()
# simulation_results = pd.DataFrame({"run": run_history})
# train SARSA
envS = RecordEpisodeStatistics(env, deque_size=n_episodes)
for episode in trange(n_episodes):
state, info = envS.reset()
done = False
while not done:
action = Sagent.epsilon_greedy(state)
next_state, reward, terminated, truncated, info = envS.step(action)
Sagent.learn(state, action, reward, terminated, next_state)
Sagent.decay_epsilon()
done = terminated or truncated
state = next_state
envS.close()
# plotting
# plot training performance
returns = envQ.return_queue
plt.plot(returns)
plt.xlabel("Episodes (Q-Learning agent)")
plt.ylabel("Returns")
plt.show()
returns = envS.return_queue
plt.plot(returns)
plt.xlabel("Episodes (SARSA agent)")
plt.ylabel("Returns")
plt.show()
# plot training error
plt.plot(Qagent.training_error)
plt.xlabel("Episodes (Q-Learning agent)")
plt.ylabel("Training Error")
plt.show()
plt.plot(Sagent.training_error)
plt.xlabel("Episodes (SARSA agent)")
plt.ylabel("Training Error")
plt.show()
# evaluate agent
env = gym.make("CliffWalking-v0", render_mode="human")
state, _ = env.reset()
done = False
while not done:
action = Qagent.greedy(state)
next_state, _, terminated, truncated, _ = env.step(action)
done = terminated or truncated
state = next_state
env.close()
env = gym.make("CliffWalking-v0", render_mode="human")
state, _ = env.reset()
done = False
while not done:
action = Sagent.greedy(state)
next_state, _, terminated, truncated, _ = env.step(action)
done = terminated or truncated
state = next_state
env.close()