《神经网络与深度学习》中的Python 3.x 代码network1.py
《神经网络与深度学习》(Michael Nielsen著)中的代码是基于python2.7的,下面为移植到python3下的代码:
mnist_loader.py代码:
点击下载:mnist_loader
“””
mnist_loader
~~~~~~~~~~~~
A library to load the MNIST image data. For details of the data
structures that are returned, see the doc strings for “load_data“
and “load_data_wrapper“. In practice, “load_data_wrapper“ is the
function usually called by our neural network code.
“””
#### Libraries
# Standard library
try:
import cPickle as pickle
except ImportError:
import pickle
# import cPickle
import gzip
# Third-party libraries
import numpy as np
def load_data():
“””Return the MNIST data as a tuple containing the training data,
the validation data, and the test data.
The “training_data“ is returned as a tuple with two entries.
The first entry contains the actual training images. This is a
numpy ndarray with 50,000 entries. Each entry is, in turn, a
numpy ndarray with 784 values, representing the 28 * 28 = 784
pixels in a single MNIST image.
The second entry in the “training_data“ tuple is a numpy ndarray
containing 50,000 entries. Those entries are just the digit
values (0…9) for the corresponding images contained in the first
entry of the tuple.
The “validation_data“ and “test_data“ are similar, except
each contains only 10,000 images.
This is a nice data format, but for use in neural networks it’s
helpful to modify the format of the “training_data“ a little.
That’s done in the wrapper function “load_data_wrapper()“, see
below.
“””
with gzip.open(‘./mnist.pkl.gz’, ‘rb’) as f:
training_data, validation_data, test_data = pickle.load(f, encoding=’latin1′)
#show_mnist_data(training_data, validation_data, test_data)
#f = gzip.open(‘./mnist.pkl.gz’, ‘rb’)
#training_data, validation_data, test_data = cPickle.load(f, encoding=”latin1″)
#f.close()
return (training_data, validation_data, test_data)
def show_mnist_data(training_data, validation_data, test_data):
fw = open(“./log.txt”, ‘w’)
np.set_printoptions(precision=4, linewidth=800)
num = 0
fw.write(“下面为MNIST所有图片灰度化之后再数字化抽样之后的数据。\n”)
fw.write(“====== TRAINING DATA Start… ======\n”)
for x,y in training_data:
num += 1
if(num > 10):
break
fw.write(“++++++ “+str(num)+ ” ++++++\n”)
fw.write(“28×28的图片数据:\n”)
for i in x.reshape(28, 28):
fw.write(str(i)+”\n”)
fw.write(“==>”+ “图片对应0~9共10个数字的权重:”+ str(y.tolist())+”\n”)
if num > 10:
fw.write(“……….\n”)
fw.write(“====== TRAINING DATA End. ======\n”)
fw.write(” \n”)
fw.write(” \n”)
num = 0
fw.write(“====== VALIDATION DATA Start… ======\n”)
for x,y in validation_data:
num += 1
if(num > 10):
break
fw.write(“++++++ “+str(num)+ ” ++++++\n”)
fw.write(“28×28的图片数据:\n”)
for i in x.reshape(28, 28):
fw.write(str(i)+”\n”)
fw.write(“==>”+ “图片所对应的数字:”+ str(y.tolist())+”\n”)
if num > 10:
fw.write(“……….\n”)
fw.write(“====== VALIDATION DATA End. ======\n”)
fw.write(” \n”)
fw.write(” \n”)
num = 0
fw.write(“====== TEST DATA Start… ======\n”)
for x,y in test_data:
num += 1
if(num > 10):
break
fw.write(“++++++ “+str(num)+ ” ++++++\n”)
fw.write(“28×28的图片数据:\n”)
for i in x.reshape(28, 28):
fw.write(str(i)+”\n”)
fw.write(“==>”+ “图片所对应的数字:”+ str(y.tolist())+”\n”)
if num > 10:
fw.write(“……….\n”)
fw.write(“====== TEST DATA End. ======\n”)
fw.write(” \n”)
fw.write(” \n”)
fw.close()
def load_data_wrapper():
“””Return a tuple containing “(training_data, validation_data,
test_data)“. Based on “load_data“, but the format is more
convenient for use in our implementation of neural networks.
In particular, “training_data“ is a list containing 50,000
2-tuples “(x, y)“. “x“ is a 784-dimensional numpy.ndarray
containing the input image. “y“ is a 10-dimensional
numpy.ndarray representing the unit vector corresponding to the
correct digit for “x“.
“validation_data“ and “test_data“ are lists containing 10,000
2-tuples “(x, y)“. In each case, “x“ is a 784-dimensional
numpy.ndarry containing the input image, and “y“ is the
corresponding classification, i.e., the digit values (integers)
corresponding to “x“.
Obviously, this means we’re using slightly different formats for
the training data and the validation / test data. These formats
turn out to be the most convenient for use in our neural network
code.”””
tr_d, va_d, te_d = load_data()
training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]
training_results = [vectorized_result(y) for y in tr_d[1]]
training_data = zip(training_inputs, training_results)
validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]
validation_data = zip(validation_inputs, va_d[1])
test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]
test_data = zip(test_inputs, te_d[1])
# show_mnist_data(training_data, validation_data, test_data) #输出,但是zip的iter变量只能用一次,输出之后zip就变空了
return (training_data, validation_data, test_data)
def vectorized_result(j):
“””Return a 10-dimensional unit vector with a 1.0 in the jth
position and zeroes elsewhere. This is used to convert a digit
(0…9) into a corresponding desired output from the neural
network.”””
e = np.zeros((10, 1))
e[j] = 1.0
return e
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import random
import numpy as np
def sigmoid(z):
“””The simgoid fnction.”””
return 1.0/(1.0+np.exp(-z))
def sigmoid_prime(z):
“””Derivative of the sigmoid function.”””
return sigmoid(z)*(1-sigmoid(z))
class Network(object):
def __init__(self, sizes):
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])]
print(“输入图片像素点数:”+str(self.sizes[0]) +”, 输入神经网络层数:”+str(self.num_layers))
print(“第 1 层为输入层(共 “+str(self.sizes[0])+” 个神经元),权重和偏置都不需要。”)
for i in range(1, self.num_layers):
print(“第 “+str(i+1)+” 层共有 “+str(self.sizes[i])+” 个神经元,初始权重和偏置如下。”)
print(” “)
layer = 1
print(“训练前的权重和偏置:”)
for lw, lb in zip(self.weights, self.biases):
layer += 1
num_nw = 0
for w, b in zip(lw, lb):
num_nw += 1
print(“第 “+str(layer)+” 层第 “+str(num_nw)+” 个神经元的权重(共”+str(len(w))+”个输入):”)
print(str(w))
print(“第 “+str(layer)+” 层第 “+str(num_nw)+” 个神经元的偏置(共”+str(len(b))+”个输出):”)
print(str(b))
print(” “)
print(” “)
def feedforward(self ,a):
“””return the output of the network if “a” is input.”””
for b, w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w, a)+b)
return a
def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None):
“””Train the neural network using mini-batch stochastic gradient descent.
The “training_data” is a list of tuples “(x, y)” representing the training inputs and the desired outputs.
The other non-optional parameters are self-explanatory.
If “test_data” is provided then the network will be evaluated against the test data after each epoch, and partial progress printed out.
This is useful for tracking progress, but slows things down substantially.
“””
training_data_list = list(training_data)
test_data_list = list(test_data)
if test_data:
n_test = len(test_data_list)
n = len(training_data_list)
print(“=================================================================”)
print(“=================================================================”)
printStr = “”
loop = 0
for j in range(epochs):
loop += 1
random.shuffle(training_data_list)
training_data = training_data_list
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, eta)
if test_data:
test_data = test_data_list
printStr += (“Epoch {0}: 成功识别:{1} / 总共:{2}”.format(j, self.evaluate(test_data), n_test)+”\n”)
print(“Epoch {0}: 成功识别:{1} / 总共:{2}”.format(j, self.evaluate(test_data), n_test))
else:
print(“Loop “+str(loop))
printStr += (“Epoch {0} complete”.format(j)+”\n”)
print(“Epoch {0} complete”.format(j))
print(“=================================================================”)
print(“=================================================================”)
print(” “)
layer = 1
print(“训练后的权重和偏置:”)
for lw, lb in zip(self.weights, self.biases):
layer += 1
num_nw = 0
for w, b in zip(lw, lb):
num_nw += 1
print(“第 “+str(layer)+” 层第 “+str(num_nw)+” 个神经元的权重(共”+str(len(w))+”个输入):”)
print(str(w))
print(“第 “+str(layer)+” 层第 “+str(num_nw)+” 个神经元的偏置(共”+str(len(b))+”个输出):”)
print(str(b))
print(” “)
print(” “)
print(“=================================================================”)
print(“=================================================================”)
print(printStr)
print(“每层测试结果的计算公式: (输入1*权重1 + 输入2*权重2 + 输入3*权重3 + …) + 偏置 “)
print(“a1*w11—|”)
print(“a2*w12—|+b1—|”)
print(“a3*w13—| |”)
print(“……—| |-output”)
print(“a1*w21—| |”)
print(“a2*w22—|+b2—|”)
print(“a3*w23—|”)
print(“……—|”)
def update_mini_batch(self, mini_batch, eta):
“””Update the network’s weights and biases by applying gradient descent using backpropagation to a single mini batch.
The “mini_batch” is a list of tuples “(x, y)”, and “eta” is the learning rate.
“””
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):
“””Return a tuple “(nabla_b, nabla_w)“ representing the gradient for the cost function C_x.
“nabla_b“ and “nabla_w“ are layer-by-layer lists of numpy arrays, similar to “self.biases“ and “self.weights“.
“””
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
#feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation) + b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass
delta = self.cost_derivative(activations[-1], y) * sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
# Note that the variable l in the loop below is used a little
# differently to the notation in Chapter 2 of the book. Here,
# l = 1 means the last layer of neurons, l = 2 is the
# second-last layer, and so on. It’s a renumbering of the
# scheme in the book, used here to take advantage of the fact
# that Python can use negative indices in lists.
for l in range(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
return (nabla_b, nabla_w)
def evaluate(self, test_data):
“””Return the number of test inputs for which the neural network outputs the correct result.
Note that the neural network’s output is assumed to be the index of whichever neuron in the final layer has the highest activation.
“””
test_results = [(np.argmax(self.feedforward(x)), y) for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_results)
def cost_derivative(self, output_activations, y):
“””Return the vector of partial derivatives \partial C_x / \partial a for the output activations.
“””
return (output_activations – y)
def test():
import mnist_loader
training_data, validation_data, test_data = mnist_loader.load_data_wrapper()
net = Network([784, 30, 10])
net.SGD(training_data, 30, 10, 3.0, test_data=test_data)
if __name__ == ‘__main__’:
test()