赞
踩
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() 功能中才被调用的。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。