JS技术

手把手入门神经网络系列(2)_74行代码实现手写数字识别 - 寒小阳 - 博客频道 - CSDN.NET 寒小阳 专注机(2)

字号+ 作者:H5之家 来源:H5之家 2015-12-14 16:23 我要评论( )

总共的输出结果如下: Epoch 0: 9045 / 10000Epoch 1: 9207 / 10000Epoch 2: 9273 / 10000Epoch 3: 9302 / 10000Epoch 4: 9320 / 10000Epoch 5: 9320 / 10000Epoch 6: 9366 / 10000Epoch 7: 9387 / 10000Epoch 8: 9

总共的输出结果如下:

Epoch 0: 9045 / 10000 Epoch 1: 9207 / 10000 Epoch 2: 9273 / 10000 Epoch 3: 9302 / 10000 Epoch 4: 9320 / 10000 Epoch 5: 9320 / 10000 Epoch 6: 9366 / 10000 Epoch 7: 9387 / 10000 Epoch 8: 9427 / 10000 Epoch 9: 9402 / 10000 Epoch 10: 9400 / 10000 Epoch 11: 9442 / 10000 Epoch 12: 9448 / 10000 Epoch 13: 9441 / 10000 Epoch 14: 9443 / 10000 Epoch 15: 9479 / 10000 Epoch 16: 9459 / 10000 Epoch 17: 9446 / 10000 Epoch 18: 9467 / 10000 Epoch 19: 9470 / 10000 Epoch 20: 9459 / 10000 Epoch 21: 9484 / 10000 Epoch 22: 9479 / 10000 Epoch 23: 9475 / 10000 Epoch 24: 9482 / 10000 Epoch 25: 9489 / 10000 Epoch 26: 9489 / 10000 Epoch 27: 9478 / 10000 Epoch 28: 9480 / 10000 Epoch 29: 9476 / 10000 5、神经网络如何识别手写数字:启发式理解

首先,我们解释一下神经网络每层的功能。


神经网络每层



第一层是输入层。因为mnist数据集中每一个手写数字样本是一个28*28像素的图像,因此对于每一个样本,其输入的信息就是每一个像素对应的灰度,总共有28*28=784个像素,故这一层有784个节点。

第三层是输出层。因为阿拉伯数字总共有10个,我们就要将样本分成10个类别,因此输出层我们采用10个节点。当样本属于某一类(某个数字)的时候,则该类(该数字)对应的节点为1,而剩下9个节点为0,如[0,0,0,1,0,0,0,0,0,0]。

因此,我们每一个样本(手写数字的图像)可以用一个超长的784维的向量表示其特征,而用一个10维向量表示该样本所属的类别(代表的真实数字),或者叫做标签。

mnist的数据就是这样表示的。所以,如果你想看训练集中第n个样本的784维特征向量,直接看training_data[n][0]就可以找到,而要看其所属的标签,看training_data[n][1]就够了。

那么,第二层神经网络所代表的意义怎么理解?这其实是很难的。但是我们可以有一个启发式地理解,比如用中间层的某一个节点表示图像中的某一个小区域的特定图像。这样,我们可以假设中间层的头4个节点依次用来识别图像左上、右上、左下、右下4个区域是否存在这样的特征的。

左上

右上、左下、右下

如果这四个节点的值都很高,说明这四个区域同时满足这些特征。将以上的四个部分拼接起来,我们会发现,输入样本很可能就是一个手写“0”!


0



因此,同一层的几个神经元同时被激活了意味着输入样本很可能是某个数字。

当然,这只是对神经网络作用机制的一个启发式理解。真实的过程却并不一定是这样。但通过启发式理解,我们可以对神经网络作用机制有一个更加直观的认识。

由此可见,神经网络能够识别手写数字的关键是它有能够对特定的图像激发特定的节点。而神经网络之所以能够针对性地激发这些节点,关键是它具有能够适应相关问题场景的权重和偏移。那这些权重和偏移如何训练呢?

6、神经网络如何训练:进一步阅读代码

上文已经图解的方式介绍了机器学习解决问题的一般思路,但是具体到神经网络将是如何训练呢?

其实最快的方式是直接阅读代码。我们将代码的结构用下图展示出来,运用其内置函数名表示基本过程,发现与我们上文分析的思路一模一样:


分析思路



简单解释一下,在神经网络模型中:

全部代码如下(去掉注释之后,只有74行):

""" 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. """ random # Third-party libraries import numpy as np : : """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.""" 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:])] : """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.""" if test_data: n_test = len(test_data) n = len(training_data) for j in xrange(epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size)] for mini_batch in mini_batches: self.update_mini_batch(mini_batch, eta) if test_data: print "Epoch {0}: {1} / {2}".format( j, self.evaluate(test_data), n_test) else: print "Epoch {0} complete".format(j) : """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)] : """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()) l in xrange(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) : """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) : """Return the vector of partial derivatives \partial C_x / \partial a for the output activations.""" return (output_activations-y) : /(1.0+np.exp(-z)) : """Derivative of the sigmoid function.""" return sigmoid(z)*(1-sigmoid(z)) 7、神经网络如何优化:训练超参数与多种模型对比

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 零基础入门学习Python(10):函数 - qq_33256568的博客 - 博客频道 - CSDN.NET qq_3

    零基础入门学习Python(10):函数 - qq_33256568的博客 - 博客频道

    2015-12-15 09:04

  • 手把手入门神经网络系列(2)_74行代码实现手写数字识别 - 龙心尘 - 博客频道 - CSDN.NET 龙心尘 目录视

    手把手入门神经网络系列(2)_74行代码实现手写数字识别 - 龙心尘 - 博

    2015-12-14 16:29

  • 2015年最新Android基础入门教程目录(完结版) - coder-pig的猪栏 - 博客频道 - CSDN.NET

    2015年最新Android基础入门教程目录(完结版) - coder-pig的猪栏 - 博

    2015-12-14 15:12

  • 【OpenCV入门教程之三】 图像的载入,显示和输出 一站式完全解析 - 【C++游戏编程】微软最有价值专家—毛星云(浅

    【OpenCV入门教程之三】 图像的载入,显示和输出 一站式完全解析 -

    2015-12-13 10:14

网友点评
s