浅析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中的len()函数的使用

函数:len() 1:作用:返回字符串、列表、字典、元组等长度 2:语法:len(str) 3:参数: str:要计算的字符串、列表、字典、元组等 4:返回值:字符串、列表、字典、元组等...

Python简单实现查找一个字符串中最长不重复子串的方法

本文实例讲述了Python简单实现查找一个字符串中最长不重复子串的方法。分享给大家供大家参考,具体如下: 刚结束的一个笔试题,很简单,不多说简单贴一下具体的实现: #!usr/bin...

Python中的CSV文件使用"with"语句的方式详解

是否可以直接使用with语句与CSV文件?能够做这样的事情似乎很自然: import csv with csv.reader(open("myfile.csv")) as reade...

python 读取txt,json和hdf5文件的实例

一.python读取txt文件 最简单的open函数: # -*- coding: utf-8 -*- with open("test.txt","r",encoding="gbk"...

Python中条件判断语句的简单使用方法

最简单的条件语句: if expression: expr_true_suite 如上,if是关键字,expression是条件表达式,条件表达式支持多重条件判断,可以用...