【深度学习笔记】torch.nn.Sequential(* args) 与 torch.nn.Module

前言

  • 二者主要是用于搭建神经网络。
  • 使用类(继承torch.nn.Moudule)可以实现灵活搭建。
  • 使用 torch.nn.Sequential 可以实现快速搭建。

一、class torch.nn.Sequential(* args)

  • 一个时序容器。Modules 会以他们传入的顺序被添加到容器中。
  • 因此,都贱神经网络模型的时候必须确保前一个模块的输出大小和下一个模块的输入大小是一致的。
  • 当然,也可以传入一个OrderedDict。
  • 为了更容易的理解如何使用Sequential, 下面给出了一个例子:
# Example of using Sequential
model = nn.Sequential(
          nn.Conv2d(1,20,5),
          nn.ReLU(),
          nn.Conv2d(20,64,5),
          nn.ReLU()
        )
# Example of using Sequential with OrderedDict
model = nn.Sequential(OrderedDict([
          ('conv1', nn.Conv2d(1,20,5)),
          ('relu1', nn.ReLU()),
          ('conv2', nn.Conv2d(20,64,5)),
          ('relu2', nn.ReLU())
        ]))

二、class torch.nn.Module

  • 所有网络的基类。

  • 我们的模型也应该继承这个类。

  • Modules也可以包含其它Modules,允许使用树结构嵌入他们。我们可以将子模块赋值给模型属性。

  • init中定义每个神经层的神经元个数,和神经元层数;

  • forward是继承nn.Moudule中函数,来实现前向反馈(加上激活函数) 。

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) # submodule: Conv2d
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
       x = F.relu(self.conv1(x))
       return F.relu(self.conv2(x))
  • 通过上面方式赋值的submodule会被注册。当调用 .cuda() 的时候,submodule的参数也会转换为cuda Tensor。
  • 抽象出的模板如下(使用的是子类化的方式定义神经网络模型):

class 神经网络模型名字(nn.Module):

    # 定义初始化函数,在类实例化时会自动调用,其中self 代表的是类的实例
    # 类似于c++中的默认构造函数
    def __init__(self, 参数列表):
        super(神经网络模型名字, self).__init__()
        self.layer1 = nn.Linear(num_input, num_hidden)
        self.layer2 = nn.Sequential(...)
        ...
        以上主要是定义需要用的网络层

    # 定义前向传播函数
    def forward(self, x):
        x1 = self.layer1(x)
        x2 = self.layer2(x)
        x = x1 + x2
        ...
        return x

三、二者的区别

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

class Net(nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        # 继承__init__函数
        super(Net, self).__init__()
        # 定义网络的各层
        self.hidden = nn.Linear(n_feature, n_hidden)
        self.predict = nn.Linear(n_hidden, n_output)
 
    # 实现所有层的连接关系。
    def forward(self, x):
        # 输入x首先在隐藏层经过激励函数的计算
        x = F.relu(self.hidden(x))
        # 输出层输出预测值
        x = self.predict(x)
        return x

net1 = Net(1, 10, 1)
print(net1)
print(type(net1))

# 快速搭建神经网络:Sequential方式
# 模板:网络名称 = torch.nn.Sequential()
net2 = nn.Sequential(
    nn.Linear(1, 10),
    nn.ReLU(),
    nn.Linear(10, 1)
)
print(net2)
print(type(net2))
  • 输出结果
Net(
  (hidden): Linear(in_features=1, out_features=10, bias=True)
  (predict): Linear(in_features=10, out_features=1, bias=True)
)
<class '__main__.Net'>

Sequential(
  (0): Linear(in_features=1, out_features=10, bias=True)
  (1): ReLU()
  (2): Linear(in_features=10, out_features=1, bias=True)
)
<class 'torch.nn.modules.container.Sequential'>
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值