博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【深度学习笔记】torch.nn.Sequential(* args) 与 torch.nn.Module
阅读量:2135 次
发布时间:2019-04-30

本文共 2632 字,大约阅读时间需要 8 分钟。

前言

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

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

  • 一个时序容器。Modules 会以他们传入的顺序被添加到容器中。
  • 因此,都贱神经网络模型的时候必须确保前一个模块的输出大小和下一个模块的输入大小是一致的。
  • 当然,也可以传入一个OrderedDict。
  • 为了更容易的理解如何使用Sequential, 下面给出了一个例子:
# Example of using Sequentialmodel = nn.Sequential(          nn.Conv2d(1,20,5),          nn.ReLU(),          nn.Conv2d(20,64,5),          nn.ReLU()        )
# Example of using Sequential with OrderedDictmodel = 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 nnimport torch.nn.functional as Fclass 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 nnimport torch.nn.functional as Fclass 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 xnet1 = 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))
Sequential( (0): Linear(in_features=1, out_features=10, bias=True) (1): ReLU() (2): Linear(in_features=10, out_features=1, bias=True))

转载地址:http://ubugf.baihongyu.com/

你可能感兴趣的文章
【LEETCODE】206-Reverse Linked List
查看>>
【LEETCODE】203-Remove Linked List Elements
查看>>
【LEETCODE】234-Palindrome Linked List
查看>>
【LEETCODE】141-Linked List Cycle
查看>>
【LEETCODE】142-Linked List Cycle II
查看>>
【LEETCODE】92-Reverse Linked List II
查看>>
【LEETCODE】283-Move Zeroes
查看>>
【LEETCODE】217-Contains Duplicate
查看>>
【LEETCODE】219-Contains Duplicate II
查看>>
【LEETCODE】220-Contains Duplicate III
查看>>
【LEETCODE】171-Excel Sheet Column Number
查看>>
【LEETCODE】169-Majority Element
查看>>
【LEETCODE】191-Number of 1 Bits
查看>>
【LEETCODE】13-Roman to Integer
查看>>
【LEETCODE】83-Remove Duplicates from Sorted List
查看>>
【LEETCODE】70-Climbing Stairs
查看>>
【LEETCODE】198-House Robber
查看>>
【LEETCODE】62-Unique Paths
查看>>
【LEETCODE】310-Minimum Height Trees
查看>>
【LEETCODE】207-Course Schedule
查看>>