日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

mxnet symbol 解析

發(fā)布時(shí)間:2023/12/16 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mxnet symbol 解析 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

mxnet symbol類定義:https://github.com/apache/incubator-mxnet/blob/master/python/mxnet/symbol/symbol.py

對(duì)于一個(gè)symbol,可分為non-grouped和grouped。且symbol具有輸出,和輸出屬性。比如,對(duì)于Variable而言,其輸入和輸出就是它自己。對(duì)于c = a+b,c的內(nèi)部有個(gè)_plus0 symbol,對(duì)于_plus0這個(gè)symbol,它的輸入是a,b,輸出是_plus0_output。

class Symbol(SymbolBase):"""Symbol is symbolic graph of the mxnet."""# disable dictionary storage, also do not have parent type.# pylint: disable=no-member

其中,Symbol還不是最基礎(chǔ)的類,Symbol類繼承了SymbolBase這個(gè)類。
而SymbolBase這個(gè)類實(shí)際是在

https://github.com/apache/incubator-mxnet/blob/master/python/mxnet/symbol/_internal.py

中引用的,通過(guò)以下方式引用:

from .._ctypes.symbol import SymbolBase, _set_symbol_class, _set_np_symbol_class

而SymbolBase的定義是在:https://github.com/apache/incubator-mxnet/blob/master/python/mxnet/_ctypes/symbol.py
這里暫時(shí)先不管SymbolBase,這應(yīng)該是是python調(diào)用c++接口創(chuàng)建的一個(gè)類。

回到Symbol中來(lái),對(duì)于mxnet符號(hào)式編程而言,定義的任何網(wǎng)絡(luò),或者變量,都是symbol類型,所以,了解這個(gè)類就顯得很重要。

Symbol類中有幾類函數(shù):
1、普通函數(shù)
2、__xx__ 函數(shù)
3、@property 修飾的函數(shù)
4、函數(shù)名為xx,實(shí)際調(diào)用op.xx的函數(shù)

1、普通函數(shù)
attr
根據(jù)key返回symbol對(duì)應(yīng)的屬性字符串,只對(duì)non-grouped symbols起作用。

def attr(self, key):"""Returns the attribute string for corresponding input key from the symbol.

list_attr
得到symbol的所有屬性

def list_attr(self, recursive=False):"""Gets all attributes from the symbol.

attr_dict
遞歸的得到symbol和孩子的屬性

def attr_dict(self):"""Recursively gets all attributes from the symbol and its children.Example------->>> a = mx.sym.Variable('a', attr={'a1':'a2'})>>> b = mx.sym.Variable('b', attr={'b1':'b2'})>>> c = a+b>>> c.attr_dict(){'a': {'a1': 'a2'}, 'b': {'b1': 'b2'}}

_set_attr
通過(guò)key-value方式,對(duì)attr進(jìn)行設(shè)置

def _set_attr(self, **kwargs):"""Sets an attribute of the symbol.For example. A._set_attr(foo="bar") adds the mapping ``"{foo: bar}"``to the symbol's attribute dictionary.

get_internals
獲取symbol的所有內(nèi)部節(jié)點(diǎn)symbol,是一個(gè)group類型(包括輸入,輸出節(jié)點(diǎn)symbol)。如果我們想階段一個(gè)network,應(yīng)該獲取它某內(nèi)部節(jié)點(diǎn)的輸出,這樣才能作為新增加的symbol的輸入。

def get_internals(self):"""Gets a new grouped symbol `sgroup`. The output of `sgroup` is a list ofoutputs of all of the internal nodes.

get_children
獲取當(dāng)前symbol輸出節(jié)點(diǎn)的inputs

def get_children(self):"""Gets a new grouped symbol whose output containsinputs to output nodes of the original symbol.

list_arguments
列出當(dāng)前symbol的所有參數(shù)(可以配合call對(duì)symbol進(jìn)行改造)

def list_arguments(self):"""Lists all the arguments in the symbol.

list_outputs
列出當(dāng)前smybol的所有輸出,如果當(dāng)前symbol是grouped類型,回遍歷輸出每一個(gè)symbol的輸出

def list_outputs(self):"""Lists all the outputs in the symbol.

list_auxiliary_states
列出symbol中的輔助狀態(tài)參數(shù),比如BN

def list_auxiliary_states(self):"""Lists all the auxiliary states in the symbol.Example------->>> a = mx.sym.var('a')>>> b = mx.sym.var('b')>>> c = a + b>>> c.list_auxiliary_states()[]Example of auxiliary states in `BatchNorm`.

list_inputs
列出當(dāng)前symbol的所有輸入?yún)?shù),和輔助狀態(tài),等價(jià)于 list_arguments和 list_auxiliary_states

def list_inputs(self):"""Lists all arguments and auxiliary states of this Symbol.

2、__xx__函數(shù)

__repr__
對(duì)于gruop symbol,它是沒(méi)有name屬性的,print或者回車,結(jié)果就是其內(nèi)部symbol節(jié)點(diǎn)的name

__iter__(self):
普通的symbol長(zhǎng)度都只有1,只有Grouped 的symbol,長(zhǎng)度才大于1:return (self[i] for i in range(len(self)))
算數(shù)及邏輯運(yùn)算:
+,-,*, /,%,abs,**, 取負(fù)(-x),==,!=,>,>=,<,<=, # 使用時(shí),要注意Broadcasting 是否支持

def __abs__(self):"""x.__abs__() <=> abs(x) <=> x.abs() <=> mx.symbol.abs(x, y)"""return self.abs()def __add__(self, other):"""x.__add__(y) <=> x+y其他

__copy__和__deep_copy__
通過(guò)deep_copy,創(chuàng)建一個(gè)深拷貝,返回輸入對(duì)象的一個(gè)拷貝,包括它當(dāng)前所有參數(shù)的當(dāng)前狀態(tài),比如weight,bias等

__call__
表示symbol的實(shí)例是一個(gè)可調(diào)用對(duì)象。可以返回一個(gè)新的symbol,這個(gè)symbol繼承了之前symbol的權(quán)重啥的,但是和之前的symbol是不同的對(duì)象,可以輸入?yún)?shù)對(duì)symbol進(jìn)行組合。

def __call__(self, *args, **kwargs):"""Composes symbol using inputs.Returns-------The resulting symbol."""s = self.__copy__() # 這里對(duì)symbol實(shí)例做了一次深拷貝,返回的新的symbols._compose(*args, **kwargs) # 實(shí)際調(diào)用的_compose函數(shù)return s# 對(duì)當(dāng)前的symbol進(jìn)行編譯,返回一個(gè)新的symbol,可以指定新symbol的name,其他輸入?yún)?shù)必須是symbol類型# 當(dāng)前symbol的輸入?yún)?shù),可以通過(guò) .list_arguments()獲取def _compose(self, *args, **kwargs):"""Composes symbol using inputs.x._compose(y, z) <=> x(y,z)This function mutates the current symbol.Example-------Returns-------The resulting symbol."""name = kwargs.pop('name', None)if name:name = c_str(name)if len(args) != 0 and len(kwargs) != 0:raise TypeError('compose only accept input Symbols \either as positional or keyword arguments, not both')

這里,我改變了b,將其輸入?yún)?shù)的x的值變?yōu)榱藅t。

__getitem__
如果symbol的長(zhǎng)度只有1,那么返回的就是它的輸出symbol,如果symbol長(zhǎng)度>1,可以通過(guò)切片訪問(wèn)其輸出symbol,返回的也是一個(gè)Group symbol。symbol可以分為non-grouped和grouped。
獲取內(nèi)部節(jié)點(diǎn)symbol還可以輸入str,但輸入的str必須屬于list_outputs(),

def __getitem__(self, index):"""x.__getitem__(i) <=> x[i]Returns a sliced view of the input symbol.Parameters----------index : int or strIndexing key"""output_count = len(self)if isinstance(index, py_slice):# 輸入切片if isinstance(index, string_types):# 輸入字符串# Returning this list of names is expensive. Some symbols may have hundreds of outputsoutput_names = self.list_outputs()idx = Nonefor i, name in enumerate(output_names):if name == index:if idx is not None:raise ValueError('There are multiple outputs with name \"%s\"' % index)idx = iif idx is None:raise ValueError('Cannot find output that matches name \"%s\"' % index)index = idx

symbol.py 除了Symbol這個(gè)類之外,還有游離在外的函數(shù):

1def var(name, attr=None, shape=None, lr_mult=None, wd_mult=None, dtype=None,init=None, stype=None, **kwargs):"""Creates a symbolic variable with specified name. # for back compatibility Variable = var # 調(diào)用 mx.sym.var和mx.sym.Variable 等價(jià)2、 def Group(symbols, create_fn=Symbol):"""Creates a symbol that contains a collection of other symbols, grouped together.A classic symbol (`mx.sym.Symbol`) will be returned if all the symbols in the listare of that type; a numpy symbol (`mx.sym.np._Symbol`) will be returned if all thesymbols in the list are of that type. A type error will be raised if a list of mixedclassic and numpy symbols are provided.Example------->>> a = mx.sym.Variable('a')>>> b = mx.sym.Variable('b')>>> mx.sym.Group([a,b])<Symbol Grouped>Parameters----------symbols : listList of symbols to be grouped.3def load(fname):"""Loads symbol from a JSON file.You also get the benefit being able to directly load/save from cloud storage(S3, HDFS).Returns-------sym : SymbolThe loaded symbol.See Also--------Symbol.save : Used to save symbol into file. # 輸入文件可以是hdfs文件 4、 數(shù)學(xué)相關(guān)函數(shù),輸入可為scalar或者是symbol def pow(base, exp):"""Returns element-wise result of base element raised to powers from exp element.base 和 exp可以是數(shù)字或者symbol # def power(base, exp): # 實(shí)際調(diào)用pow def maximum(left, right): def minimum(left, right): def hypot(left, right): # 返回直角三角形的斜邊 def eye(N, M=0, k=0, dtype=None, **kwargs):"""Returns a new symbol of 2-D shpae, filled with ones on the diagonal and zeros elsewhere. # 返回2D shape的symbol,對(duì)角線為1,其余位置為0 def zeros(shape, dtype=None, **kwargs):"""Returns a new symbol of given shape and type, filled with zeros. # 返回一個(gè)shape的全0 symbol def ones(shape, dtype=None, **kwargs):"""Returns a new symbol of given shape and type, filled with ones. def full(shape, val, dtype=None, **kwargs):"""Returns a new array of given shape and type, filled with the given value `val`. def arange(start, stop=None, step=1.0, repeat=1, infer_range=False, name=None, dtype=None):"""Returns evenly spaced values within a given interval. def arange(start, stop=None, step=1.0, repeat=1, infer_range=False, name=None, dtype=None):"""Returns evenly spaced values within a given interval. def linspace(start, stop, num, endpoint=True, name=None, dtype=None):"""Return evenly spaced numbers within a specified interval. def histogram(a, bins=10, range=None, **kwargs):"""Compute the histogram of the input data. def split_v2(ary, indices_or_sections, axis=0, squeeze_axis=False):"""Split an array into multiple sub-arrays.

總結(jié)

以上是生活随笔為你收集整理的mxnet symbol 解析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。