继承CustomOp

  • 定义操作符,重写前向后向方法,此时可以通过_init__ 方法传递需要用到的参数
 class LossLayer(mxnet.operator.CustomOp):
def __init__(self, *args, **kwargs):
super(LossLayer, self).__init__()
# recipe some arguments for forward or backward calculation def forward(self, is_train, req, in_data, out_data, aux):
"""
in_data是一个列表,其中tensor的顺序和对应属性类中定义的list_arguments()参数一一对应
out_data输出列表
is_train 是否是训练过程
req [Null, write or inplace, add]指如何处理对应的复制操作
"""
pass
# 函数最后一般调用父类的self.assign(dst, req[0], src)进行赋值操作
# 但对于dst或者src是list类型的时候要调用多次assign函数处理,此时也可以直接自己赋值
# dst[:]=src def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
"""
out_grad 上一层反传的误差
in_data 输入数据,list
out_data 输出的数据,由forward方法确定, 其类型大小和out_grad一致
in_grad 需要计算的回传误差
"""
pass
# 其操作值得复制操作类似于forward方法
  • 定义好操作符之后还需要定义其对应的属性类,并将其注册到operator中
 @mx.operator.register('losslayer')  # 注意这里注册的名字将是后面调用该操作符使用的类型名
  • 重写对应的属性类
 class LossLayerProp(mx.operator.CustomOpProp): # 这里的名字并非必须对应操作类名称,被@修饰符修饰
def __init__(self, params):
super(LossLayerProp,self).__init__(need_top_grad=False)
# 最后的损失层不需要接收上层的误差,则将need_top_grad设置为False
# 可以传递一些参数用以传递给操作类 def list_arguments(self):
# 这个方法非常重要,定义了该操作符的输入参数,当绑定对应操作符时,输入量由该方法指定
return ['data1','data2','data3','label'] def list_outputs(self):
# 同样返回的是列表,表示输出的量,这个其实是输出变量的后缀suffix
# 若返回的是['output1','output2']则输出为 操作类的名称name加上对应后缀的量[name_output1, name_output2]
return ['output'] def infer_shape(self, in_shape):
# 给定in_shape,显示每一个变量的对应大小,以判断大小是否一致
return [],[],[]
# 返回的必须是3个列表,即使列表为空,分别对应着输入参数的大小、输出数据的大小、aux参数的大小,一般最后一个为空 def infer_type(self, in_type):
# 该方法类似于infer_shape,推断数据类型 def create_operator(self, ctx, shapes, dtypes):
# 该方法真正的创建操作类对象,默认调用
return LossLayer()
  • 自定义操作符的使用
 data1=mx.sym.Variable('data1')
data2=mx.sym.Variable('data2')
data3=mx.sym.Variable('data3')
label = mx.sym.Variable('label')
# 下面这句调用很重要,显示指定输入的symbol,然后指定自定义操作符类型
net = mx.sym.Custom(data1=data1, data2=data2, data3=data3, label=label, name='net', op_type='losslayer')
# 输出操作符的相关属性
print(net.infer_shape(data1=(4,1,10,10), data2=(4,1,10,10),data3=(4,1,10,10) label=(4,)))
# data1=(4,1,10,10)表示对应symbol的shape
print(net.infer_type(data1=np.int, data2=np.int, data3=np.int, label=np.int))
# data1=np.int 标识对应symbol的数据类型
print(net.list_arguments()) # 变量参数
print(net.list_outputs()) #输出的变量参数 ex = net.simple_bind(ctx=mx.gpu(0), data1=(4,1,10,10), data2=(4,1,10,10),data3=(4,1,10,10) label=(4,)) # simple_bind只需要指定输入参数的大小
ex.forward(data1=data1, data2=data2, label=label))
print(ex.outputs[0])
  • 上面是没有参数的层,创建带有参数的中间层和上面类似, 只是修改下面部分代码
 def list_arguments(self):
return ['data','weight', 'bias'] def infer_shape(self, in_shape):
data_shape = in_shape[0]
weight_shape = ...
bias_shape = ...
output_shape = ...
return [data_shape, weight_shape, bias_shape], [output_shape], []

调用方式:

net = mx.symbol.Custom(data, name='newLayer', op_type='myLayer')

包含参数的layer在定义backward方法时要注意梯度的更新方式,即req的选择

NOTE:

有参数的操作符中,一般使用‘weight’和‘bias’作为参数, 该参数会最为后缀加到 opname_weight, opname_bias中,因为mxnet默认的参数初始化方法只认‘weight’, 'bias', 'gamma', 'beta'四个量, 对于自己新定义的量,比如weight2, 需要指定初始化方法

Default initialization is now limited to "weight", "bias", "gamma" (1.0), and "beta" (0.0).
Please use mx.sym.Variable(init=mx.init.*) to set initialization pattern

How to create own operator with python in mxnet?的更多相关文章

  1. error: could not create '/System/Library/Frameworks/Python.framework/Versions/2.7/share': Operation not permitted

    参考: Python pip安装模块报错 Mac升级到EI Captain之后pip install 无法使用问题 error: could not create '/System/Library/F ...

  2. Create your first isolated Python environment

    # Install virtualenv for Python 2.7 and create a sandbox called my27project: pip2. install virtualen ...

  3. [Python] Object spread operator in Python

    In JS, we have object spread opreator: const x = { a: '1', b: '2' } const y = { c: '3', d: '4' } con ...

  4. 使用python创建mxnet操作符(网络层)

    对cuda了解不多,所以使用python创建新的操作层是个不错的选择,当然这个性能不如cuda编写的代码. 在MXNET源码的example/numpy-ops/下有官方提供的使用python编写新操 ...

  5. How to create PDF files in a Python/Django application using ReportLab

    https://assist-software.net/blog/how-create-pdf-files-python-django-application-using-reportlab CONT ...

  6. Think Python - Chapter 17 - Classes and methods

    17.1 Object-oriented featuresPython is an object-oriented programming language, which means that it ...

  7. Think Python - Chapter 11 - Dictionaries

    Dictionaries A dictionary is like a list, but more general. In a list, the indices have to be intege ...

  8. Data manipulation primitives in R and Python

    Data manipulation primitives in R and Python Both R and Python are incredibly good tools to manipula ...

  9. caffe2 教程入门(python版)

    学习思路 1.先看官方文档,学习如何使用python调用caffe2包,包括 Basics of Caffe2 - Workspaces, Operators, and Nets Toy Regres ...

随机推荐

  1. linux服务器---安装swat

    安装swat swat是一个图形化的samba管理软件,可以帮助不熟悉的人去灵活的配置samba服务, 1.安装swat [root@localhost wj]#yum install -y samb ...

  2. Centos7下PHP的卸载与安装nginx

    Centos7下PHP的卸载与安装nginx CentOS上PHP完全卸载,想把PHP卸载干净,直接用yum的remove命令是不行的,需要查看有多少rpm包,然后按照依赖顺序逐一卸载. 1.首先查看 ...

  3. 通过Jenkins + Docker实现antdPro自动化推送私服、自动容器化部署功能

    Docker与Docker私服 1. 安装docker https://docs.docker.com/install/ 2. 配置docker镜像加速 https://www.daocloud.io ...

  4. 根据wsdl,axis2工具生成客户端代码

    根据wsdl,axis2工具生成客户端代码 步骤: 1,下载axis2版本http://axis.apache.org/axis2/java/core/download.html 2,下载完成后解压, ...

  5. 根据wsdl,apache cxf的wsdl2java工具生成客户端、服务端代码

    根据wsdl,apache cxf的wsdl2java工具生成客户端.服务端代码 apache cxf的wsdl2java工具的简单使用: 使用步骤如下: 一.下载apache cxf的包,如apac ...

  6. 【翻译】std::remove - C++ Reference

    函数模板 std::remove 头文件<algorithm> template <class ForwardIterator, class T> ForwardIterato ...

  7. 函数指针(pointer to function)——qsort函数应用实例

    一,举例应用 在ACM比赛中常使用 stdlib.h 中自带的 qsort 函数,是教科书式的函数指针应用示范. #include <stdio.h> #include <stdli ...

  8. 实验二Java面向对象程序设计

    一.单元测试 了解三种代码: 1.伪代码:类似于自然语言说明,描述实现逻辑思维 2.产品代码:程序员编辑的开发代码,要求可修改.可移植 3.测试代码:我理解是相当于开发软件在软件开放之前,程序员找到b ...

  9. C# 将 Stream 写入文件

    public void StreamToFile(Stream stream,string fileName) { // 把 Stream 转换成 byte[] byte[] bytes = new ...

  10. 权限管理,pymysql模块

    权限管理 权限管理重点 MySQL 默认有个root用户,但是这个用户权限太大,一般只在管理数据库时候才用.如果在项目中要连接 MySQL 数据库,则建议新建一个权限较小的用户来连接. 在 MySQL ...