mxnet-symbol学习第一课

本文详细介绍了MXNet中的Symbol API,包括如何使用符号构建神经网络结构图,如何通过bind函数将NDArrays与symbol节点绑定生成Executor,以及如何执行前向传播获取计算结果。同时,还探讨了多输出绑定、bind函数参数详解及Executor的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值