-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathtaxilearning.py
277 lines (206 loc) · 6.68 KB
/
taxilearning.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""
==========================================
Q-Learning toy sample based on OpenAI Gym.
==========================================
Source:
* https://www.learndatasci.com/tutorials/reinforcement-q-learning-scratch-python-openai-gym/
* https://github.com/GaurangSharma18/Reinforcement-Learning-Open-AI-gym---Taxi
* Sutton Book, "Reinforcement Learning"
In RL, QLearning, we want to learn a Q table, a function, for which given a
state we can check the all the different actions to determine which one has
the greater value on the Q table, and pick that one. It is very easy to
implement, works very well, but it requires a lot of episodes.
This Q table can be replaced by a neural network (as function approximator).
5x5 grid
4 destinations
4+1 passengers locations (the 4 destinations plus inside the taxi)
+---------+
|R: | : :G|
| : | : : |
| : : : : |
| | : | : |
|Y| : |B: |
+---------+
6 possible actions
0 south
1 north
2 east
3 west
4 pickup
5 dropoff
5 x 5 x 5 x 4 states
"""
import gym
import numpy as np
import random
import matplotlib.pyplot as plt
env = gym.make('Taxi-v3', render_mode="ansi").env
env.reset()
env.render()
print('Action state {}'. format(env.action_space))
print('State space {}'.format(env.observation_space))
state = env.encode(3,1,2,0) # Taxi location row and column, 2 is where the passenger is located (the second location), and 0 is where it should go.
env.s = state
env.render()
# env.P represents {action: prob, nextstate, rewards, done}
# When done is true, the episode finishes and we had succeeded.
print(env.P[state])
env.s = 328 # set environment to illustration's state
epochs = 0
penalties, reward = 0, 0
frames = [] # for animation
done = False
while (not done) and (epochs<400):
action = env.action_space.sample()
#print(f"Action: {action}")
state, reward, done, info,ext = env.step(action)
#print(f"State: {state}")
if reward == -10:
penalties += 1
# Put each rendered frame into dict for animation
frames.append({
'frame': env.render(),
'state': state,
'action': action,
'reward': reward
}
)
epochs += 1
# Let's see what is happening..... this is 100% exploration without any learning.
from time import sleep, time
def print_frames(frames):
for i, frame in enumerate(frames):
print(frame['frame'])
print(f"Timestep: {i + 1}")
print(f"State: {frame['state']}")
print(f"Action: {frame['action']}")
print(f"Reward: {frame['reward']}")
sleep(.1)
print(chr(27) + "[2J")
print_frames(frames)
print("Timesteps taken: {}".format(epochs))
print("Penalties incurred: {}".format(penalties))
# Q-Learning rule, Q(s,a) <- (1-𝛂) Q(s,a) + 𝛂 ( R + γ max_an Q(next state, an)
# Alpha is the explotation-exploration tradeoff whle gamma is the greedy-longterm term (0 is greedy)
env.reset()
# Hyperparameters
alpha = 0.1
gamma = 0.6
epsilon = 0.1
q_table = np.zeros([5 * 5 * 5 * 4 , env.action_space.n])
reward_list = []
ave_reward_list = []
tot_rewards = 0
for i in range(1, 100000):
env.reset()
done = False
state=0
while not done:
if random.uniform(0, 1) < epsilon:
action = env.action_space.sample() # Explore action space
else:
action = np.argmax(q_table[state,:]) # Exploit learned values
#print(f"Action: {action}")
next_state, reward, done, info,ext = env.step(action)
#print(f"State: {state} -> {next_state}")
old_value = q_table[state, action]
next_max = np.max(q_table[next_state,:])
new_value = (1 - alpha) * old_value + alpha * (reward + gamma * next_max)
q_table[state, action] = new_value
tot_rewards += reward
if reward == -10:
penalties += 1
# Put each rendered frame into dict for animation
frames.append({
'frame': env.render(),
'state': state,
'action': action,
'reward': reward
}
)
epochs += 1
state=next_state
# Track rewards
reward_list.append(tot_rewards)
penalties=0
tot_rewards=0
if (i+1) % 100 == 0:
ave_reward = np.mean(reward_list)
ave_reward_list.append(ave_reward)
reward_list = []
if (i+1) % 100 == 0:
print('Episode {} Average Reward: {}'.format(i+1, ave_reward))
plt.plot(100*(np.arange(len(ave_reward_list)) + 1), ave_reward_list)
plt.xlabel('Episodes')
plt.ylabel('Average Reward')
plt.title('Average Reward vs Episodes')
#plt.savefig('rewards.pdf')
#plt.close()
plt.show()
print("Training finished.\n")
"""Evaluate agent's performance after Q-learning"""
total_epochs, total_penalties = 0, 0
episodes = 100
total_penalties_optimal_list = []
for _ in range(episodes):
env.reset()
epochs, penalties, reward = 0, 0, 0
done = False
state=0
while not done:
action = env.action_space.sample()
state, reward, done, info, ext = env.step(action)
if reward == -10:
penalties += 1
epochs += 1
total_penalties += penalties
total_epochs += epochs
total_penalties_optimal_list.append(penalties)
print(f"Random Actions")
print(f"--------------")
print(f"Results after {episodes} episodes:")
print(f"Average timesteps per episode: {total_epochs / episodes}")
print(f"Average penalties per episode: {total_penalties / episodes}")
total_epochs, total_penalties = 0, 0
episodes = 100
total_penalties_random_list = []
for _ in range(episodes):
env.reset()
epochs, penalties, reward = 0, 0, 0
done = False
state=0
while not done:
action = np.argmax(q_table[state,:])
state, reward, done, info, ext = env.step(action)
if reward == -10:
penalties += 1
epochs += 1
total_penalties += penalties
total_epochs += epochs
total_penalties_random_list.append(penalties)
print(f"Optimal Policy")
print(f"--------------")
print(f"Results after {episodes} episodes:")
print(f"Average timesteps per episode: {total_epochs / episodes}")
print(f"Average penalties per episode: {total_penalties / episodes}")
plt.plot(total_penalties_random_list, label='Random Actions')
plt.plot(total_penalties_optimal_list, label='Optimal Policy')
plt.xlabel('Episodes')
plt.ylabel('Penalties')
plt.title('Penalties vs Episodes')
plt.show()
done = False
frames = [] # for animation
env.reset()
while not done:
action = np.argmax(q_table[state,:])
state, reward, done, info, ext = env.step(action)
frames.append({
'frame': env.render(),
'state': state,
'action': action,
'reward': reward
}
)
epochs += 1
print_frames(frames)