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

相关文章

通过数据库对Django进行删除字段和删除模型的操作

删除字段 从Model中删除一个字段要比添加容易得多。 删除字段,仅仅只要以下几个步骤:     删除字段,然后重新启动你的web服务器。 &nb...

Python设计模式之解释器模式原理与用法实例分析

Python设计模式之解释器模式原理与用法实例分析

本文实例讲述了Python设计模式之解释器模式原理与用法。分享给大家供大家参考,具体如下: 解释器模式(Interpreter Pattern):给定一个语言,定义它的文法的一种表示,并...

Python实现二叉树结构与进行二叉树遍历的方法详解

Python实现二叉树结构与进行二叉树遍历的方法详解

二叉树的建立 使用类的形式定义二叉树,可读性更好 class BinaryTree: def __init__(self, root): self.key = ro...

Python数据类型详解(三)元祖:tuple

一.基本数据类型   整数:int   字符串:str(注:\t等于一个tab键)   布尔值: bool   列表:list   列表用[]   元祖:tuple   元祖用()...

python实现接口并发测试脚本

常用的网站性能测试指标有:并发数、响应时间、吞吐量、性能计数器等。 1、并发数 并发数是指系统同时能处理的请求数量,这个也是反应了系统的负载能力。 2、响应时间 响应时间是一个系...