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

相关文章

pandas把所有大于0的数设置为1的方法

如下所示: df = pd.read_csv(‘hahaha.csv') df[df>0] = 1 print(df) 以上这篇pandas把所有大于0的数设置为1的方法...

Python实现批量修改文件名实例

本文实例讲述了Python实现批量修改文件名的方法。分享给大家供大家参考。具体如下: 下载了评书《贺龙传奇》,文件名中却都含有xxx有声下载,用脚本将其去掉。脚本涉及os.rename重...

Python Opencv任意形状目标检测并绘制框图

Python Opencv任意形状目标检测并绘制框图

opencv 进行任意形状目标识别,供大家参考,具体内容如下 工作中有一次需要在简单的图上进行目标识别,目标的形状不固定,并且存在一定程度上的噪声影响,但是噪声影响不确定。这是一个简单...

python连接池实现示例程序

复制代码 代码如下:import socketimport Queueimport threading def worker():    while Tru...

Python列表的切片实例讲解

Python列表的切片实例讲解

之前讲过python列表的基本操作,我们今天继续讲解列表中的切片等操作,列表的切片就是根据索引取列表中的数据,切片并不会改变原列表。接下来跟着小编一起学习python列表的其他操作吧。...