-
Notifications
You must be signed in to change notification settings - Fork 1
/
pong.py
226 lines (186 loc) · 7.97 KB
/
pong.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
"""
Reinforcement Learning for Pong!
More Info : https://github.com/mlitb/pong
Authors:
1. Faza Fahleraz https://github.com/ffahleraz
2. Nicholas Rianto Putra https://github.com/nicholaz99
3. Abram Perdanaputra https://github.com/abrampers
"""
import os
import gym
import argparse
import numpy as np
import pickle as pkl
from typing import Dict, List
# Type shorthands
Model = Dict[np.ndarray, np.ndarray]
EpisodeBuffer = Dict[str, List]
Gradient = Dict[str, np.ndarray]
def preprocess(frame: np.ndarray) -> np.ndarray:
"""
Preprocess 210x160x3 uint8 frame into 6400 (80x80) 1D float vector.
"""
frame = frame[35:195] # crop
frame = frame[::2,::2,0] # downsample by factor of 2
frame[frame == 144] = 0 # erase background
frame[frame == 109] = 0 # erase background
frame[frame != 0] = 1 # set paddles and ball to 1
return frame.astype(np.float).ravel()
def relu(x: np.ndarray) -> np.ndarray:
y = np.copy(x)
y[x < 0] = 0
return y
def relu_prime(x: np.ndarray) -> np.ndarray:
y = np.zeros_like(x)
y[x > 0] = 1
return y
def sigmoid(x: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-x))
def forward(x: np.ndarray, model: Model, episode_buffer: EpisodeBuffer) -> float:
"""
Do a forward pass to get the probability of moving the paddle up.
"""
ph = np.dot(model['wh'], x)
h = relu(ph)
py = np.dot(model['wo'], h)
y = sigmoid(py)
episode_buffer['x'].append(x)
episode_buffer['ph'].append(ph)
episode_buffer['h'].append(h)
episode_buffer['y'].append(y)
return y
def backward(model: Model, episode_buffer: EpisodeBuffer, episode_reward: np.ndarray) -> Gradient:
"""
Do a backward pass to get the gradient of the network weights.
"""
y_true = np.vstack(episode_buffer['y_true'])
y = np.vstack(episode_buffer['y'])
h = np.vstack(episode_buffer['h'])
ph = np.vstack(episode_buffer['ph'])
x = np.vstack(episode_buffer['x'])
# the objective here is to maximize the log likelihood of y_true being chosen
# (given the probability y) (see http://cs231n.github.io/neural-networks-2/#losses
# section 'Attribute classification' for more details), so the gradient of the
# log likelihood function on py should be:
grad_py = y_true - y
adv_grad_py = grad_py * episode_reward # advantage based on reward
grad_wo = np.dot(adv_grad_py.T, h)
grad_h = np.dot(adv_grad_py, model['wo'])
grad_ph = relu_prime(ph) * grad_h
grad_wh = np.dot(grad_ph.T, x)
return {'wh': grad_wh, 'wo': grad_wo}
def normal_discounted_reward(episode_buffer: EpisodeBuffer, discount_factor: float) -> float:
"""
Calculate the normalized and discounted reward for the current episode.
"""
reward = episode_buffer['reward']
discounted_reward = np.zeros((len(reward), 1))
future_reward = 0
for i in range(len(reward) - 1, -1, -1):
if reward[i] != 0: # reset future reward after each score
future_reward = 0
discounted_reward[i][0] = reward[i] + discount_factor * future_reward
future_reward = discounted_reward[i][0]
discounted_reward -= np.mean(discounted_reward)
discounted_reward /= np.std(discounted_reward)
return discounted_reward
def main(load_fname: str, save_dir: str, render: bool) -> None:
"""
Main training loop.
"""
batch_size = 10
input_layer_size = 6400
hidden_layer_size = 200
learning_rate = 1e-3
discount_factor = .99
rmsprop_decay = .90
rmsprop_smoothing = 1e-5
if load_fname is not None:
saved = pkl.load(open(load_fname, 'rb'))
model = saved['model']
moving_grad_rms = saved['moving_grad_rms']
episode_number = saved['episode_number']
print('Resuming saved model in \'{}\'.'.format(load_fname))
else:
model = {
'wh': np.random.randn(hidden_layer_size, input_layer_size) / np.sqrt(input_layer_size),
'wo': np.random.randn(1, hidden_layer_size) / np.sqrt(hidden_layer_size),
}
moving_grad_rms = {
'wh': np.zeros_like(model['wh']),
'wo': np.zeros_like(model['wo']),
}
episode_number = 0
batch_gradient_buffer = {
'wh': np.zeros_like(model['wh']),
'wo': np.zeros_like(model['wo']),
}
batch_rewards = []
env = gym.make('Pong-v0')
while True:
observation = env.reset()
prev_frame = np.zeros(input_layer_size)
episode_done = False
timestep = 0
episode_buffer = {
'x': [], # input vector
'ph': [], # product of hidden layer
'h': [], # activation of hidden layer
'y': [], # activation of output layer, probability of taking action 'UP'
'y_true': [], # fake label
'reward': [] # rewards
}
while not episode_done:
if render:
env.render()
# generate input vector
frame = preprocess(observation)
x = frame - prev_frame
prev_frame = frame
# forward pass
y = forward(x, model, episode_buffer)
action, y_true = (2, 1.0) if np.random.uniform() < y else (5, 0.0)
episode_buffer['y_true'].append(y_true)
# perform action and get new observation
observation, reward, episode_done, info = env.step(action)
episode_buffer['reward'].append(reward)
timestep += 1
if episode_done:
# backward pass
episode_reward = normal_discounted_reward(episode_buffer, discount_factor)
gradient = backward(model, episode_buffer, episode_reward)
for key in model:
batch_gradient_buffer[key] += gradient[key]
# bookeeping
batch_rewards.append(sum(episode_buffer['reward']))
episode_number += 1
# training info
# print('Episode: {}, rewards: {}'.format(episode_number, sum(episode_buffer['reward'])))
# parameter update (rmsprop)
if episode_number % batch_size == 0:
for key in model:
moving_grad_rms[key] = rmsprop_decay * moving_grad_rms[key] + \
(1 - rmsprop_decay) * (batch_gradient_buffer[key] ** 2)
model[key] += batch_gradient_buffer[key] * learning_rate / \
(np.sqrt(moving_grad_rms[key]) + rmsprop_smoothing)
batch_gradient_buffer[key] = np.zeros_like(model[key])
# training info
print('Batch: {}, avg episode rewards: {}'.format(episode_number // batch_size,
sum(batch_rewards) / len(batch_rewards)))
batch_rewards = []
# save model
if episode_number % 50 == 0 and save_dir is not None:
if not os.path.exists(save_dir):
os.makedirs(save_dir)
save_fname = os.path.join(save_dir, 'save_{}.pkl'.format(episode_number))
pkl.dump({'model': model, 'moving_grad_rms': moving_grad_rms,
'episode_number': episode_number}, open(save_fname, 'wb'))
print('Model saved to \'{}\'!'.format(save_fname))
env.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Train an RL agent to play the mighty game of Pong.')
parser.add_argument('-l', '--load', action="store", default=None, help='path to the saved model to load from')
parser.add_argument('-s', '--save', action="store", default=None, help='path to the folder to save model')
parser.add_argument('-r', '--render', action="store_true", default=False, help='whether to render the environment or not')
args = parser.parse_args()
main(load_fname=args.load, save_dir=args.save, render=args.render)