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

相关文章

python实现维吉尼亚算法

python实现维吉尼亚算法

本文实例为大家分享了python实现维吉尼亚算法的具体代码,供大家参考,具体内容如下 1 Virginia加密算法、解密算法 Vigenenre密码是最著名的多表代换密码,是法国著名密码...

bpython 功能强大的Python shell

bpython 功能强大的Python shell

Python是一个非常实用、流行的解释型编程语言,其优势之一就是可以借助其交互的shell进行探索式地编程。你可以试着输入一些代码,然后马上获得解释器的反馈,而不必专门写一个脚本。但是P...

python中子类调用父类函数的方法示例

前言 本文主要给大家介绍了关于python子类调用父类函数的相关内容,Python中子类中的__init__()函数会覆盖父类的函数,一些情况往往需要在子类里调用父类函数。下面话不多说了...

Python实现读写sqlite3数据库并将统计数据写入Excel的方法示例

本文实例讲述了Python实现读写sqlite3数据库并将统计数据写入Excel的方法。分享给大家供大家参考,具体如下: src = 'F:\\log\\mha-041log\\...

使用Python实现正态分布、正态分布采样

使用Python实现正态分布、正态分布采样

多元正态分布(多元高斯分布) 直接从多元正态分布讲起。多元正态分布公式如下: 这就是多元正态分布的定义,均值好理解,就是高斯分布的概率分布值最大的位置,进行采样时也就是采样的中心点。而...