浅析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的turtle模块画图的方法

使用Python的turtle模块画图的方法

简介:turtle是一个简单的绘图工具。它提供了一个海龟,你可以把它理解为一个机器人,只听得懂有限的指令。 1.在文件头写上如下行,这能让我们在语句中插入中文 #-*-coding:ut...

python list语法学习(带例子)

创建:list = [5,7,9]取值和改值:list[1] = list[1] * 5列表尾插入:list.append(4)去掉第0个值并返回第0个值的数值:list.pop(0)去...

Python随机读取文件实现实例

Python随机读取文件 代码如下 import os import random rootdir = "d:\\face\\train" file_names = [] for...

Pandas之MultiIndex对象的示例详解

约定 import pandas as pd from pandas import DataFrame import numpy as np MultiIndex MultiI...

Python随机生成带特殊字符的密码

在日常运维中,如果涉及到用户管理,就一定会用到给用户设置密码的工作,其实吧,平时脑子里觉得设置个密码没什么,但要真让你随手敲一个12位带特殊字符的随机密码,也是很痛苦的事,如果让你敲10...