继承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. python网络编程之一

    套接字的详细介绍会在另一篇博文指出,此片博文主要是python套接字的简单客户端编写. 两种套接字介绍: 面向连接的套接字:面向连接的套接字提供序列化,可靠的和不重复的数据交付.面向连接是可靠的传输, ...

  2. Python3 打开 https 链接,异常:“SSL: CERTIFICATE_VERIFY_FAILED”

    Python3 打开 https 链接,异常:“SSL: CERTIFICATE_VERIFY_FAILED” 一.问题 Python2.7.9 之后,当使用urllib.urlopen打开一个 ht ...

  3. Go第十一篇之编译与工具

    Go 语言的工具链非常丰富,从获取源码.编译.文档.测试.性能分析,到源码格式化.源码提示.重构工具等应有尽有. 在 Go 语言中可以使用测试框架编写单元测试,使用统一的命令行即可测试及输出测试报告的 ...

  4. USB Compound Device,USB复合设备 ; USB Composite Device,USB组合设备【转】

    本文转载自:https://blog.csdn.net/autumn20080101/article/details/52776863 科普下USB复合设备和USB组合设备的区别. 关键字 Commu ...

  5. Linux文件时间详解ctime、mtime、atime【转】

    本文转载自:http://blog.csdn.net/doiido/article/details/43792561 Linux系统文件有三个主要的时间属性,分别是 ctime(change time ...

  6. 【建表】ElasticSearch建表命令

    使用google插件Postman 发送方式为PUT,url地址: 192.168.2.11:9200/IndexName 文本raw,数据为json格式 { "settings" ...

  7. 【入门教程】kafka环境搭建以及基础教程

    问题导读 1.Kafka独特设计在什么地方?2.Kafka如何搭建及创建topic.发送消息.消费消息?3.如何书写Kafka程序?4.数据传输的事务定义有哪三种?5.Kafka判断一个节点是否活着有 ...

  8. 第八章 对称加密算法--AES

    注意:本节内容主要参考自<Java加密与解密的艺术(第2版)>第7章“初等加密算法--对称加密算法” 8.1.AES 特点: 密钥建立时间短.灵敏性好.内存需求低(不管怎样,反正就是好) ...

  9. maven 插件在线安装

    NO.1 在Eclipse中安装Maven插件安装详解 前言 本来是没打算写博客的,作为一个13年毕业的菜鸟,自认为水平太渣写不出什么好文章,但是前些日子看到一篇鼓励性质的文章说,技术人员的成长靠的就 ...

  10. The way to Go(7): 常量

    Reference: Github: Go Github: The way to Go 常量 常量使用关键字 const 定义,用于存储不会改变的数据. const identifier [type] ...