Pytorch 之torch.nn初探 torch.nn.Module与线性--Linear layers

本文介绍了如何在PyTorch中使用torch.nn.Module构建神经网络,包括各种层如线性层、卷积层、非线性层、池化层和损失函数,以及如何创建和操作Sequential模块和自定义模型.
摘要由CSDN通过智能技术生成

初探 torch.nn.Module

神经网络可以使用torch.nn包构建。它提供了几乎所有与神经网络相关的功能,例如:

  • 线性图层 nn.Linear,nn.Bilinear
  • 卷积层 nn.Conv1d,nn.Conv2d,nn.Conv3d,nn.ConvTranspose2d
  • 非线性 nn.Sigmoid,nn.Tanh,nn.ReLU,nn.LeakyReLU
  • 池化层 nn.MaxPool1d,nn.AveragePool2d
  • Recurrent网络 nn.LSTM,nn.GRU
  • 标准化 nn.BatchNorm2d
  • Dropout nn.Dropout,nn.Dropout2d
  • Embedding - nn.Embedding
  • 损失函数 nn.MSELoss,nn.CrossEntropyLoss,nn.NLLLoss

这些类的实例将具有一个内置的__call__函数,可通过图层运行输入。

任务描述

本关任务:

本关要求利用nn.Linear()声明一个线性模型 l,并构建一个变量 net 由三个l序列构成。

相关知识

torch.nn.Module是所有神经网络模块的基类,用户自定义的神经网络模型同样继承自这个类。它定义了训练神经网络需要的所有基础方法,并且是可以序列化的抽象类。

torch.nn.Module模块还可以包含其他模块,允许将它们嵌套在树形结构中。

torch.nn.Module

import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
       x = F.relu(self.conv1(x))
       return F.relu(self.conv2(x))

以这种方式分配的子模块将被注册,并且在调用.cuda()等时也将转换它们的参数。

方法

  • train(mode=True) 将模型设置为训练状态 这只对诸如Dropout或BatchNorm等模块有影响
  • 返回值:self
  • 返回类型 :Module
  • eval() 将模型设置为测试状态 这只对诸如Dropout或BatchNorm等模块有影响
  • float() 将所有的参数转化为float的数据类型
  • forward(*input) 定义每次调用时执行的计算 应该被所有的子类重写
  • zero_grad() 将所有模型参数的梯度设置为0
  • modules() 返回网络中所有模块的迭代器 重复的模块只返回一次。在下面的例子中,l只会被返回一次

应用示例:

l = nn.Linear(2, 2)
net = nn.Sequential(l, l)
print(l)
print(net)
for idx, m in enumerate(net.modules()):
    print(idx, '->', m)

输出结果:

Linear(in_features=2, out_features=2)Sequential( (0): Linear(in_features=2, out_features=2) (1): Linear(in_features=2, out_features=2))0 -> Sequential( (0): Linear(in_features=2, out_features=2) (1): Linear(in_features=2, out_features=2))1 -> Linear(in_features=2, out_features=2)

具体语义说明:

torch.nn.Sequential,一个序列化的模块。模块将按照它们在构造函数中传递的顺序添加到其中。或者,也可以传入模块的有序字典。

编程要求

本关涉及的代码文件为 module.py,本次的编程任务是补全右侧代码片段中Begin至End中间的代码,具体要求如下:

  • 声明一个in_features=2,out_features=3的线性模型 l并输出;
  • 变量 net 由三个l序列构成,并输出net。
  • 具体请参见后续测试样例。

测试说明

测试过程:

  • 本关涉及的测试文件为moduleTest.py,运行用户填写后的程序判断正误。
  • 测试程序将检测两个方面:是否包含特定的代码行以及程序的输出是否正确,若两个方面均正确则输出下面的预期输出,否则报错。
  • 请注意输出格式及规范。
  • 注意,在声明变量时请按照提示命名,否则将会报错。

以下是测试样例:

测试输入: 预期输出:

Linear(in_features=2, out_features=3, bias=True)
Sequential(
  (0): Linear(in_features=2, out_features=3, bias=True)
  (1): Linear(in_features=2, out_features=3, bias=True)
  (2): Linear(in_features=2, out_features=3, bias=True)
)

Congratulation!

代码实战

import torch
import torch.nn as nn
from torch.autograd import Variable


#/********** Begin *********/
#声明一个in_features=2,out_features=3的线性模型 l并输出
l = nn.Linear(2, 3)
print(l)

#变量 net 由三个l 序列构成,并输出 net
net = nn.Sequential(l, l,l)
print(net)

#/********** End *********/

线性--Linear layers 

任务描述

本关介绍了利用module.weight,module.bias查询模块的权重和偏移量。

本关任务:

本关要求同学们创建一个线性层变量linear并输出linear的 type 属性。

相关知识

现在我们autograd有了初步的了解,而nn建立在autograd的基础上来进行模型的定义和微分。

我们自定义的网络结构是由若干的layer组成的,我们将其设置为 nn.Module的子类,nn.Module中包含着神经网络的层,只要使用方法forward(input)就能够将output返回。

Linear是module的子类,是参数化module的一种,与其名称一样,表示着一种线性变换。

首先,先导入我们本次实训使用的包。

import torch
import torch.nn as nn
from torch.autograd import Variable

torch.nn.Linear

基本形式:

torch.nn.Linear (in_features, out_features, bias=True)

用途:对输入数据应用一个线性转换,格式如下所示:

y=Ax+b

参数说明:

  • in_features – 输入样本的大小
  • out_features – 输出样本的大小
  • bias – 偏移量
  • False:该层将不会学习额外的偏移量
  • 默认值为True

维度大小:

  • Input: (N,∗,in_features) *表示任意大小的附加维度
  • Output: (N,∗,out_features) 最后一个维度要与输入相同

学习到的变量:

  • weight– 可学习权重(out_features x in_features)
  • bias – 可学习偏移量(out_features)

应用示例:

module = nn.Linear(4, 2)
print(module)

输出结果:

Linear(in_features=4, out_features=2)

属性

利用module.weight,module.bias查询模块的权重和偏移量。

print("module.weight: 
%s"% module.weight)#W
print("module.bias: 
%s"% module.bias)#b

输出结果:

module.weight: Parameter containing:0.2790 0.1672 -0.3788 0.2498-0.1267 -0.0837 -0.1896 0.1558[torch.FloatTensor of size 2x4]

module.bias: Parameter containing:-0.2481-0.0124[torch.FloatTensor of size 2]

应用

有了权重、偏移量后,随机生成输入样本后,我们就可以利用 公式 y=wx+b进行线性转换啦。

#生成输入样本
input = Variable(torch.randn(8, 4))

# output = input * module
output = module(input)
print(output.size())

这里有两个二维张量:

  • input-大小为8*4
  • w- 大小为2*4

实际在计算中,是input 和 w 的转置做矩阵乘法,得到输出张量 output,大小为8*2。输出结果如下:

torch.Size([8, 2])

编程要求

本关涉及的代码文件为linear.py,本次编程任务是补全右侧代码片段中Begin至End中间的代码,具体要求如下:

  • 创建in_features=3, out_features=2线性层变量 linear并输出;
  • 输出linear的 type 属性。

测试说明

测试过程:

  • 本关涉及的测试文件为linear.py,运行用户填写后的程序判断正误。
  • 测试程序将检测两个方面:是否包含特定的代码行以及程序的输出是否正确,若两个方面均正确则输出下面的预期输出,否则报错。
  • 请注意输出格式及规范,如在打印 linear 时前面要显示linear: 字符。
  • 注意,在声明变量时请按照提示命名,否则将会报错。

以下是测试样例:

测试输入: 预期输出:

linear: Linear(in_features=3, out_features=2)type of linear : <bound method Module.type of Linear(in_features=3, out_features=2)>

Congratulation!

代码实战

import torch
import torch.nn as nn
from torch.autograd import Variable

#/********** Begin *********/
# 创建in_features=3, out_features=2线性层变量 linear
linear=nn.Linear(3,2)
#输出linear
print('linear: ',linear)
#输出linear的 type 属性
print('type of linear : ',linear.type)
#/********** End *********/
  • 28
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十有久诚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值