-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetwork1.py
More file actions
197 lines (142 loc) · 4.62 KB
/
Network1.py
File metadata and controls
197 lines (142 loc) · 4.62 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
import pickle
import time
import numpy as np
from activations import sigmoid, sigmoid_prime
# Compute the cross entropy given an activation and a target
def cross_entropy(a, y):
return -(y.dot(np.log2(a)) + (1 - y).dot(np.log2(1-a)))
class Network1(object):
def __init__(self, sizes):
# The number of layers in the network
self.num_layers = len(sizes)
# The sizes of the layers in the network
self.sizes = sizes
# A list of bias vectors (numpy.ndarray)
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
# A list of weight matrices (numpy.ndarray)
self.weights = [np.random.randn(numRows, numCols) for numRows, numCols
in zip(sizes[1:], sizes[:-1])]
# Evaluate the derivative of the cost function for the
# given activation and target vectors
#
# a : numpy.ndarray
# y : numpy.ndarray
#
def cost_derivative(self, a, y):
return a - y
# Compute the output of the network given an input vector.
#
# inputVec : numpy.ndarray
#
def feedForward(self, inputVec):
# Copy the input vector
a = inputVec.copy()
for b, w in zip(self.biases, self.weights):
a = sigmoid(w.dot(a) + b)
return a
# Train the network with stochastic gradient descent
#
# training_data:
# epochs: int
# batch_size: int
# eta: float
# test_data:
#
def sgd(self, training_data, epochs, batch_size, eta, test_data = None):
# Check for test_data
if test_data != None:
show_progress = True
num_tests = len(test_data)
else:
show_progress = False
num_tests = 0
n = len(training_data)
# Update network for each epoch
for j in range(epochs):
start_time = time.time()
np.random.shuffle(training_data)
batches = (training_data[k : k + batch_size] for k in range(0, n, batch_size))
# Run through a set of batches
for batch in batches:
self.update_batch(batch, eta)
epoch_time = time.time() - start_time
# Test network with test_data
if show_progress:
num_correct = 0
for image, label in test_data:
activation = self.feedForward(image)
guess = np.argmax(activation)
if label[guess] > 0:
num_correct += 1
print("Epoch {:d}. {}. {:d} / {:d}".format(j, epoch_time, num_correct, num_tests))
else:
print("Epoch {:d}. {}.".format(j, epoch_time))
def update_batch(self, batch, eta):
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in batch:
# Compute gradient for this instance
delta_nabla_b, delta_nabla_w = self.backprop(x, y)
# Add result to batch totals
for j in range(len(nabla_b)):
nabla_b[j] += delta_nabla_b[j]
nabla_w[j] += delta_nabla_w[j]
# Update biases and weights for this batch
for j in range(len(nabla_b)):
self.biases[j] -= (eta / len(batch)) * nabla_b[j]
self.weights[j] -= (eta / len(batch)) * nabla_w[j]
# Perform a mini-batch update all at once
#
# batch:
# eta: int
#
def update_batch2(self, batch, eta):
# Compute gradient of cost function for this batch
nabla_b, nabla_w = self.backprop2(batch)
# Update biases and weights with gradient
for j in range(len(nabla_b)):
self.biases[j] -= (eta / len(batch)) * nabla_b[j]
self.weights[j] -= (eta / len(batch)) * nabla_w[j]
#
#
# x:
# y:
#
def backprop(self, x, y):
'''
x : n x 1 ndarray
y : n x 1 ndarray
'''
nabla_b = []
nabla_w = []
activations = [x]
weighted_inputs = []
# forward pass
for b, w in zip(self.biases, self.weights):
weighted_inputs.append(w.dot(activations[-1]) + b)
activations.append(sigmoid(weighted_inputs[-1]))
# initialization
delta = self.cost_derivative(activations[-1], y) * sigmoid_prime(weighted_inputs[-1])
nabla_b.append(delta)
nabla_w.append(np.outer(delta, activations[-2]))
# backward pass
for i in range(2, len(self.sizes)):
delta = (self.weights[-i + 1].T).dot(delta) * sigmoid_prime(weighted_inputs[-i])
nabla_b.append(delta)
# check return shape of np.outer
nabla_w.append(np.outer(delta, activations[-i - 1]))
# These were built in reverse order
nabla_w.reverse()
nabla_b.reverse()
return (nabla_b, nabla_w)
# Compute the gradients for all inputs in the batch
def backprop2(self, batch):
# Convert to 2d arrays
xs = []
ys = []
for x, y in batch:
xs.append(x)
ys.append(y)
xs = np.array(xs).T
ys = np.array(ys).T
# backprop