-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNN.py
315 lines (271 loc) · 7.97 KB
/
NN.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
# Neural Network
#
# Author: Luke Munro
from sigNeuron import *
import numpy as np
"""Neural net class for systems with ONE hidden layer,
eventually will work generically for more. """
class Net:
def __init__(self, nodes, gridSize):
# ------ One Hidden Layer ------
# Nodes = # nodes in layer | sizeX = # data points | ouptuts = # possible ouptuts
# ----------- All sizes do NOT CONTAIN BIAS UNITS -----------
self.gridSize = gridSize
self.sizeX = 2*(gridSize*(gridSize+1)) #+2
# ------ Hidden layer variables -------------------
self.hidden = []
self.sizeH = nodes
#-------- Output variables ----------
self.outs = []
self.sizeO = self.sizeX #-2# For player scores
for i in range(nodes):
self.hidden.append(Neuron(1, i, self.sizeX+1, i))
for i in range(self.sizeO):
self.outs.append(Neuron(2, i, self.sizeH+1, i)) # +1 for bias
self.layers = [self.hidden, self.outs]
def getWeights(self):
layer1 = np.zeros(shape=(self.sizeH, self.sizeX+1))
layer2 = np.zeros(shape=(self.sizeO, self.sizeH+1))
for i, node in enumerate(self.hidden):
layer1[i] = node.getW()
for i, node in enumerate(self.outs):
layer2[i] = node.getW()
weights = [layer1, layer2]
return weights
def writeWeights(self):
layerWeights = self.getWeights()
layerWeights[0].tofile('weights1')
layerWeights[1].tofile('weights2')
def loadWeights(self):
weights1 = np.fromfile('weights1').reshape(self.sizeH, self.sizeX+1)
weights2 = np.fromfile('weights2').reshape(self.sizeO, self.sizeH+1)
# print "---- read ----\n" + str(weights2)
for i, weight in enumerate(weights1):
self.hidden[i].assignW(weight)
for i, weight in enumerate(weights2):
self.outs[i].assignW(weight)
def updateWeights(self, layerWeights):
# print "---- written ----\n" + str(layerWeights[1])
layerWeights[0].tofile('weights1')
layerWeights[1].tofile('weights2')
# self.loadWeights()
def getMove(self):
# self.loadWeights()
a = []
z = []
a1 = getData()
justMoves = a1 #list(a0[:len(a0)-2])
a1 = addBias(a1)
a.append(a1)
z2 = computeZ(self.layers[0], a1)
z.append(z2)
a2 = sigmoid(z2)
a2 = addBias(a2)
a.append(a2)
z3 = computeZ(self.layers[1], a2)
z.append(z3)
a3 = sigmoid(z3)
a.append(a3)
# print a3
moves = findMoves(a3)
legalMoves = onlyLegal(moves, justMoves)
nextMoves = formatMoves(legalMoves, makeCommands(self.gridSize))
return nextMoves[0]
def getA(self):
a = []
z = []
a1 = getData()
justMoves = a1 #list(a0[:len(a0)-2])
a1 = addBias(a1)
a.append(a1)
z2 = computeZ(self.layers[0], a1)
z.append(z2)
a2 = sigmoid(z2)
a2 = addBias(a2)
a.append(a2)
z3 = computeZ(self.layers[1], a2)
z.append(z3)
a3 = sigmoid(z3)
return a3
def train(self, alpha, y):
# ----- Leave steps split for easier comprehension ------
print self.getWeights()[1]
a = []
z = []
a1 = getData()
justMoves = a1
a1 = addBias(a1)
a.append(a1)
z2 = computeZ(self.layers[0], a1)
z.append(z2)
a2 = sigmoid(z2)
a2 = addBias(a2)
a.append(a2)
z3 = computeZ(self.layers[1], a2)
z.append(z3)
a3 = sigmoid(z3)
a.append(a3)
print costMeanSquared(y, a3)
delta3 = (a3 - y) * sigGradient(z3)
layerWeights = self.getWeights()
w1 = layerWeights[0]
w2 = layerWeights[1]
w1NoBias = rmBias(w1)
delta2 = np.dot(w1NoBias, delta3) * sigGradient(z2)
Grad1 = delta2 * a1.transpose()
Grad2 = delta3 * a2.transpose()
w1 += alpha * Grad1
w2 += alpha * Grad2
for i, weight in enumerate(w1):
self.hidden[i].assignW(weight)
for i, weight in enumerate(w2):
self.outs[i].assignW(weight)
print self.getWeights()[1]
# -------------------------- Computations -------------------------------
def computeZ(Nodes, X):
w = np.zeros(shape=(np.size(Nodes), np.size(X)))
for i, node in enumerate(Nodes):
w[i] = node.getW()
z = np.dot(w, X).reshape(np.size(Nodes), 1)
return z
def sigmoid(z):
return 1/(1+np.exp(-z))
def costLog(y, a):
cost = -y * np.log10(a) - (1 - y) * np.log10(1 - a)
return sum(cost)
def costMeanSquared(y, a):
cost = ((a - y)**2)/2.0
return sum(cost)
def sigGradient(z):
return sigmoid(z) * (1 - sigmoid(z))
def reg(weights, Lambda): # Bias must be removed from weights
w1= rmBias(weights[0])
w2 = rmBias(weights[1])
reg = Lambda/2.0 * (sum(sum(w1**2)) + sum(sum(w2**2)))
return reg
def estimateGradlog(y, a, weights, epsilon): # DO THIS LATER
for i in range(weights):
for i in range(weights[i]):
continue
return None
# return (costLog(y, a+epsilon) - costLog(y, a-epsilon))
# ---------------------------- Utility ----------------------------------
def getData():
with open('data', 'r') as d:
data = d.read()
data = [[int(data[x])] for x in range(len(data)) if x%3==1]
data = np.array(data)
return data
def addBias(aLayer): # Adds 1 to vertical vector matrix
return np.insert(aLayer, 0, 1, axis=0)
def rmBias(weightMatrix): # removes bias weight from all nodes
return np.delete(weightMatrix, 0, axis=1)
# ------------------ Translating to BoxesDotes ----------------------
def findMoves(probs): # CONDENSE fix for same prob
moves = []
probs = probs.tolist()
tProbs = list(probs)
for i in range(len(probs)):
high = max(tProbs)
index = probs.index(high)
probs[index] = -1 # working fix for same probs bug
moves.append(index)
tProbs.remove(high)
return moves
def makeCommands(gridDim):
moveCommands = []
for i in range(gridDim*2+1):
if i%2==0:
for x in range(gridDim):
moveCommands.append(str(i)+str(x))
else:
for x in range(gridDim+1):
moveCommands.append(str(i)+str(x))
return moveCommands
def formatMoves(moveOrder, commands): # CONDENSE
fmatMoves = []
for i, move in enumerate(moveOrder):
fmatMoves.append(commands[move])
return fmatMoves
def onlyLegal(moves, justMoves): # CONDENSE
legalMoves = []
for i in range(len(justMoves)):
if justMoves[i] == 0:
legalMoves.append(i)
moveOrder = filter(lambda x: x in legalMoves, moves)
return moveOrder
# --------------- for testing ----------------------------------
def main():
y = np.zeros(shape=(12, 1))
t = np.zeros(shape=(12, 1))+0.001
#y = addBias(y)
x= [[ 0.44841772], [ 0.44841772], [ 0.44841772], [ 0.44841772], [ 0.3939411 ], [ 0.3939411 ], [ 0.3939411 ], [ 0.3939411 ], [ 0.43916391], [ 0.43916391], [ 0.43916391], [ 0.43916391]]
# print y, y.shape
a4 = np.zeros(shape=(12, 1))
for i in range(12):
a4[i] = x[i]
aI = Net(10, 2)
aI.loadWeights()
a = []
z = []
a1 = getData()
justMoves = a1 #list(a0[:len(a0)-2])
a1 = addBias(a1)
print a1, a1.shape
a.append(a1)
z2 = computeZ(aI.layers[0], a1)
z.append(z2)
a2 = sigmoid(z2)
a2 = addBias(a2)
a.append(a2)
z3 = computeZ(aI.layers[1], a2)
z.append(z3)
a3 = sigmoid(z3)
a.append(a3)
print "------- costs -------"
print costLog(y, a3)
# print costMeanSquared(y, a3)
delta3log = a3 - y
delta3squared = (a3 - y) * sigGradient(z3)
print "------- deltas3s -------"
print delta3log, delta3log.shape
# print ''
# print delta3squared
w = aI.getWeights()
print "----- regularization -----"
print reg(w, 1)
print "------- delta2s --------"
print "weight dims - " + str(w[0].shape), str(w[1].shape)
wNoBias = np.delete(w[1], 0, axis=1)
delta2log = np.dot(wNoBias.transpose(), delta3log) * sigGradient(z2)
delta2squared = np.dot(wNoBias.transpose(), delta3squared) * sigGradient(z2)
print delta2log, delta2log.shape
# print ""
# print delta2squared
w2Gradlog = delta3log * a2.transpose()
w2GradSquared = delta3squared * a2.transpose()
print"-------- gradients weights 2 --------"
print w2Gradlog, w2Gradlog.shape
# print w2GradSquared
print "------- gradient weights 1 --------"
w1Gradlog = delta2log * a1.transpose()
w1GradSquared = delta2squared * a1.transpose()
print w1Gradlog, w1Gradlog.shape
# print w1GradSquared
print "--------- weights ----------"
print w[0]
print ""
print w[1]
print "--------- added gradient ---------"
w1 = w[0] + w1Gradlog
w2 = w[1] + w2Gradlog
print w1
print ""
print w2
# print sigmoid(a)
# print 1 - sigmoid(a)
# grad = sigGradient(z)
# delta3 = y - a # * a2
# delta2 = delta3 * sigGradient(z2) # a1
if __name__ == '__main__':
main()