浅析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模拟三级菜单效果的具体代码,供大家参考,具体内容如下 1.功能简介 此程序模拟多级菜单操作,实现按菜单项对应数字索引进入下级菜单,按b键回退到上一级菜单,...

Python中 传递值 和 传递引用 的区别解析

Python中 传递值 和 传递引用 的区别解析

对于不可变类型传递值(不会影响原数据)   不可变类型 对于可变类型传递引用(会影响原数据)   不可变类型传递引用 python3不可变类型 Number(数...

使用python画社交网络图实例代码

使用python画社交网络图实例代码

在图书馆的检索系统中,关于图书的信息里面有一个是图书相关借阅关系图。跟这个社交网络图是一样的,反映了不同对象间的关联性。 利用python画社交网络图使用的库是 networkx,更多关...

python 发送json数据操作实例分析

python 发送json数据操作实例分析

本文实例讲述了python 发送json数据操作。分享给大家供大家参考,具体如下: # !/usr/bin/env python # -*- coding: utf-8 -*-...

python实现根据文件格式分类

python实现根据文件格式分类

本文实例为大家分享了python根据文件格式分类的具体代码,供大家参考,具体内容如下 使用到python内置os模块(对目录或文件的新建/删除/属性查看,还提供了对文件以及目录的路径操作...