使用Sequential快速搭建神经网络
torch.nn.Sequential是一个Sequential容器,模块将按照构造函数中传递的顺序添加到模块中.另外也可以传递一个有序模块.
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.Relu(),
nn.Conv2d(20,64,5),
nn.Relu()
)
model = nn.Sequential(OrderedDict([
('conv1',nn.Conv2d(1,20,5)),
('relu1',nn.Relu()),
('conv2',nn.Conv2d(20,64,5)),
('relu2',nn.Relu())
]))
使用普通方法搭建一个神经网络
class Net(nn.Module):
def __init__(self,n_feature,n_hidden,n_output):
super(Net,self).__init()
self.hidden = torch.nn.Linear(n_feature,n_hidden)
self.predict = torch.nn.Linear(n_hidden,n_output)
def forward(self,x):
x = F.relu(self.hidden(x))
x = self.predict(x)
return x
使用torch.nn.Sequential会自动加入激励函数, 但是 使用普通方法搭建的网络, 激励函数实际上是在 forward() 功能中才被调用的.
torch.nn.Sequential与torch.nn.Module区别与选择
使用torch.nn.Module,我们可以根据自己的需求改变传播过程,如RNN等
如果你需要快速构建或者不需要过多的过程,直接使用torch.nn.Sequential即可
网友评论