-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrainer.py
More file actions
285 lines (216 loc) · 9.31 KB
/
Copy pathtrainer.py
File metadata and controls
285 lines (216 loc) · 9.31 KB
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
278
279
280
281
282
283
284
285
import os
from time import time, sleep
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as T
from game import Game
from util import *
from IPython.display import clear_output
#########################################################################################
# Basic Trainer
#########################################################################################
class Trainer:
def __init__(self):
return
def train(self, game, agent):
pass
def eval(self, game, agent, n_games, n_print, delay):
"""Train an agent over n_games"""
wins = 0
stop_choices = [0] * game.n_idx
agent.eval()
# Iterate through games
for i in tqdm(range(n_games), leave=False):
# Reset game and agent
game.reset()
agent.reset()
self.params = self.reset(game)
# Iterate through game
while True:
action = agent.getAction(self.params)
if action == 0:
stop_choices[self.params['idx']] += 1
self.params['idx'], self.params['val'], self.params['reward'], self.params['game_status'] = game.step(action)
if self.params['game_status']:
wins += game.win
break
if (i % n_print == 0) & (i > 0):
sleep(delay)
clear_output()
print("EVAL PCT: {:.2} |\t VICTORY PERCENTAGE: {:.2}".format(i/n_games, wins/i))
clear_output()
print("EVAL COMPLETE |\t FINAL VICTORY PERCENTAGE: {:.2}".format(wins/n_games))
return wins/n_games, stop_choices
def reset(self, game):
return {"lo":game.lo,
"hi":game.hi,
"n_idx":game.n_idx,
"replace":game.replace,
"idx":0,
"action":None,
"val":game.val,
"game_status":False}
#########################################################################################
# Q-Learner Trainer
#########################################################################################
class QTrainer(Trainer):
def __init__(self):
super().__init__()
return
def train(self, game, agent, n_games, n_print, delay):
"""Train an agent over n_games"""
wins, games = 0, 0
agent.train()
# Iterate through games
for i in tqdm(range(n_games), leave=False):
#Reset game and agent
game.reset()
agent.reset()
self.params = self.reset(game)
self.params['game_i'] = i
# Iterate through game
while True:
self.params['action'] = agent.getAction(self.params)
self.params['idx'], self.params['val'], self.params['reward'], self.params['game_status'] = game.step(self.params['action'])
if self.params['game_status']:
wins += game.win
break
else:
#Step and update
self.params['action'] = agent.getAction(self.params)
self.params['idx'], self.params['val'], _, _ = game.step(self.params['action'])
agent.update(self.params)
# Update Q-values
agent.update(self.params)
games += 1
if (i % n_print == 0) & (i > 0):
sleep(delay)
clear_output()
print("TRAIN PCT: {:.2} |\t VICTORY PERCENTAGE: {:.2}".format(i/n_games, wins/games))
clear_output()
print("TRAINING COMPLETE |\t FINAL VICTORY PERCENTAGE: {:.2}".format(wins/games))
return wins/games
def reset(self, game):
return {"lo":game.lo,
"hi":game.hi,
"n_idx":game.n_idx,
"replace":game.replace,
"idx":0,
"action":None,
"val":game.val,
"game_status":False}
#########################################################################################
# MCMC Trainer
#########################################################################################
class MCMCTrainer(Trainer):
def __init__(self):
super().__init__()
return
def train(self, game, agent, n_games):
wins, games = 0, 0
agent.train()
for i in tqdm(range(n_games), leave=False):
game.reset()
agent.reset()
self.params = self.reset(game)
episode = self.mcEpisode(game, agent)
if episode[-1][3] > 0: # if the reward was positive, we probably won
wins += 1
games += 1
agent.update(self.params, episode)
return wins/games
def mcEpisode(self, game, agent):
action, val = agent.getAction(self.params)
self.params['idx'], self.params['val'], reward, self.params['game_status'] = game.step(action)
if self.params['game_status']:
return [[self.params['idx'], val, action, reward]]
else:
return [[self.params['idx']-1, val, action, reward]] + self.mcEpisode(game, agent)
def reset(self, game):
return {"lo":game.lo,
"hi":game.hi,
"n_idx":game.n_idx,
"replace":game.replace,
"idx":game.idx,
"val":game.val}
#########################################################################################
# DQN Trainer
#########################################################################################
class DQTrainer(Trainer):
def __init__(self):
super().__init__()
return
def train(self, game, agent, n_games, n_print, delay, device):
"""Train a DQAgent over n_games"""
wins, games = 0, 0
agent.train()
for game_i in tqdm(range(n_games)):
game.reset()
agent.reset()
self.params = self.reset(game)
self.params['game_i'] = game_i
while True:
action, state = agent.getAction(self.params)
self.params['idx'], self.params['val'], self.params['reward'], self.params['game_status'] = game.step(action.item())
reward = torch.tensor([self.params['reward']], device=device)
if self.params['game_status']:
next_state = None
agent.memory.push(state, action, next_state, reward)
agent.update()
wins += game.win
break
else:
next_state = agent.p_to_s(self.params, agent.v_key)
agent.memory.push(state, action, next_state, reward)
state = next_state
agent.update()
agent.updateNet(game_i)
games += 1
if (game_i % n_print == 0) & (game_i > 0):
sleep(delay)
clear_output()
print("TRAIN PCT: {:.2} |\t VICTORY PERCENTAGE: {:.2}".format(game_i/n_games, wins/games))
clear_output()
print("TRAINING COMPLETE |\t FINAL VICTORY PERCENTAGE: {:.2}".format(wins/games))
return wins/games
def eval(self, game, agent, n_games, n_print, delay, device):
"""Eval a DQAgent over n_games"""
wins, games = 0, 0
stop_choices = [0] * game.n_idx
agent.eval()
for game_i in tqdm(range(n_games)):
game.reset()
agent.reset()
self.params = self.reset(game)
self.params['game_i'] = game_i
while True:
action = agent.getAction(self.params)
if action == 0:
stop_choices[self.params['idx']] += 1
self.params['idx'], self.params['val'], self.params['reward'], self.params['game_status'] = game.step(action.item())
reward = torch.tensor([self.params['reward']], device=device)
if self.params['game_status']:
wins += game.win
break
games += 1
if (game_i % n_print == 0) & (game_i > 0):
sleep(delay)
clear_output()
print("TRAIN PCT: {:.2} |\t VICTORY PERCENTAGE: {:.2}".format(game_i/n_games, wins/games))
clear_output()
print("TRAINING COMPLETE |\t FINAL VICTORY PERCENTAGE: {:.2}".format(wins/games))
print("STOP CHOICES:", stop_choices)
return wins/games, stop_choices
def reset(self, game):
return {"lo":game.lo,
"hi":game.hi,
"n_idx":game.n_idx,
"replace":game.replace,
"idx":0,
"action":None,
"val":game.val,
"game_status":False}