时间: 2020-09-03 00:08:26 人气: 2274 评论: 0
这是《使用腾讯云 GPU 学习深度学习》系列文章的第二篇,主要介绍了 Tensorflow 的原理,以及如何用最简单的Python代码进行功能实现。本系列文章主要介绍如何使用 腾讯云GPU服务器 进行深度学习运算,前面主要介绍原理部分,后期则以实践为主。
往期内容:
使用腾讯云 GPU 学习深度学习系列之一:传统机器学习的回顾
神经网络模型,是上一章节提到的典型的监督学习问题,即我们有一组输入以及对应的目标输出,求最优模型。通过最优模型,当我们有新的输入时,可以得到一个近似真实的预测输出。
我们先看一下如何实现这样一个简单的神经网络:
x = [1,2,3],y = [-0.85, 0.72]求所需参数 w1_0 w2_0 b1_0 b2_0, 使得给定输入 x 下得到的输出 ,和目标输出
之间的平均均方误差 (Mean Square Errors, MSE) 最小化 。
我们首先需要思考,有几个参数?由于是两层神经网络,结构如下图(图片来源http://stackoverflow.com/questions/22054877/backpropagation-training-stuck), 其中输入层为 3,中间层为 4,输出层是 2:
因此,其中总共包含 (3x4+4) + (4*2+2) = 26 个参数需要训练。我们可以如图初始化参数。参数可以随机初始化,也可以随便指定:
# python import numpy as np w1_0 = np.array([[ 0.1, 0.2, 0.3, 0.4], [ 0.5, 0.6, 0.7, 0.8], [ 0.9, 1.0, 1.1, 1.2]]) w2_0 = np.array([[ 1.3, 1.4], [ 1.5, 1.6], [ 1.7, 1.8], [ 1.9, 2.0]]) b1_0 = np.array( [-2.0, -6.0, -1.0, -7.0]) b2_0 = np.array( [-2.5, -5.0])
我们进行一次正向传播:
# python x = [1,2,3] y = [-0.85, 0.72] o1 = np.dot(x, w1_0 ) + b1_0 os1 = np.power(1+np.exp(o1*-1), -1) o2 = np.dot(os1, w2_0) + b2_0 os2 = np.tanh(o2)
再进行一次反向传播:
# python alpha = 0.1 grad_os2 = (y - os2) * (1-np.power(os2, 2)) grad_os1 = np.dot(w2_0, grad_os2.T).T * (1-os1)*os1 grad_w2 = ... grad_b2 = ... ... ... w2_0 = w2_0 + alpha * grad_w2 b2_0 = b2_0 + alpha * grad_b2 ... ...
如此反复多次,直到最终误差收敛。进行反向传播时,需要将所有参数的求导结果都写上去,然后根据求导结果更新参数。我这里就没有写全,因为一层一层推导实在是太过麻烦。更重要的是,当我们需要训练新的神经网络结构时,这些都需要重新推导一次,费时费力。
然而仔细想一想,这个推导的过程也并非无规律可循。即上一级的神经网络梯度输出,会被用作下一级计算梯度的输入,同时下一级计算梯度的输出,会被作为上一级神经网络的输入。于是我们就思考能否将这一过程抽象化,做成一个可以自动求导的框架?OK,以 Tensorflow 为代表的一系列深度学习框架,正是根据这一思路诞生的。
近几年最火的深度学习框架是什么?毫无疑问,Tensorflow 高票当选。
但实际上,这些深度学习框架都具有一些普遍特征。Gokula Krishnan Santhanam认为,大部分深度学习框架都包含以下五个核心组件:
其中,张量 Tensor 可以理解为任意维度的数组——比如一维数组被称作向量(Vector),二维的被称作矩阵(Matrix),这些都属于张量。有了张量,就有对应的基本操作,如取某行某列的值,张量乘以常数等。运用拓展包其实就相当于使用底层计算软件加速运算。
我们今天重点介绍的,就是计算图模型,以及自动微分两部分。首先介绍以 Torch 框架为例,谈谈如何实现自动求导,然后再用最简单的方法,实现这两部分。
诸如 Tensorflow 这样的深度学习框架的入门,网上有大量的 几行代码、几分钟入门这样的资料,可以快速实现手写数字识别等简单任务。但如果想深入了解 Tensorflow 的背后原理,可能就不是这么容易的事情了。这里我们简单的谈一谈这一部分。
我们知道,当我们拿到数据、训练神经网络时,网络中的所有参数都是 变量。训练模型的过程,就是如何得到一组最佳变量,使预测最准确的过程。这个过程实际上就是,输入数据经过 正向传播,变成预测,然后预测与实际情况的误差 反向传播 误差回来,更新变量。如此反复多次,得到最优的参数。这里就会遇到一个问题,神经网络这么多层,如何保证正向、反向传播都可以正确运行?
值得思考的是,这两种传播方式,都具有 管道传播 的特征。正向传播一层一层算就可以了,上一层网络的结果作为下一层的输入。而反向传播过程可以利用 链式求导法则,从后往前,不断将误差分摊到每一个参数的头上。
图片来源:Colah博客
进过抽象化后,我们发现,深度学习框架中的 每一个模块都需要两个函数,一个连接正向,一个连接反向。这里的正向和反向,如同武侠小说中的 任督二脉。而训练模型的过程,数据通过正向传播生成预测结果,进而将误差反向传回更新参数,就如同让真气通过任督二脉在体内游走,随着训练误差逐渐缩小收敛,深度神经网络也将打通任督二脉。
接下来,我们将首先审视一下 Torch 框架的源码如何实现这两部分内容,其次我们通过 Python 直接编写一个最简单的深度学习框架。
举 Torch 的 nn 项目的例子是因为Torch 的代码文件结构比较简单,Tensorflow 的规律和Torch比较近似,但文件结构相对更加复杂,有兴趣的可以仔细读读相关文章。
Torch nn 模块Github 源码 这个目录下的几乎所有 .lua 文件,都有这两个函数:
# lua function xxx:updateOutput(input) input.THNN.xxx_updateOutput( input:cdata(), self.output:cdata() ) return self.output end function xxx:updateGradInput(input, gradOutput) input.THNN.xxx_updateGradInput( input:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.output:cdata() ) return self.gradInput end
这里其实是相当于留了两个方法的定义,没有写具体功能。具体功能的代码,在 ./lib/THNN/generic 目录中用 C 实现实现,具体以 Sigmoid 函数举例。
我们知道 Sigmoid 函数的形式是:
代码实现起来是这样:
# lua void THNN_(Sigmoid_updateOutput)( THNNState *state, THTensor *input, THTensor *output) { THTensor_(resizeAs)(output, input); TH_TENSOR_APPLY2(real, output, real, input, *output_data = 1./(1.+ exp(- *input_data)); ); }
Sigmoid 函数求导变成:
所以这里在实现的时候就是:
// c void THNN_(Sigmoid_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *output) { THNN_CHECK_NELEMENT(input, gradOutput); THTensor_(resizeAs)(gradInput, output); TH_TENSOR_APPLY3(real, gradInput, real, gradOutput, real, output, real z = * output_data; *gradInput_data = *gradOutput_data * (1. - z) * z; ); }
大家应该注意到了一点, updateOutput 函数, output_data 在等号左边, input_data 在等号右边。 而 updateGradInput 函数, gradInput_data 在等号左边, gradOutput_data 在等号右边。 这里,output = f(input) 对应的是 正向传播 input = f(output) 对应的是 反向传播。
这部分内容属于“造轮子”,并且借用了优达学城的一个小型项目 MiniFlow。
首先,我们实现一个父类 Node,然后基于这个父类,依次实现 Input Linear Sigmoid 等模块。这里运用了简单的 Python Class 继承。这些模块中,需要将 forward 和 backward 两个方法针对每个模块分别重写。
代码如下:
# python class Node(object): """ Base class for nodes in the network. Arguments: `inbound_nodes`: A list of nodes with edges into this node. """ def __init__(self, inbound_nodes=[]): """ Node's constructor (runs when the object is instantiated). Sets properties that all nodes need. """ # A list of nodes with edges into this node. self.inbound_nodes = inbound_nodes # The eventual value of this node. Set by running # the forward() method. self.value = None # A list of nodes that this node outputs to. self.outbound_nodes = [] # New property! Keys are the inputs to this node and # their values are the partials of this node with # respect to that input. self.gradients = {} # Sets this node as an outbound node for all of # this node's inputs. for node in inbound_nodes: node.outbound_nodes.append(self) def forward(self): """ Every node that uses this class as a base class will need to define its own `forward` method. """ raise NotImplementedError def backward(self): """ Every node that uses this class as a base class will need to define its own `backward` method. """ raise NotImplementedError class Input(Node): """ A generic input into the network. """ def __init__(self): Node.__init__(self) def forward(self): pass def backward(self): self.gradients = {self: 0} for n in self.outbound_nodes: self.gradients[self] += n.gradients[self] class Linear(Node): """ Represents a node that performs a linear transform. """ def __init__(self, X, W, b): Node.__init__(self, [X, W, b]) def forward(self): """ Performs the math behind a linear transform. """ X = self.inbound_nodes[0].value W = self.inbound_nodes[1].value b = self.inbound_nodes[2].value self.value = np.dot(X 技术沙龙 教程文章 热点综合