浅析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中对变量判断是否为None的三种方法总结

三种主要的写法有: 第一种:if X is None; 第二种:if not X; 当X为None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组(...

python xlsxwriter库生成图表的应用示例

python xlsxwriter库生成图表的应用示例

xlsxwriter可能用过的人并不是很多,不过使用后就会感觉,他的功能让你叹服,除了可以按要求生成你所需要的excel外 还可以加上很形象的各种图,比如柱状图、饼图、折线图等。 xls...

Python配置mysql的教程(推荐)

Linux系统自带Python,且根据系统自带资源来对python配置mysql;安装需要已配置好正确的yum源; 在python未配置mysql的情形下,直接import MySQLd...

Python使用Pycrypto库进行RSA加密的方法详解

密码与通信 密码技术是一门历史悠久的技术。信息传播离不开加密与解密。密码技术的用途主要源于两个方面,加密/解密和签名/验签 在信息传播中,通常有发送者,接受者和窃听者三个角色。假设发送者...

python使用pandas实现数据分割实例代码

本文研究的主要是Python编程通过pandas将数据分割成时间跨度相等的数据块的相关内容,具体如下。 先上数据,有如下dataframe格式的数据,列名分别为date、ip,我需要统计...