Pytorch 实现自定义参数层的例子

yipeiwu_com5年前Python基础

注意,一般官方接口都带有可导功能,如果你实现的层不具有可导功能,就需要自己实现梯度的反向传递。

官方Linear层:

class Linear(Module):
  def __init__(self, in_features, out_features, bias=True):
    super(Linear, self).__init__()
    self.in_features = in_features
    self.out_features = out_features
    self.weight = Parameter(torch.Tensor(out_features, in_features))
    if bias:
      self.bias = Parameter(torch.Tensor(out_features))
    else:
      self.register_parameter('bias', None)
    self.reset_parameters()

  def reset_parameters(self):
    stdv = 1. / math.sqrt(self.weight.size(1))
    self.weight.data.uniform_(-stdv, stdv)
    if self.bias is not None:
      self.bias.data.uniform_(-stdv, stdv)

  def forward(self, input):
    return F.linear(input, self.weight, self.bias)

  def extra_repr(self):
    return 'in_features={}, out_features={}, bias={}'.format(
      self.in_features, self.out_features, self.bias is not None
    )

实现view层

class Reshape(nn.Module):
  def __init__(self, *args):
    super(Reshape, self).__init__()
    self.shape = args

  def forward(self, x):
    return x.view((x.size(0),)+self.shape)

实现LinearWise层

class LinearWise(nn.Module):
  def __init__(self, in_features, bias=True):
    super(LinearWise, self).__init__()
    self.in_features = in_features

    self.weight = nn.Parameter(torch.Tensor(self.in_features))
    if bias:
      self.bias = nn.Parameter(torch.Tensor(self.in_features))
    else:
      self.register_parameter('bias', None)
    self.reset_parameters()

  def reset_parameters(self):
    stdv = 1. / math.sqrt(self.weight.size(0))
    self.weight.data.uniform_(-stdv, stdv)
    if self.bias is not None:
      self.bias.data.uniform_(-stdv, stdv)

  def forward(self, input):
    x = input * self.weight
    if self.bias is not None:
      x = x + self.bias
    return x

以上这篇Pytorch 实现自定义参数层的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详解Python并发编程之从性能角度来初探并发编程

详解Python并发编程之从性能角度来初探并发编程

. 前言 作为进阶系列的一个分支「并发编程」,我觉得这是每个程序员都应该会的。 并发编程 这个系列,我准备了将近一个星期,从知识点梳理,到思考要举哪些例子才能更加让人容易吃透这些知识...

Python中多线程thread与threading的实现方法

学过Python的人应该都知道,Python是支持多线程的,并且是native的线程。本文主要是通过thread和threading这两个模块来实现多线程的。 python的thread...

一篇文章入门Python生态系统(Python新手入门指导)

一篇文章入门Python生态系统(Python新手入门指导)

译者按:原文写于2011年末,虽然文中关于Python 3的一些说法可以说已经不成立了,但是作为一篇面向从其他语言转型到Python的程序员来说,本文对Python的生态系统还是做了较为...

学习Django知识点分享

路由关系映射的一个小问题 URL中那个上尖号在正则中表示 以某某开头 $符号表示以某某结尾 这就限制了开头和结尾,也就固定了长度 但是 admin/123 也不能匹配到admin 为什...

Python实现自动上京东抢手机

本文实例为大家分享了Python自动上京东抢手机的具体代码,供大家参考,具体内容如下 上次抢荣耀V9,被京东给恶心到了,所以就写了个简单的Python来自动抢V9。虽然用的是比较蠢的方法...