当前位置:   article > 正文

nn.Sequential方法介绍

nn.sequential

 

       torch.nn.Sequential是一个Sequential容器,模块将按照构造函数中传递的顺序添加到模块中。另外,也可以传入一个有序模块。具体理解如下:

 
①普通构建网络:

import torch
import torch.nn as nn

class Net(nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        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 = F.relu(self.hidden(x))      # hidden后接relu层
        x = self.predict(x)
        return x

model_1 = Net(1, 10, 1)
print(model_1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

Out:
              在这里插入图片描述

 
②使用Sequential快速搭建网络:

import torch
import torch.nn as nn

class Net(nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net,self).__init__()
        self.net_1 = nn.Sequential(
            nn.Linear(n_feature, n_hidden),
            nn.ReLU(),
            nn.Linear(n_hidden, n_output)
        )
    
    def forward(self,x):
        x = self.net_1(x)
        return x

model_2 = Net(1,10,1)
print(model_2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

Out:
              在这里插入图片描述

       使用torch.nn.Sequential会自动加入激励函数, 但是 model_1 中, 激励函数实际上是在 forward() 功能中才被调用的。

Ref

  1. pytorch使用torch.nn.Sequential快速搭建神经网络
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/103353
推荐阅读
相关标签
  

闽ICP备14008679号