mxnet-symbol学习第一课

Symbol API : https://mxnet.incubator.apache.org/api/python/symbol/symbol.html
Symbolic Configuration and Execution in Pictures (一些symbol操作的图示):https://mxnet.incubator.apache.org/versions/master/api/python/symbol_in_pictures/symbol_in_pictures.html
Symbol - Neural network graphs(symbol入门教程): https://mxnet.incubator.apache.org/versions/master/tutorials/basic/symbol.html

用symbol定义网络结构图,执行图的步骤
1、用symbol的一些符号,操作构建网络结构图
2、用bind函数将NDArrays与argument nodes(用symbol生成的一些中间变量节点,或输出变量节点)进行绑定,生成Executor。其实就是将Executor中用到的变量进行赋值。

a = mx.sym.Variable('a')
b = mx.sym.Variable('b')
c = 2*a+b
e = c.bind(ctx=mx.cpu(), args={'a':mx.nd.array([1,2]]), 'b':mx.nd.array([2,3])})

其中,c就是argument nodes,e是生成的Executor。然后执行forward运算,就可以获得计算图的输出。

e.forward()
e.outputs[0]  #  访问计算图的输出值,存放在Executor的outputs变量中

绑定多个输出

mx.sym.Group : Creates a symbol that contains a collection of other symbols, grouped together.
G = mx.sym.Group([E,C])

关于bind函数
We first declare the computation and then bind to the data to run. This function returns an executor which provides method forward() method for evaluation and a outputs() method to get all the results.

bind(ctx, args, args_grad=None, grad_req='write', aux_states=None, group2ctx=None, shared_exec=None)

变量说明:

ctx: 生成的executor需要在哪里执行。ctx=mx.cpu()或ctx=mx.gpu()。
args:list of NDArray or dict of str to NDArray,给之前定义的symbol赋值。args可以是NDArray的list,
但是必须和list_arguments()对应。c=a+b,c.list_arguments() = ['a','b']。或者是字符串到NDArray的字典。
args={'a' : mx.nd.ones([2,3]), 'b' : mx.nd.ones([2,3])},任何情况下,必须提供所有symbol的值。
args_grad:使用方法同args,但是当提供字典时,只需要提供需要计算梯度的键值,用来记录反向传播中变量的梯度值(可以初始化为0)。
grad_req :指定我们如何更新梯度值到args_grad中,有三种方式,'write'表示每次梯度被更新到args_grad NDArray中,'add'表示每次梯度被增加到制定的args_grad,‘null’表示梯度不会被计算。aux_states:指定symbol的辅助状态(前提是输出的list_auxiliary_states() 不为空)。
**返回值**:executor 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章