浅析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之方法的覆盖与super函数详解

对Python3之方法的覆盖与super函数详解

#覆盖 覆盖:在继承关系中,子类实现了与基类同名的方法,在子类的实例调用该方法时,实例调用的是子类的覆盖版本。 通俗的讲,就是小明继承了他⑧的自行车,经过自己的改装,成了电动车,那么小明...

Python编程中time模块的一些关键用法解析

Python编程中time模块的一些关键用法解析

python中time模块其实不难,就是关系转换有点老记不住,先看下图可以说明几个时间对象的的关系.供参考理解. 黑色细箭头表示输入值,参数 深黄色的粗箭头表示返回值,输出...

Python Tkinter简单布局实例教程

Python Tkinter简单布局实例教程

本文实例展示了Python Tkinter实现简单布局的方法,示例中备有较为详尽的注释,便于读者理解。分享给大家供大家参考之用。具体如下: # -*- coding: utf-8 -...

python 检查文件mime类型的方法

magic 模块可以检查文件的mime类型,而不是从后缀名来判断,例如判断文件是不是视频或图片类型如下: #检查文件类型 mime_type = magic.from_file(fu...

Python面向对象程序设计示例小结

本文实例讲述了Python面向对象程序设计。分享给大家供大家参考,具体如下: 示例1: #encoding:utf-8 '''example 1 class test: def...