-
Notifications
You must be signed in to change notification settings - Fork 0
/
nnagent_half.py
565 lines (471 loc) · 19.8 KB
/
nnagent_half.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# myTeam.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# ([email protected]) and Dan Klein ([email protected]).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel ([email protected]).
from captureAgents import CaptureAgent
import random, time, util
from util import nearestPoint
from game import Directions
import numpy as np
import game
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from collections import namedtuple
from torch.autograd import Variable
import pickle
def optimize_model():
if len(MEMORY) < BATCH_SIZE:
return
transitions = MEMORY.sample(BATCH_SIZE)
# Transpose the batch (see http://stackoverflow.com/a/19343/3343043 for
# detailed explanation).
batch = Transition(*zip(*transitions))
# Compute a mask of non-final states and concatenate the batch elements
non_final_mask = ByteTensor(tuple(map(lambda s: s is not None,
batch.next_state)))
non_final_next_states = Variable(torch.cat([s for s in batch.next_state
if s is not None]),
volatile=True)
state_batch = Variable(torch.cat(batch.state))
action_batch = Variable(torch.cat(batch.action))
reward_batch = Variable(torch.cat(batch.reward))
# Compute Q(s_t, a) - the model computes Q(s_t), then we select the
# columns of actions taken
state_action_values = policy_net(state_batch).gather(1, action_batch)
# Compute V(s_{t+1}) for all next states.
next_state_values = Variable(torch.zeros(BATCH_SIZE).type(Tensor))
index = policy_net(non_final_next_states).max(1)[1]
next_state_values[non_final_mask] = target_net(non_final_next_states)[np.arange(index.size()[0]), index]
# Compute the expected Q values
expected_state_action_values = (next_state_values * GAMMA) + reward_batch
# Undo volatility (which was used to prevent unnecessary gradients)
expected_state_action_values = Variable(expected_state_action_values.data)
# Compute Huber loss
loss = F.smooth_l1_loss(state_action_values, expected_state_action_values)
# Optimize the model
optimizer.zero_grad()
loss.backward()
for param in policy_net.parameters():
param.grad.data.clamp_(-1, 1)
optimizer.step()
Transition = namedtuple('Transition',
('state', 'action', 'next_state', 'reward'))
class ReplayMemory(object):
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
self.position = 0
self.counter=1
def push(self, *args):
"""Saves a transition."""
if len(self.memory) < self.capacity:
self.memory.append(None)
self.memory[self.position] = Transition(*args)
self.position = (self.position + 1) % self.capacity
def sample(self, batch_size):
return random.sample(self.memory, batch_size)
def __len__(self):
return len(self.memory)
def count(self):
self.counter+=1
class DQN(nn.Module):
def __init__(self):
super(DQN, self).__init__()
# todo: sort shapes
self.conv1 = nn.Conv2d(6, 16, 3)
self.conv2 = nn.Conv2d(16, 32, 3)
self.fc3 = nn.Linear(30*14*32, 256)
self.fc4 = nn.Linear(256, 5)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x=x.view(-1,self.num_flat_features(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
use_cuda = torch.cuda.is_available()
FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor
LongTensor = torch.cuda.LongTensor if use_cuda else torch.LongTensor
ByteTensor = torch.cuda.ByteTensor if use_cuda else torch.ByteTensor
Tensor = FloatTensor
policy_net = DQN()
target_net = DQN()
EPS_START = 0.9
EPS_END = 0.05
EPS_DECAY = 200
BATCH_SIZE = 32
TARGET_UPDATE = 10
GAMMA = 0.99
MEMORY = ReplayMemory(10000)
load_memory=1
load_net=1
if load_memory == 1:
try:
with open("/output/silver_memo.file", "rb") as f:
MEMORY = pickle.load(f)
MEMORY.counter=1
print('MEMORY LOADED')
except:
print('COULDNT LOAD MEMORY')
if load_net == 1:
try:
policy_net = torch.load('/output/silver_net')
print('NET LOADED')
except:
print('COULDNT LOAD NET')
target_net.load_state_dict(policy_net.state_dict())
target_net.eval()
if use_cuda:
policy_net.cuda()
target_net.cuda()
optimizer = optim.RMSprop(policy_net.parameters(), lr=0.0002)
#################
# Team creation #
#################
def createTeam(firstIndex, secondIndex, isRed,
first='NNAgent', second='DefensiveReflexAgent'):
"""
This function should return a list of two agents that will form the
team, initialized using firstIndex and secondIndex as their agent
index numbers. isRed is True if the red team is being created, and
will be False if the blue team is being created.
As a potentially helpful development aid, this function can take
additional string-valued keyword arguments ("first" and "second" are
such arguments in the case of this function), which will come from
the --redOpts and --blueOpts command-line arguments to capture.py.
For the nightly contest, however, your team will be created without
any extra arguments, so you should make sure that the default
behavior is what you want for the nightly contest.
"""
# The following line is an example only; feel free to change it.
return [eval(first)(firstIndex), eval(second)(secondIndex)]
class NNAgent(CaptureAgent):
"""
A Dummy agent to serve as an example of the necessary agent structure.
You should look at baselineTeam.py for more details about how to
create an agent as this is the bare minimum.
"""
def update_reward(self, gameState):
reward= -0.1 #for time step
if self.old_action==4:
reward-=0.1
food_in_belly = gameState.getAgentState(self.index).numCarrying
food_returned = gameState.getAgentState(self.index).numReturned
if food_in_belly==0:
reward+=(self.last_distance-self.distance)
if food_in_belly>self.last_food_in_belly:
reward+=10*(food_in_belly-self.last_food_in_belly)
reward+=10*(food_returned-self.last_food_returned)
self.last_food_in_belly=food_in_belly
self.last_food_returned=food_returned
return reward
'''
self.reward+=0.01*self.getScore(gameState)
self.reward-=0.001*len(self.getFood(gameState).asList())
self.reward+=0.001*len(self.getFoodYouAreDefending(gameState).asList())
self.reward-=0.00001*self.time'''
#self.reward-=0.01*minDistance
def registerInitialState(self, gameState):
"""
This method handles the initial setup of the
agent to populate useful fields (such as what team
we're on).
A distanceCalculator instance caches the maze distances
between each pair of positions, so your agents can use:
self.distancer.getDistance(p1, p2)
IMPORTANT: This method may run for at most 15 seconds.
"""
'''
Make sure you do not delete the following line. If you would like to
use Manhattan distances instead of maze distances in order to save
on initialization time, please take a look at
CaptureAgent.registerInitialState in captureAgents.py.
'''
self.old_state = None
self.old_action = None
self.name = 'Steven'
self.reward = 0
self.time = 0
# self.alpha=0.00001
self.old_q = None
self.epsilon = 0.3
###Parameters for reward
self.last_distance = 0
self.last_food_in_belly=0
self.last_food_returned=0
self.start = gameState.getAgentPosition(self.index)
CaptureAgent.registerInitialState(self, gameState)
'''
Your initialization code goes here, if you need any.
'''
def state_to_input(self, gameState):
walls = np.array(gameState.data.layout.walls.data, dtype=int)
capsules = np.zeros(walls.shape, dtype=int)
c1=self.getCapsulesYouAreDefending(gameState)
for c in c1:
capsules[c]+=1
c2=self.getCapsules(gameState)
for c in c2:
capsules[c] -= 1
f1=np.array(self.getFoodYouAreDefending(gameState).data,dtype=int)
f2=np.array(self.getFood(gameState).data,dtype=int)
food = f1-f2
my_agent=np.zeros(walls.shape, dtype=int)
my_pos=gameState.getAgentPosition(self.index)
if gameState.getAgentState(self.index).isPacman:
my_agent[my_pos]=1
else:
my_agent[my_pos] = -1
opponents = np.zeros(walls.shape, dtype=int)
my_mate = np.zeros(walls.shape, dtype=int)
for i in range(4):
pos = gameState.getAgentPosition(i)
if pos and i!=self.index:
if gameState.isOnRedTeam(i):
if self.red:
if gameState.getAgentState(i).isPacman:
my_mate[pos] = 1
else:
my_mate[pos] = -1
else:
if gameState.getAgentState(i).isPacman:
opponents[pos] = 1
else:
opponents[pos] = -1
else:
if self.red:
if gameState.getAgentState(i).isPacman:
opponents[pos] = 1
else:
opponents[pos] = -1
else:
if gameState.getAgentState(i).isPacman:
my_mate[pos] = 1
else:
my_mate[pos] = -1
# todo:add probabilities,scared
state_tensor=np.stack((walls,food,capsules,my_agent,my_mate,opponents))
return state_tensor
def pick_best_allowed_action(self, Q_values, allowed_actions):
actions = ['North', 'South', 'East', 'West', 'Stop']
value_list = list(zip(actions, Q_values.ravel()))
while True:
action = max(value_list, key=lambda x: x[1])
if action[0] in allowed_actions:
return action[0]
else:
value_list.remove(action)
def action_to_int(self, action):
if action == 'North':
return 0
elif action == 'South':
return 1
elif action == 'East':
return 2
elif action == 'West':
return 3
elif action == 'Stop':
return 4
def index_to_action(self, index):
actions = ['North', 'South', 'East', 'West', 'Stop']
return actions[index]
def chooseAction(self, gameState):
"""
Picks among actions randomly.
"""
foodList = self.getFood(gameState).asList()
myPos = gameState.getAgentState(self.index).getPosition()
minDistance = min([self.getMazeDistance(myPos, food) for food in foodList])
self.distance=minDistance
self.time += 1
state = self.state_to_input(gameState)
if self.time > 1:
reward = Tensor([self.update_reward(gameState)])
MEMORY.push(torch.from_numpy(self.old_state).unsqueeze(0).type(Tensor), LongTensor([[self.old_action]]),
torch.from_numpy(state).unsqueeze(0).type(Tensor), reward)
optimize_model()
if self.time % TARGET_UPDATE == 0:
target_net.load_state_dict(policy_net.state_dict())
actions = gameState.getLegalActions(self.index)
# You can profile your evaluation time by uncommenting these lines
# start = time.time()
# print('eval time for agent %d: %.4f' % (self.index, time.time() - start))
Q = policy_net(
# Variable(self.state_to_input(gameState), volatile=True).type(FloatTensor)).data.max(1)[1].view(1, 1)
Variable(torch.from_numpy(state).unsqueeze(0).type(Tensor), volatile=True).type(FloatTensor)).data
Q = Q.numpy()
index = np.argmax(Q)
action = self.index_to_action(index)
if np.random.random() > self.epsilon:
if action not in actions:
self.old_action = self.action_to_int(action)
action = random.choice(actions)
else:
self.old_action = self.action_to_int(action)
else:
action = random.choice(actions)
self.old_action = self.action_to_int(action)
foodList = self.getFood(gameState).asList()
if len(foodList) > 0: # This should always be True, but better safe than sorry
myPos = gameState.getAgentState(self.index).getPosition()
minDistance = min([self.getMazeDistance(myPos, food) for food in foodList])
self.last_distance = minDistance
self.old_state = state
self.last_distance=self.distance
return action
def finalUpdate(self, winner, gameState):
state = self.state_to_input(gameState)
reward=self.update_reward(gameState)
if winner=='Red':
if self.red:
reward+=100
else:
reward -= 100
elif winner=='Blue':
if self.red:
reward -= 100
else:
reward += 100
else:
reward -= 10
reward = Tensor([reward])
MEMORY.push(torch.from_numpy(self.old_state).unsqueeze(0).type(Tensor), LongTensor([[self.old_action]]),
None, reward)
optimize_model()
if MEMORY.counter>0 and MEMORY.counter%10==0:
with open("/output/silver_memo.file", "wb") as f:
pickle.dump(MEMORY, f, pickle.HIGHEST_PROTOCOL)
print('SAVING MEMORY')
torch.save(policy_net, '/output/silver_net')
print('SAVING NET')
print('Iteration ',MEMORY.counter)
MEMORY.count()
class ReflexCaptureAgent(CaptureAgent):
"""
A base class for reflex agents that chooses score-maximizing actions
"""
def registerInitialState(self, gameState):
self.name = 'paolo'
self.start = gameState.getAgentPosition(self.index)
CaptureAgent.registerInitialState(self, gameState)
def chooseAction(self, gameState):
"""
Picks among the actions with the highest Q(s,a).
"""
food_in_belly = gameState.getAgentState(self.index).numCarrying
if food_in_belly>0:
a=0
actions = gameState.getLegalActions(self.index)
# You can profile your evaluation time by uncommenting these lines
# start = time.time()
values = [self.evaluate(gameState, a) for a in actions]
# print('eval time for agent %d: %.4f' % (self.index, time.time() - start))
maxValue = max(values)
bestActions = [a for a, v in zip(actions, values) if v == maxValue]
foodLeft = len(self.getFood(gameState).asList())
if foodLeft <= 2:
bestDist = 9999
for action in actions:
successor = self.getSuccessor(gameState, action)
pos2 = successor.getAgentPosition(self.index)
dist = self.getMazeDistance(self.start, pos2)
if dist < bestDist:
bestAction = action
bestDist = dist
return bestAction
return random.choice(bestActions)
def getSuccessor(self, gameState, action):
"""
Finds the next successor which is a grid position (location tuple).
"""
successor = gameState.generateSuccessor(self.index, action)
pos = successor.getAgentState(self.index).getPosition()
if pos != nearestPoint(pos):
# Only half a grid position was covered
return successor.generateSuccessor(self.index, action)
else:
return successor
def evaluate(self, gameState, action):
"""
Computes a linear combination of features and feature weights
"""
features = self.getFeatures(gameState, action)
weights = self.getWeights(gameState, action)
return features * weights
def getFeatures(self, gameState, action):
"""
Returns a counter of features for the state
"""
features = util.Counter()
successor = self.getSuccessor(gameState, action)
features['successorScore'] = self.getScore(successor)
return features
def getWeights(self, gameState, action):
"""
Normally, weights do not depend on the gamestate. They can be either
a counter or a dictionary.
"""
return {'successorScore': 1.0}
class OffensiveReflexAgent(ReflexCaptureAgent):
"""
A reflex agent that seeks food. This is an agent
we give you to get an idea of what an offensive agent might look like,
but it is by no means the best or only way to build an offensive agent.
"""
def getFeatures(self, gameState, action):
features = util.Counter()
successor = self.getSuccessor(gameState, action)
foodList = self.getFood(successor).asList()
features['successorScore'] = -len(foodList) # self.getScore(successor)
# Compute distance to the nearest food
if len(foodList) > 0: # This should always be True, but better safe than sorry
myPos = successor.getAgentState(self.index).getPosition()
minDistance = min([self.getMazeDistance(myPos, food) for food in foodList])
features['distanceToFood'] = minDistance
return features
def getWeights(self, gameState, action):
return {'successorScore': 100, 'distanceToFood': -1}
class DefensiveReflexAgent(ReflexCaptureAgent):
"""
A reflex agent that keeps its side Pacman-free. Again,
this is to give you an idea of what a defensive agent
could be like. It is not the best or only way to make
such an agent.
"""
def getFeatures(self, gameState, action):
features = util.Counter()
successor = self.getSuccessor(gameState, action)
myState = successor.getAgentState(self.index)
myPos = myState.getPosition()
# Computes whether we're on defense (1) or offense (0)
features['onDefense'] = 1
if myState.isPacman: features['onDefense'] = 0
# Computes distance to invaders we can see
enemies = [successor.getAgentState(i) for i in self.getOpponents(successor)]
invaders = [a for a in enemies if a.isPacman and a.getPosition() != None]
features['numInvaders'] = len(invaders)
if len(invaders) > 0:
dists = [self.getMazeDistance(myPos, a.getPosition()) for a in invaders]
features['invaderDistance'] = min(dists)
if action == Directions.STOP: features['stop'] = 1
rev = Directions.REVERSE[gameState.getAgentState(self.index).configuration.direction]
if action == rev: features['reverse'] = 1
return features
def getWeights(self, gameState, action):
return {'numInvaders': -1000, 'onDefense': 100, 'invaderDistance': -10, 'stop': -100, 'reverse': -2}