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)

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)

Out:
              在这里插入图片描述

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

Ref

  1. pytorch使用torch.nn.Sequential快速搭建神经网络

猜你喜欢

转载自blog.csdn.net/qq_40520596/article/details/106015404