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 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章