-
Notifications
You must be signed in to change notification settings - Fork 760
/
agent.py
228 lines (158 loc) · 6.19 KB
/
agent.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
# %matplotlib inline
import numpy as np
import random
import MCTS as mc
from game import GameState
from loss import softmax_cross_entropy_with_logits
import config
import loggers as lg
import time
import matplotlib.pyplot as plt
from IPython import display
import pylab as pl
class User():
def __init__(self, name, state_size, action_size):
self.name = name
self.state_size = state_size
self.action_size = action_size
def act(self, state, tau):
action = input('Enter your chosen action: ')
pi = np.zeros(self.action_size)
pi[action] = 1
value = None
NN_value = None
return (action, pi, value, NN_value)
class Agent():
def __init__(self, name, state_size, action_size, mcts_simulations, cpuct, model):
self.name = name
self.state_size = state_size
self.action_size = action_size
self.cpuct = cpuct
self.MCTSsimulations = mcts_simulations
self.model = model
self.mcts = None
self.train_overall_loss = []
self.train_value_loss = []
self.train_policy_loss = []
self.val_overall_loss = []
self.val_value_loss = []
self.val_policy_loss = []
def simulate(self):
lg.logger_mcts.info('ROOT NODE...%s', self.mcts.root.state.id)
self.mcts.root.state.render(lg.logger_mcts)
lg.logger_mcts.info('CURRENT PLAYER...%d', self.mcts.root.state.playerTurn)
##### MOVE THE LEAF NODE
leaf, value, done, breadcrumbs = self.mcts.moveToLeaf()
leaf.state.render(lg.logger_mcts)
##### EVALUATE THE LEAF NODE
value, breadcrumbs = self.evaluateLeaf(leaf, value, done, breadcrumbs)
##### BACKFILL THE VALUE THROUGH THE TREE
self.mcts.backFill(leaf, value, breadcrumbs)
def act(self, state, tau):
if self.mcts == None or state.id not in self.mcts.tree:
self.buildMCTS(state)
else:
self.changeRootMCTS(state)
#### run the simulation
for sim in range(self.MCTSsimulations):
lg.logger_mcts.info('***************************')
lg.logger_mcts.info('****** SIMULATION %d ******', sim + 1)
lg.logger_mcts.info('***************************')
self.simulate()
#### get action values
pi, values = self.getAV(1)
####pick the action
action, value = self.chooseAction(pi, values, tau)
nextState, _, _ = state.takeAction(action)
NN_value = -self.get_preds(nextState)[0]
lg.logger_mcts.info('ACTION VALUES...%s', pi)
lg.logger_mcts.info('CHOSEN ACTION...%d', action)
lg.logger_mcts.info('MCTS PERCEIVED VALUE...%f', value)
lg.logger_mcts.info('NN PERCEIVED VALUE...%f', NN_value)
return (action, pi, value, NN_value)
def get_preds(self, state):
#predict the leaf
inputToModel = np.array([self.model.convertToModelInput(state)])
preds = self.model.predict(inputToModel)
value_array = preds[0]
logits_array = preds[1]
value = value_array[0]
logits = logits_array[0]
allowedActions = state.allowedActions
mask = np.ones(logits.shape,dtype=bool)
mask[allowedActions] = False
logits[mask] = -100
#SOFTMAX
odds = np.exp(logits)
probs = odds / np.sum(odds) ###put this just before the for?
return ((value, probs, allowedActions))
def evaluateLeaf(self, leaf, value, done, breadcrumbs):
lg.logger_mcts.info('------EVALUATING LEAF------')
if done == 0:
value, probs, allowedActions = self.get_preds(leaf.state)
lg.logger_mcts.info('PREDICTED VALUE FOR %d: %f', leaf.state.playerTurn, value)
probs = probs[allowedActions]
for idx, action in enumerate(allowedActions):
newState, _, _ = leaf.state.takeAction(action)
if newState.id not in self.mcts.tree:
node = mc.Node(newState)
self.mcts.addNode(node)
lg.logger_mcts.info('added node...%s...p = %f', node.id, probs[idx])
else:
node = self.mcts.tree[newState.id]
lg.logger_mcts.info('existing node...%s...', node.id)
newEdge = mc.Edge(leaf, node, probs[idx], action)
leaf.edges.append((action, newEdge))
else:
lg.logger_mcts.info('GAME VALUE FOR %d: %f', leaf.playerTurn, value)
return ((value, breadcrumbs))
def getAV(self, tau):
edges = self.mcts.root.edges
pi = np.zeros(self.action_size, dtype=np.integer)
values = np.zeros(self.action_size, dtype=np.float32)
for action, edge in edges:
pi[action] = pow(edge.stats['N'], 1/tau)
values[action] = edge.stats['Q']
pi = pi / (np.sum(pi) * 1.0)
return pi, values
def chooseAction(self, pi, values, tau):
if tau == 0:
actions = np.argwhere(pi == max(pi))
action = random.choice(actions)[0]
else:
action_idx = np.random.multinomial(1, pi)
action = np.where(action_idx==1)[0][0]
value = values[action]
return action, value
def replay(self, ltmemory):
lg.logger_mcts.info('******RETRAINING MODEL******')
for i in range(config.TRAINING_LOOPS):
minibatch = random.sample(ltmemory, min(config.BATCH_SIZE, len(ltmemory)))
training_states = np.array([self.model.convertToModelInput(row['state']) for row in minibatch])
training_targets = {'value_head': np.array([row['value'] for row in minibatch])
, 'policy_head': np.array([row['AV'] for row in minibatch])}
fit = self.model.fit(training_states, training_targets, epochs=config.EPOCHS, verbose=1, validation_split=0, batch_size = 32)
lg.logger_mcts.info('NEW LOSS %s', fit.history)
self.train_overall_loss.append(round(fit.history['loss'][config.EPOCHS - 1],4))
self.train_value_loss.append(round(fit.history['value_head_loss'][config.EPOCHS - 1],4))
self.train_policy_loss.append(round(fit.history['policy_head_loss'][config.EPOCHS - 1],4))
plt.plot(self.train_overall_loss, 'k')
plt.plot(self.train_value_loss, 'k:')
plt.plot(self.train_policy_loss, 'k--')
plt.legend(['train_overall_loss', 'train_value_loss', 'train_policy_loss'], loc='lower left')
display.clear_output(wait=True)
display.display(pl.gcf())
pl.gcf().clear()
time.sleep(1.0)
print('\n')
self.model.printWeightAverages()
def predict(self, inputToModel):
preds = self.model.predict(inputToModel)
return preds
def buildMCTS(self, state):
lg.logger_mcts.info('****** BUILDING NEW MCTS TREE FOR AGENT %s ******', self.name)
self.root = mc.Node(state)
self.mcts = mc.MCTS(self.root, self.cpuct)
def changeRootMCTS(self, state):
lg.logger_mcts.info('****** CHANGING ROOT OF MCTS TREE TO %s FOR AGENT %s ******', state.id, self.name)
self.mcts.root = self.mcts.tree[state.id]