损失函数为QuatraticCost,初始化weights,biases服从N(0,1)
import random
import numpy as np
class Network(object):
def __init__(self, sizes, cost):
self.layernumber = len(sizes)
self.sizes = sizes
self.large_weight()
self.cost = cost
def large_weight(self):
self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]
self.weights = [np.random.randn(y, x) for x, y in zip(self.sizes[:-1],self.sizes[1:])]
def feedforward(self, a):
for w, b in zip(self.weights, self.biases):
a = sigmoid(np.dot(w, a) + b)
return a
def evaluate(self, test_data):
test_result = [(np.argmax(self.feedforward(x)), y)
for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_result)
def cost_derivate(self, out_activation, y):
return out_activation - y
def update_mini_batch(self, mini_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 mini_batch:
delta_nabla_b, delta_nabla_w = self.backprop(x, y)
nabla_b = [nb + dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw +dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
self.weights = [w - (eta/len(mini_batch)) * nw
for w, nw in zip(self.weights, nabla_w)]
self.biases = [b - (eta/len(mini_batch)) * nb
for b, nb in zip(self.biases, nabla_b)]
def backprop(self, x, y):
nabla_b = [np.zeros(b.shape()) for b in self.biases]
nabla_w = [np.zeros(w.shape()) for w in self.weights]
activation = x
activations = [x]
z = sigmoid(activation)
zs = []
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation) + b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
delta = self.cost_derivate(activation[-1], y) * sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
for j in range(2, self.layernumber):
z = zs[-j]
ps = sigmoid(z)
delta = np.dot(self.weights[-j+1].transpose(), delta) * ps
nabla_b[-j] = delta
nabla_w[-j] = np.dot(delta, activations[-j-1].transpose())
return nabla_b, nabla_w
def sgd(self, training_data, epochs, mini_batch_size, eta, test_data=None):
if test_data:
n_test = len(test_data)
n = len(training_data)
for i in range(epochs):
random.shuffle(training_data)
mini_batches = [training_data[k, k + mini_batch_size]
for k in range(0, n, mini_batch_size)]
for mini_batch in mini_batches:
self.update_mini_batch(mini_batch)
if test_data:
print('Epoch{0}:{1}/{2}'.format(i, self.evaluate(test_data), n_test))
else:
print('Epoch{0} complete'.format(i))
def cost(self, a, y):
return 0.5 * np.linalg.norm(a - y) ** 2
def sigmoid(z):
return 1.0/(1.0+np.exp(-z))
def sigmoid_prime(z):
return sigmoid(z) * (1 - sigmoid(z))