mxnet symbol 解析

2024-04-24 11:08
文章标签 解析 symbol mxnet

本文主要是介绍mxnet symbol 解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

对于一个symbol,可分为non-grouped和grouped。且symbol具有输出,和输出属性。比如,对于Variable而言,其输入和输出就是它自己。对于c = a+b,c的内部有个_plus0 symbol,对于_plus0这个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还不是最基础的类,Symbol类继承了SymbolBase这个类。
而SymbolBase这个类实际是在

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

中引用的,通过以下方式引用:

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
这里暂时先不管SymbolBase,这应该是是python调用c++接口创建的一个类。

回到Symbol中来,对于mxnet符号式编程而言,定义的任何网络,或者变量,都是symbol类型,所以,了解这个类就显得很重要。

Symbol类中有几类函数:
1、普通函数
2、__xx__ 函数
3、@property 修饰的函数
4、函数名为xx,实际调用op.xx的函数

1、普通函数
attr
根据key返回symbol对应的属性字符串,只对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
通过key-value方式,对attr进行设置

    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的所有内部节点symbol,是一个group类型(包括输入,输出节点symbol)。如果我们想阶段一个network,应该获取它某内部节点的输出,这样才能作为新增加的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
获取当前symbol输出节点的inputs

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

list_arguments
列出当前symbol的所有参数(可以配合call对symbol进行改造)

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

list_outputs
列出当前smybol的所有输出,如果当前symbol是grouped类型,回遍历输出每一个symbol的输出

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

list_auxiliary_states
列出symbol中的辅助状态参数,比如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
列出当前symbol的所有输入参数,和辅助状态,等价于 list_arguments和 list_auxiliary_states

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

2、__xx__函数

__repr__
对于gruop symbol,它是没有name属性的,print或者回车,结果就是其内部symbol节点的name
在这里插入图片描述
__iter__(self):
普通的symbol长度都只有1,只有Grouped 的symbol,长度才大于1:return (self[i] for i in range(len(self)))
算数及逻辑运算:
+,-,*, /,%,abs,**, 取负(-x),==,!=,>,>=,<,<=, # 使用时,要注意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__
通过deep_copy,创建一个深拷贝,返回输入对象的一个拷贝,包括它当前所有参数的当前状态,比如weight,bias等
在这里插入图片描述
__call__
表示symbol的实例是一个可调用对象。可以返回一个新的symbol,这个symbol继承了之前symbol的权重啥的,但是和之前的symbol是不同的对象,可以输入参数对symbol进行组合。

    def __call__(self, *args, **kwargs):"""Composes symbol using inputs.Returns-------The resulting symbol."""s = self.__copy__()  #  这里对symbol实例做了一次深拷贝,返回的新的symbols._compose(*args, **kwargs) # 实际调用的_compose函数return s# 对当前的symbol进行编译,返回一个新的symbol,可以指定新symbol的name,其他输入参数必须是symbol类型# 当前symbol的输入参数,可以通过 .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,将其输入参数的x的值变为了tt。
在这里插入图片描述

__getitem__
如果symbol的长度只有1,那么返回的就是它的输出symbol,如果symbol长度>1,可以通过切片访问其输出symbol,返回的也是一个Group symbol。symbol可以分为non-grouped和grouped。
获取内部节点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这个类之外,还有游离在外的函数:

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  #  调用 mx.sym.var和mx.sym.Variable 等价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、
数学相关函数,输入可为scalar或者是symbol
def pow(base, exp):"""Returns element-wise result of base element raised to powers from exp element.base 和 exp可以是数字或者symbol
# def power(base, exp):  #  实际调用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,对角线为1,其余位置为0
def zeros(shape, dtype=None, **kwargs):"""Returns a new symbol of given shape and type, filled with zeros.  # 返回一个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.

这篇关于mxnet symbol 解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/931579

相关文章

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

Redis过期删除机制与内存淘汰策略的解析指南

《Redis过期删除机制与内存淘汰策略的解析指南》在使用Redis构建缓存系统时,很多开发者只设置了EXPIRE但却忽略了背后Redis的过期删除机制与内存淘汰策略,下面小编就来和大家详细介绍一下... 目录1、简述2、Redis http://www.chinasem.cn的过期删除策略(Key Expir

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

springboot项目中使用JOSN解析库的方法

《springboot项目中使用JOSN解析库的方法》JSON,全程是JavaScriptObjectNotation,是一种轻量级的数据交换格式,本文给大家介绍springboot项目中使用JOSN... 目录一、jsON解析简介二、Spring Boot项目中使用JSON解析1、pom.XML文件引入依

Python中文件读取操作漏洞深度解析与防护指南

《Python中文件读取操作漏洞深度解析与防护指南》在Web应用开发中,文件操作是最基础也最危险的功能之一,这篇文章将全面剖析Python环境中常见的文件读取漏洞类型,成因及防护方案,感兴趣的小伙伴可... 目录引言一、静态资源处理中的路径穿越漏洞1.1 典型漏洞场景1.2 os.path.join()的陷