实现属于自己的TensorFlow(一) - 计算图与前向传播

前言

前段时间因为课题需要使用了一段时间TensorFlow,感觉这种框架很有意思,除了可以搭建复杂的神经网络,也可以优化其他自己需要的计算模型,所以一直想自己学习一下写一个类似的图计算框架。前几天组会开完决定着手实现一个模仿TensorFlow接口的简陋版本图计算框架以学习计算图程序的编写以及前向传播和反向传播的实现。目前实现了前向传播和反向传播以及梯度下降优化器,并写了个优化线性模型的例子。

代码放在了GitHub上,取名SimpleFlow, 仓库链接:

  
  
  1. https://github.com/PytLab/simpleflow

虽然前向传播反向传播这些原理了解起来并不是很复杂,但是真正着手写起来才发现,里面还是有很多细节需要学习和处理才能对实际的模型进行优化(例如Loss函数对每个计算节点矩阵求导的处理)。其中SimpleFlow的代码并没有考虑太多的东西比如dtype和张量size的检查等,因为只是为了实现主要图计算功能并没有考虑任何的优化, 内部张量运算使用的Numpy的接口(毕竟是学习和练手的目的嘛)。

好久时间没更新博客了,在接下来的几篇里面我将把实现的过程的细节总结一下,希望可以给后面学习的童鞋做个参考。

正文

本文主要介绍计算图以及前向传播的实现, 主要涉及图的构建以及通过对构建好的图进行后序遍历然后进行前向传播计算得到具体节点上的输出值。

先贴上一个简单的实现效果吧:

  
  
  1. import simpleflow as sf

  2. # Create a graph

  3. with sf.Graph().as_default():

  4.    a = sf.constant(1.0, name='a')

  5.    b = sf.constant(2.0, name='b')

  6.    result = sf.add(a, b, name='result')

  7.    # Create a session to compute

  8.    with tf.Session() as sess:

  9.        print(sess.run(result))

计算图(Computational Graph)

计算图是计算代数中的一个基础处理方法,我们可以通过一个有向图来表示一个给定的数学表达式,并可以根据图的特点快速方便对表达式中的变量进行求导。而神经网络的本质就是一个多层复合函数, 因此也可以通过一个图来表示其表达式。

本部分主要总结计算图的实现,在计算图这个有向图中,每个节点代表着一种特定的运算例如求和,乘积,向量乘积,平方等等… 例如求和表达式 f(x, y)=x+y 使用有向图表示为:

表达式 f(x,y,z)=z(x+y) 使用有向图表示为:

与TensorFlow的实现不同,为了简化,在SimpleFlow中我并没有定义Tensor类来表示计算图中节点之间的数据流动,而是直接定义节点的类型,其中主要定义了四种类型来表示图中的节点:

1、Operation: 操作节点主要接受一个或者两个输入节点然后进行简单的操作运算,例如上图中的加法操作和乘法操作等。

2、Variable: 没有输入节点的节点,此节点包含的数据在运算过程中是可以变化的。

3、Constant: 类似Variable节点,也没有输入节点,此节点中的数据在图的运算过程中不会发生变化

4、Placeholder: 同样没有输入节点,此节点的数据是通过图建立好以后通过用户传入的

其实图中的所有节点都可以看成是某种操作,其中Variable, Constant, Placeholder都是一种特殊的操作,只是相对于普通的Operation而言,他们没有输入,但是都会有输出(像上图中的xx, yy节点,他们本身输出自身的值到++节点中去),通常会输出到Operation节点,进行进一步的计算。

下面我们主要介绍如何实现计算图的基本组件: 节点和边。

Operation节点

节点表示操作,边代表节点接收和输出的数据,操作节点需要含有以下属性:

1、input_nodes: 输入节点,里面存放与当前节点相连接的输入节点的引用

2、output_nodes: 输出节点, 存放以当前节点作为输入的节点,也就是当前节点的去向

3、outputvalue: 存储当前节点的数值, 如果是Add节点,此变量就存储两个输入节点outputvalue的和

4、name: 当前节点的名称

5、graph: 此节点所属的图 下面我们定义了Operation基类用于表示图中的操作节点(详见https://github.com/PytLab/simpleflow/blob/master/simpleflow/operations.py):

  
  
  1. class Operation(object):

  2.    ''' Base class for all operations in simpleflow.

  3.    An operation is a node in computational graph receiving zero or more nodes

  4.    as input and produce zero or more nodes as output. Vertices could be an

  5.    operation, variable or placeholder.

  6.    '''

  7.    def __init__(self, *input_nodes, name=None):

  8.        ''' Operation constructor.

  9.        :param input_nodes: Input nodes for the operation node.

  10.        :type input_nodes: Objects of `Operation`, `Variable` or `Placeholder`.

  11.        :param name: The operation name.

  12.        :type name: str.

  13.        '''

  14.        # Nodes received by this operation.

  15.        self.input_nodes = input_nodes

  16.        # Nodes that receive this operation node as input.

  17.        self.output_nodes = []

  18.        # Output value of this operation in session execution.

  19.        self.output_value = None

  20.        # Operation name.

  21.        self.name = name

  22.        # Graph the operation belongs to.

  23.        self.graph = DEFAULT_GRAPH

  24.        # Add this operation node to destination lists in its input nodes.

  25.        for node in input_nodes:

  26.            node.output_nodes.append(self)

  27.        # Add this operation to default graph.

  28.        self.graph.operations.append(self)

  29.    def compute_output(self):

  30.        ''' Compute and return the output value of the operation.

  31.        '''

  32.        raise NotImplementedError

  33.    def compute_gradient(self, grad=None):

  34.        ''' Compute and return the gradient of the operation wrt inputs.

  35.        '''

  36.        raise NotImplementedError

在初始化方法中除了定义上面提到的属性外,还需要进行两个操作:

1、将当前节点的引用添加到他输入节点的output_nodes这样可以在输入节点中找到当前节点。

2、将当前节点的引用添加到图中,方便后面对图中的资源进行回收等操作

另外,每个操作节点还有两个必须的方法: computoutput和computegradient. 他们分别负责根据输入节点的值计算当前节点的输出值和根据操作属性和当前节点的值计算梯度。关于梯度的计算将在后续的文章中详细介绍,本文只对节点输出值的计算进行介绍。

下面我以求和操作为例来说明具体操作节点的实现:

  
  
  1. class Add(Operation):

  2.    ''' An addition operation.

  3.    '''

  4.    def __init__(self, x, y, name=None):

  5.        ''' Addition constructor.

  6.        :param x: The first input node.

  7.        :type x: Object of `Operation`, `Variable` or `Placeholder`.

  8.        :param y: The second input node.

  9.        :type y: Object of `Operation`, `Variable` or `Placeholder`.

  10.        :param name: The operation name.

  11.        :type name: str.

  12.        '''

  13.        super(self.__class__, self).__init__(x, y, name=name)

  14.    def compute_output(self):

  15.        ''' Compute and return the value of addition operation.

  16.        '''

  17.        x, y = self.input_nodes

  18.        self.output_value = np.add(x.output_value, y.output_value)

  19.        return self.output_value

可见,计算当前节点output_value的值的前提条件就是他的输入节点的值在此之前已经计算得到了。

Variable节点

与Operation节点类似,Variable节点也需要outputvalue, outputnodes等属性,但是它没有输入节点,也就没有inputnodes属性了,而是需要在创建的时候确定一个初始值initialvalue:

  
  
  1. class Variable(object):

  2.    ''' Variable node in computational graph.

  3.    '''

  4.    def __init__(self, initial_value=None, name=None, trainable=True):

  5.        ''' Variable constructor.

  6.        :param initial_value: The initial value of the variable.

  7.        :type initial_value: number or a ndarray.

  8.        :param name: Name of the variable.

  9.        :type name: str.

  10.        '''

  11.        # Variable initial value.

  12.        self.initial_value = initial_value

  13.        # Output value of this operation in session execution.

  14.        self.output_value = None

  15.        # Nodes that receive this variable node as input.

  16.        self.output_nodes = []

  17.        # Variable name.

  18.        self.name = name

  19.        # Graph the variable belongs to.

  20.        self.graph = DEFAULT_GRAPH

  21.        # Add to the currently active default graph.

  22.        self.graph.variables.append(self)

  23.        if trainable:

  24.            self.graph.trainable_variables.append(self)

  25.    def compute_output(self):

  26.        ''' Compute and return the variable value.

  27.        '''

  28.        if self.output_value is None:

  29.            self.output_value = self.initial_value

  30.        return self.output_value

Constant节点和Placeholder节点

Constant和Placeholder节点与Variable节点类似,具体实现详见:

  
  
  1. https://github.com/PytLab/simpleflow/blob/master/simpleflow/operations.py

计算图对象

在定义了图中的节点后我们需要将定义好的节点放入到一个图中统一保管,因此就需要定义一个Graph类来存放创建的节点,方便统一操作图中节点的资源。

  
  
  1. class Graph(object):

  2.    ''' Graph containing all computing nodes.

  3.    '''

  4.    def __init__(self):

  5.        ''' Graph constructor.

  6.        '''

  7.        self.operations, self.constants, self.placeholders = [], [], []

  8.        self.variables, self.trainable_variables = [], []

为了提供一个默认的图,在导入simpleflow模块的时候创建一个全局变量来引用默认的图:

  
  
  1. from .graph import Graph

  2. # Create a default graph.

  3. import builtins

  4. DEFAULT_GRAPH = builtins.DEFAULT_GRAPH = Graph()

为了模仿TensorFlow的接口,我们给Graph添加上下文管理器协议方法使其成为一个上下文管理器, 同时也添加一个as_default方法:

  
  
  1. class Graph(object):

  2.    #...

  3.    def __enter__(self):

  4.        ''' Reset default graph.

  5.        '''

  6.        global DEFAULT_GRAPH

  7.        self.old_graph = DEFAULT_GRAPH

  8.        DEFAULT_GRAPH = self

  9.        return self

  10.    def __exit__(self, exc_type, exc_value, exc_tb):

  11.        ''' Recover default graph.

  12.        '''

  13.        global DEFAULT_GRAPH

  14.        DEFAULT_GRAPH = self.old_graph

  15.    def as_default(self):

  16.        ''' Set this graph as global default graph.

  17.        '''

  18.        return self

这样在进入with代码块之前先保存旧的默认图对象然后将当前图赋值给全局图对象,这样with代码块中的节点默认会添加到当前的图中。最后退出with代码块时再对图进行恢复即可。这样我们可以按照TensorFlow的方式来在某个图中创建节点.

Ok,根据上面的实现我们已经可以创建一个计算图了:

  
  
  1. import simpleflow as sf

  2. with sf.Graph().as_default():

  3.    a = sf.constant([1.0, 2.0], name='a')

  4.    b = sf.constant(2.0, name='b')

  5.    c = a * b

前向传播(Feedforward)

实现了计算图和图中的节点,我们需要对计算图进行计算, 本部分对计算图的前向传播的实现进行总结。

会话

首先,我们需要实现一个Session来对一个已经创建好的计算图进行计算,因为当我们创建我们之前定义的节点的时候其实只是创建了一个空节点,节点中并没有数值可以用来计算,也就是output_value是空的。为了模仿TensorFlow的接口,我们在这里也把session定义成一个上下文管理器:

  
  
  1. class Session(object):

  2.    ''' A session to compute a particular graph.

  3.    '''

  4.    def __init__(self):

  5.        ''' Session constructor.

  6.        '''

  7.        # Graph the session computes for.

  8.        self.graph = DEFAULT_GRAPH

  9.    def __enter__(self):

  10.        ''' Context management protocal method called before `with-block`.

  11.        '''

  12.        return self

  13.    def __exit__(self, exc_type, exc_value, exc_tb):

  14.        ''' Context management protocal method called after `with-block`.

  15.        '''

  16.        self.close()

  17.    def close(self):

  18.        ''' Free all output values in nodes.

  19.        '''

  20.        all_nodes = (self.graph.constants + self.graph.variables +

  21.                     self.graph.placeholders + self.graph.operations +

  22.                     self.graph.trainable_variables)

  23.        for node in all_nodes:

  24.            node.output_value = None

  25.    def run(self, operation, feed_dict=None):

  26.        ''' Compute the output of an operation.'''

  27.        # ...

计算某个节点的输出值

上面我们已经可以构建出一个计算图了,计算图中的每个节点与其相邻的节点有方向的联系起来,现在我们需要根据图中节点的关系来推算出某个节点的值。那么如何计算呢? 还是以我们刚才 f(x,y,z)=z(x+y) 的计算图为例,

若我们需要计算橙色 X 运算节点的输出值,我们需要计算与它相连的两个输入节点的输出值,进而需要计算绿色 + 的输入节点的输出值。我们可以通过后序遍历来获取计算一个节点所需的所有节点的输出值。为了方便实现,后序遍历我直接使用了递归的方式来实现:

  
  
  1. def _get_prerequisite(operation):

  2.    ''' Perform a post-order traversal to get a list of nodes to be computed in order.

  3.    '''

  4.    postorder_nodes = []

  5.    # Collection nodes recursively.

  6.    def postorder_traverse(operation):

  7.        if isinstance(operation, Operation):

  8.            for input_node in operation.input_nodes:

  9.                postorder_traverse(input_node)

  10.        postorder_nodes.append(operation)

  11.    postorder_traverse(operation)

  12.    return postorder_nodes

通过此函数我们可以获取计算一个节点值所需要所有节点列表,再依次计算列表中节点的输出值,最后便可以轻易的计算出当前节点的输出值了。

  
  
  1. class Session(object):

  2.    # ...

  3.    def run(self, operation, feed_dict=None):

  4.        ''' Compute the output of an operation.

  5.        :param operation: A specific operation to be computed.

  6.        :type operation: object of `Operation`, `Variable` or `Placeholder`.

  7.        :param feed_dict: A mapping between placeholder and its actual value for the session.

  8.        :type feed_dict: dict.

  9.        '''

  10.        # Get all prerequisite nodes using postorder traversal.

  11.        postorder_nodes = _get_prerequisite(operation)

  12.        for node in postorder_nodes:

  13.            if type(node) is Placeholder:

  14.                node.output_value = feed_dict[node]

  15.            else:  # Operation and variable

  16.                node.compute_output()

  17.        return operation.output_value

例子

上面我们实现了计算图以及前向传播,我们就可以创建计算图计算表达式的值了, 如下:

  
  
  1. import simpleflow as sf

  2. # Create a graph

  3. with sf.Graph().as_default():

  4.    w = sf.constant([[1, 2, 3], [3, 4, 5]], name='w')

  5.    x = sf.constant([[9, 8], [7, 6], [10, 11]], name='x')

  6.    b = sf.constant(1.0, 'b')

  7.    result = sf.matmul(w, x) + b

  8.    # Create a session to compute

  9.    with sf.Session() as sess:

  10.        print(sess.run(result))

输出值:

  
  
  1. array([[  54.,   54.],

  2.       [ 106.,  104.]])

总结

本文使用Python实现了计算图以及计算图的前向传播,并模仿TensorFlow的接口创建了Session以及Graph对象。下篇中将继续总结计算图节点计算梯度的方法以及反向传播和梯度下降优化器的实现。

最后再附上simpleflow项目的链接, 欢迎相互学习和交流:

  
  
  1. https://github.com/PytLab/simpleflow

参考

  
  
  1. Deep Learning From Scratch

  2. https://en.wikipedia.org/wiki/Tree_traversal#Post-order

  3. https://zhuanlan.zhihu.com/p/25496760

  4. http://blog.csdn.net/magic_anthony/article/details/77531552


赞赏作者


本文作者

PytLab,Python 中文社区专栏作者。主要从事科学计算与高性能计算领域的应用,主要语言为Python,C,C++。熟悉数值算法(最优化方法,蒙特卡洛算法等)与并行化 算法(MPI,OpenMP等多线程以及多进程并行化)以及python优化方法,经常使用C++给python写扩展。
知乎专栏:化学狗码砖的日常

blog:http://pytlab.org

github:https://github.com/PytLab

点击阅读原文,加入CodingGo编程社区更多阅读请点击:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值