浅析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程序可...

在python中,使用scatter绘制散点图的实例

如下所示: # coding=utf-8 import matplotlib.pyplot as plt x_values=[1,2,3,4,5] y_values=[1,4,9,...

Python3中关于cookie的创建与保存

1.cookie的作用 cookie 是指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据,就像有些网站上的一些数据是需要登录后才能看得到,那么想抓取某个页面...

Python-copy()与deepcopy()区别详解

最近在实习,boss给布置了一个python的小任务,学习过程中发现copy()和deepcopy()这对好基友实在是有点过分,搞的博主就有点傻傻分不清啊,但是呢本着一探到底的精神,还是...

python实现的多任务版udp聊天器功能案例

python实现的多任务版udp聊天器功能案例

本文实例讲述了python实现的多任务版udp聊天器。分享给大家供大家参考,具体如下: 说明 编写一个有2个线程的程序 线程1用来接收数据然后显示 线程2用来检测键盘数据然后通过udp...