浅析PyTorch中nn.Linear的使用

yipeiwu_com6年前Python基础

查看源码

Linear 的初始化部分:

class Linear(Module):
 ...
 __constants__ = ['bias']
 
 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()
 ...
 

需要实现的内容:

计算步骤:

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

返回的是:input * weight + bias

对于 weight

weight: the learnable weights of the module of shape
  :math:`(\text{out\_features}, \text{in\_features})`. The values are
  initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
  :math:`k = \frac{1}{\text{in\_features}}`

对于 bias

bias:  the learnable bias of the module of shape :math:`(\text{out\_features})`.
    If :attr:`bias` is ``True``, the values are initialized from
    :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
    :math:`k = \frac{1}{\text{in\_features}}`

实例展示

举个例子:

>>> import torch
>>> nn1 = torch.nn.Linear(100, 50)
>>> input1 = torch.randn(140, 100)
>>> output1 = nn1(input1)
>>> output1.size()
torch.Size([140, 50])
 

张量的大小由 140 x 100 变成了 140 x 50

执行的操作是:

[140,100]×[100,50]=[140,50]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 3.6.5 安装配置方法图文教程

python 3.6.5 安装配置方法图文教程

Windowns操作系统中安装Python,供大家参考,具体内容如下 一.下载Python 1.python 官网 下载安装包 2.选择版本 我这里用安装版(64位) 二...

python基础教程之对象和类的实际运用

我们熟悉了对象和类的基本概念。我们将进一步拓展,以便能实际运用对象和类。 调用类的其它信息 上一讲中提到,在定义方法时,必须有self这一参数。这个参数表示某个对象。对象拥有类的所有性质...

使用python opencv对目录下图片进行去重的方法

版本: 平台:ubuntu 14 / I5 / 4G内存 python版本:python2.7 opencv版本:2.13.4 依赖: 如果系统没有python,则需要进行安装 sudo...

python绘制圆柱体的方法

python绘制圆柱体的方法

本文实例为大家分享了python绘制圆柱体示的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python import vtk # 参考的C++版本源码及解释...

python文件操作整理汇总

总是记不住API。昨晚写的时候用到了这些,但是没记住,于是就索性整理一下吧: python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。 得到当前工作目录,...