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

相关文章

python3+PyQt5实现使用剪贴板做复制与粘帖示例

python3+PyQt5实现使用剪贴板做复制与粘帖示例

本文是对《Python Qt GUI快速编程》的第10章的例子剪贴板用Python3+PyQt5进行改写,分别对文本,图片和html文本的复制与粘帖,三种做法大同小异。 #!/usr...

python 定义n个变量方法 (变量声明自动化)

code: for i in range(100): cmd = "t%s = 1" % i exec cmd eval("t%s" % i) print t10 输出...

Python OpenCV利用笔记本摄像头实现人脸检测

Python OpenCV利用笔记本摄像头实现人脸检测

本文实例为大家分享了Python OpenCV利用笔记本摄像头实现人脸检测的具体代码,供大家参考,具体内容如下 1.安装opencv 首先参考其他文章安装pip。 之后以管理员身份运行命...

Python 使用多属性来进行排序

Python 中 list.sort() 是列表中非常常用的排序函数, key 参数可以对单个属性进行排序。 但是想要实现类似 sql 中 order by id, age 一样,对多个...

Python做智能家居温湿度报警系统

Python做智能家居温湿度报警系统

物联网技术开创了一个智慧城市的新时代,从智能摄像头到部署各种传感器,以此对城市各种数据进行收集,并经云端AI技术处理后,有助于提高对交通和街道等城市公共管理能力;物联网的发展也为智能家居...