浅析PyTorch中nn.Linear的使用

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

相关文章

Windows中安装使用Virtualenv来创建独立Python环境

Windows中安装使用Virtualenv来创建独立Python环境

0、什么时候会用到virtualenv? 假设系统中的两个应用,其中A应用对库LibFoo的版本要求为1,而B应用对同一个库LibFoo的版本要求为2,两个应用对同一个库的要求想冲突了,...

python实现下载指定网址所有图片的方法

本文实例讲述了python实现下载指定网址所有图片的方法。分享给大家供大家参考。具体实现方法如下: #coding=utf-8 #download pictures of the u...

python3 判断列表是一个空列表的方法

python3 判断空列表 @(python3) 有个判断列表是否为空的需求,试了好多方式,比如: a = [] if a is not None: COMMAND a =...

在Python中利用Into包整洁地进行数据迁移的教程

在Python中利用Into包整洁地进行数据迁移的教程

动机 我们花费大量的时间将数据从普通的交换格式(比如CSV),迁移到像数组、数据库或者二进制存储等高效的计算格式。更糟糕的是,许多人没有将数据迁移到高效的格式,因为他们不知道怎么(或者不...

Python实现针对给定单链表删除指定节点的方法

Python实现针对给定单链表删除指定节点的方法

本文实例讲述了Python实现针对给定单链表删除指定节点的方法。分享给大家供大家参考,具体如下: 题目: 初始化定义一个单链表,删除指定节点,输出链表 下面是具体的实现: #!usr...