pytorch自定义二值化网络层方式

yipeiwu_com5年前Python基础

任务要求:

自定义一个层主要是定义该层的实现函数,只需要重载Function的forward和backward函数即可,如下:

import torch
from torch.autograd import Function
from torch.autograd import Variable

定义二值化函数

class BinarizedF(Function):
  def forward(self, input):
    self.save_for_backward(input)
    a = torch.ones_like(input)
    b = -torch.ones_like(input)
    output = torch.where(input>=0,a,b)
    return output
  def backward(self, output_grad):
    input, = self.saved_tensors
    input_abs = torch.abs(input)
    ones = torch.ones_like(input)
    zeros = torch.zeros_like(input)
    input_grad = torch.where(input_abs<=1,ones, zeros)
    return input_grad

定义一个module

class BinarizedModule(nn.Module):
  def __init__(self):
    super(BinarizedModule, self).__init__()
    self.BF = BinarizedF()
  def forward(self,input):
    print(input.shape)
    output =self.BF(input)
    return output

进行测试

a = Variable(torch.randn(4,480,640), requires_grad=True)
output = BinarizedModule()(a)
output.backward(torch.ones(a.size()))
print(a)
print(a.grad)

其中, 二值化函数部分也可以按照方式写,但是速度慢了0.05s

class BinarizedF(Function):
  def forward(self, input):
    self.save_for_backward(input)
    output = torch.ones_like(input)
    output[input<0] = -1
    return output
  def backward(self, output_grad):
    input, = self.saved_tensors
    input_grad = output_grad.clone()
    input_abs = torch.abs(input)
    input_grad[input_abs>1] = 0
    return input_grad

以上这篇pytorch自定义二值化网络层方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python开发编码规范

这篇文档所给出的编码约定适用于在主要的Python发布版本中组成标准库的Python   代码,请查阅相关的关于在Python的C实现中C代码风格指南的描述...

在django-xadmin中APScheduler的启动初始化实例

环境: python3.5.x + django1.9.x + xadmin-for-python3 APScheduler做为一个轻量级和使用量很多的后台任务计划(scheduler)...

python基础教程之简单入门说明(变量和控制语言使用方法)

简介有兴趣可以看看: 解释性语言+动态类型语言+强类型语言交互模式:(主要拿来试验,可以试试 ipython)复制代码 代码如下:$python>>> print 'h...

Python2.7读取PDF文件的方法示例

本文实例讲述了Python2.7读取PDF文件的方法。分享给大家供大家参考,具体如下: 这篇文章示例代码采用的Python版本是2.7,需要下载的插件是PDFMiner,下载地址是htt...

Python编程入门的一些基本知识

Python编程入门的一些基本知识

 Python与Perl,C和Java语言等有许多相似之处。不过,也有语言之间有一些明确的区别。本章的目的是让你迅速学习Python的语法。 第一个Python程序: 交互模式...