继承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基础命令---comm

    comm 逐行比较两个已经排序过的文件.结果以3列显示:第1列显示只在file1出现的内容,第2列显示只在file2出现的内容,第3列显示同时出现的内容. 此命令的适用范围:RedHat.RHEL.U ...

  2. checkbox的readonly不起作用的解决方案

    checkbox的readonly不起作用的解决方案 <input type="checkbox" readonly /> checkbox没有readOnly属性,r ...

  3. MySQL Crash Course #08# Chapter 16. Using Different Join Types

    记文档还是相当重要的! 索引 假名的三个用途 自交(Self Joins) 自然交(Natural Joins) Outer Joins Using Table Aliases Using alias ...

  4. rabbitmq架构简介(包括集群)

    总的来说,rabbitmq使用erlang语言编写,其架构类似于servlet容器运行servlet应用,底层是erlang VM.然后是erlang节点,上面是应用.如下所示: 每个MQ中运行的应用 ...

  5. 01: Centos7 常用命令

    1.1 centos7中防火墙相关命令 1.查看状态 1.  getenforce           # 查看内核防火墙状态(disabled标识关闭) 2.  systemctl status f ...

  6. 自动对比度的opencv实现

    在http://www.cnblogs.com/Imageshop/archive/2011/11/13/2247614.html 一文中,作者给出了“自动对比度”的实现方法,非常nice 实际实现过 ...

  7. intent bundle的使用

    1.什么是bundle Bundle主要用于传递数据:它保存的数据,是以key-value(键值对)的形式存在的.我们经常使用Bundle在Activity之间传递数据,传递的数据可以是boolean ...

  8. Specify Computed Columns in a Table

    https://docs.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table ...

  9. 51nod 1083 矩阵取数问题

    就很简单很简单的dp 只能从右或者从下走 所以  dp方程直接看下面公式吧  反正也不难 #include<bits/stdc++.h> using namespace std; ; in ...

  10. js与jquery对象的互转

    //dom对象 var odiv = document.getElementById('box'); //dom对象转化成JQ对象, 在通过原生的方法获取到元素后,给它加上$() //$(odiv). ...