深度学习笔记(四)利用神经网络分类数字 含python代码

利用我们的神经网络来分类数字

前言

Tips:
你可以在终端git编者的代码
git clone https://github.com/mnielsen/neural-networks-and-deep-learning.git

对MINIST的使用,我们将用50000张图片进行训练我们的神经网络,用10000张图片来作为我们的validation set(验证集).
在本次章节中我们不会运用validation set,但在之后我们将会引入它,并会发现它在定义 一些hyper-parameters (超参数)是非常有用的----例如learning rate 等等,这些参数不被我们的学习算法直接选择.尽管验证数据不是原始 MNIST 规范的⼀部分,然⽽许多⼈以这种⽅式使⽤ MNIST,并且在神经⽹络中使⽤验证数据是很普遍的。

**note:**从现在起我提到“MNIST 训练数据”时,我指的是我们的 50,000 个图像数据集,⽽不是原始的 60,000 图像数据集.

代码正式部分

下列是神经网络代码的核心特性. 核心的片段是一个 Network class,用来表示一个神经网络
下面是它的初始化

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:])]
  • sizes:包含各层神经元的数量.例如,如果我们想创建⼀个在第⼀层有2 个神经元,第⼆层有 3 个神经元,最后层有 1 个神经元的 Network 对象,我们应这样写代码:net = Network([2, 3, 1])
  • Python中的[1:]意思是去掉列表中第一个元素(下标为0),对后面的元素进行操作.
  • zip 将对象中对应元素打包成一个数组.
    输出示例:
net=Network([2,3,1])  #表示第一层2个神经元 第二层3个神经元 最后一层1个神经元
print(net.sizes)
print(net.biases)
print(net.weights)
[2, 3, 1]
[array([[-0.95257317],
       [ 0.24527865],
       [-1.76486741]]), array([[-1.55405365]])] #第二层的3个 bias 和第三层的 1个bias
[array([[ 0.99151032, -0.4567537 ],
       [ 1.43200064,  0.45544157],
       [ 1.00863618,  0.73885859]]), array([[ 1.28685745,  0.40043007, -1.47589017]])]#第二层受到第一层的权重值和第三层受到第二层的权重值

之后会直接附录上整个代码,并加上自己的注释,方便大家观看

network.py

"""
network.py
~~~~~~~~~~

A module to implement the stochastic gradient descent learning
algorithm for a feedforward neural network.  Gradients are calculated
using backpropagation.  Note that I have focused on making the code
simple, easily readable, and easily modifiable.  It is not optimized,
and omits many desirable features.
"""
from __future__ import print_function
#### Libraries
# Standard library
import random

# Third-party libraries
import numpy as np

class Network(object):

    def __init__(self, sizes):#sizes各层神经元的数量
        """The list ``sizes`` contains the number of neurons in the
        respective layers of the network.  For example, if the list
        was [2, 3, 1] then it would be a three-layer network, with the
        first layer containing 2 neurons, the second layer 3 neurons,
        and the third layer 1 neuron.  The biases and weights for the
        network are initialized randomly, using a Gaussian
        distribution with mean 0, and variance 1.  Note that the first
        layer is assumed to be an input layer, and by convention we
        won't set any biases for those neurons, since biases are only
        ever used in computing the outputs from later layers.
        '''
        - sizes:包含各层神经元的数量.例如,如果我们想创建⼀个在第⼀层有2 个神经元,第⼆层有 3 个神经元,最后层有 1 个神经元的 Network 对象,我们应这样写代码:net = Network([2, 3, 1])
        - Python中的[1:]意思是去掉列表中第一个元素(下标为0),对后面的元素进行操作.
        - zip 将对象中对应元素打包成一个数组.
        - num_layers 神经元的层数
输出示例:

net=Network([2,3,1])  #表示第一层2个神经元 第二层3个神经元 最后一层1个神经元
print(net.sizes)
print(net.biases)
print(net.weights)

[2, 3, 1]
[array([[-0.95257317],
       [ 0.24527865],
       [-1.76486741]]), array([[-1.55405365]])] #第二层的3个 bias 和第三层的 1个bias
[array([[ 0.99151032, -0.4567537 ],
       [ 1.43200064,  0.45544157],
       [ 1.00863618,  0.73885859]]), array([[ 1.28685745,  0.40043007, -1.47589017]])]#第二层受到第一层的权重值和第三层受到第二层的权重值
'''"""
        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 list(zip(sizes[:-1], sizes[1:]))]


    def feedforward(self, a):
        #给定输入a,返回对应的输出
        """Return the output of the network if ``a`` is input."""
        for b, w in list(zip(self.biases, self.weights)):
            a = sigmoid(np.dot(w, a)+b)  #np.dot 向量内积a·b
        return a

    def SGD(self, training_data, epochs, mini_batch_size, eta,
            test_data=None):
        #training_data (x,y)数组列表,表示训练的输入和期望的输出;epochs:迭代期的数量;mini_batch_size:采样时小批量数据的大小
        #eta:及学习速率;test_data:是否对网络进行评估,并打印出进展,有利于追踪进度,但会使程序运行缓慢
        """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."""
        test_data = list(test_data)#此处是因为Python2版本中zip不再有len,则现需要对其求list
        # 在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。
        #n_test = len(test_data)   #感觉无用
        if test_data: n_test = len(test_data)
        #该语句的意思就是当test_data不是None时,执行冒号后面的语句,即n_test = len(test_data)
        training_data=list(training_data)
        n = len(training_data)
        for j in range(epochs):  #在每个迭代期
            random.shuffle(training_data)  #shuffle 将training_data序列所有的元素随机排序
            mini_batches = [
                training_data[k:k+mini_batch_size]#选取一个小批量数据
                for k in range(0, n, mini_batch_size)]  #mini_batch_size即为每次步进的距离
            for mini_batch in mini_batches:
                self.update_mini_batch(mini_batch, eta)  #对每个mini_batch 应用一次梯度下降
            if test_data:
                print ("Epoch {0}: {1} / {2}".format(
                    j, self.evaluate(test_data), n_test))
            else:
                print ("Epoch {0} complete".format(j))

    def update_mini_batch(self, mini_batch, eta):      #通过对每一个mini_batch运用反向传播backpropagation梯度下降,来更新神经网络的weights 和bias
        """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 向量微分算子
        nabla_b = [np.zeros(b.shape) for b in self.biases]
        #https://blog.csdn.net/cpc784221489/article/details/82885590
        # 参考shape讲解,及传入其数组(矩阵)的行和列
        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)#backprop 一种快速计算代价函数梯度的方法 反向传播算法.先不做详细理解,用到之后再看
            nabla_b = [nb+dnb for nb, dnb in list(zip(nabla_b, delta_nabla_b))]
            nabla_w = [nw+dnw for nw, dnw in list(zip(nabla_w, delta_nabla_w))]
        self.weights = [w-(eta/len(mini_batch))*nw
                        for w, nw in list(zip(self.weights, nabla_w))]
        self.biases = [b-(eta/len(mini_batch))*nb
                       for b, nb in list(zip(self.biases, nabla_b))] #参考公式20 公式21可以了解

    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 list(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)

#### Miscellaneous functions
def sigmoid(z):#定义sigmoid函数
    """The sigmoid function."""
    return 1.0/(1.0+np.exp(-z))

def sigmoid_prime(z):
    """Derivative of the sigmoid function."""
    return sigmoid(z)*(1-sigmoid(z))

minist_loader.py

"""
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
import pickle
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.
    """
    f = gzip.open('../data/mnist.pkl.gz', 'rb')  #rb 以二进制读方式打开
    training_data, validation_data, test_data = pickle.load(f,encoding='bytes')#该方法实现的是将序列化的对象从文件file中读取出来
    f.close()
    return (training_data, validation_data, test_data)

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])
    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
'''
用于测试
load_data()
load_data_wrapper()
e=vectorized_result(5)
print(e)
'''
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值