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 networkx 包绘制复杂网络关系图的实现

1. 创建一个图 import networkx as nx g = nx.Graph() g.clear() #将图上元素清空 所有的构建复杂网络图的操作基本都围绕这个g来执行...

python使用urllib模块开发的多线程豆瓣小站mp3下载器

复制代码 代码如下:#! /usr/bin/python2.7# -- coding:utf-8 -- import os, urllib,urllib2, thread,threadi...

Django Aggregation聚合使用方法解析

在当今根据需求而不断调整而成的应用程序中,通常不仅需要能依常规的字段,如字母顺序或创建日期,来对项目进行排序,还需要按其他某种动态数据对项目进行排序。Djngo聚合就能满足这些要求。 以...

Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据示例

Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据示例

本文实例讲述了Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据。分享给大家供大家参考,具体如下: 一、Logistic回归模型:   二、Logisti...

Django3.0 异步通信初体验(小结)

Django3.0 异步通信初体验(小结)

此前博主曾经写过一篇博文,介绍了Django3.0的新特性,其中最主要的就是加入对ASGI的支持,实现全双工的异步通信。 2019年12月2日,Django终于正式发布了3.0版本。怀着...