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设计】。

相关文章

Django自定义分页效果

Django自定义分页效果

分页功能在每个网站都是必要的,对于分页来说,其实就是根据用户的输入计算出应该显示在页面上的数据在数据库表中的起始位置。 确定分页需求: 1. 每页显示的数据条数 2. 每页显示页号链接数...

树莓派动作捕捉抓拍存储图像脚本

本文实例为大家分享了树莓派动作捕捉抓拍存储图像的具体代码,供大家参考,具体内容如下 #!/usr/bin/python # original script by brainflak...

解决pandas read_csv 读取中文列标题文件报错的问题

从windows操作系统本地读取csv文件报错 data = pd.read_csv(path) Traceback (most recent call last): Fi...

python中的函数用法入门教程

本文较为详细的讲述了Python程序设计中函数的用法,对于Python程序设计的学习有不错的借鉴价值。具体分析如下: 一、函数的定义: Python中使用def关键字定义函数,函数包括函...

python调用外部程序的实操步骤

python调用外部程序的实操步骤

在python的使用中,有时也不得不调用一下外部程序,那么如何调用外部程序: 首先,我们要启动python软件,使用的是python2.7的版本,具体如图: 在外部调用中主要要用到一...