nn.Sequential方法介绍
torch.nn.Sequential是一个Sequential容器,模块将按照构造函数中传递的顺序添加到模块中。另外,也可以传入一个有序模块。具体理解如下: ①普通构建网络:import torchimport torch.nn as nnclass Net(nn.Module):def _
   ·  
 
       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
更多推荐
 
 




所有评论(0)