浅析PyTorch中nn.Linear的使用

yipeiwu_com6年前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的Bottle框架中获取制定cookie的教程

这两天为用bottle+mongodb写的一个项目加上登录功能,无奈怎么都获取不到保存的cookie,文档给出让我们这样操作cookie的代码片段: @route('/login')...

python使用TensorFlow进行图像处理的方法

一、图片的放大缩小 在使用TensorFlow进行图片的放大缩小时,有三种方式: 1、tf.image.resize_nearest_neighbor():临界点插值 2、tf.i...

Python决策树分类算法学习

Python决策树分类算法学习

从这一章开始进入正式的算法学习。 首先我们学习经典而有效的分类算法:决策树分类算法。 1、决策树算法 决策树用树形结构对样本的属性进行分类,是最直观的分类算法,而且也可以用于回归。不...

python 设置输出图像的像素大小方法

如下所示: plt.rcParams['savefig.dpi'] = 300 #图片像素 plt.rcParams['figure.dpi'] = 300 #分辨率 为了记住不...