在搭建神经网络的过程中,我们也经常使用 Sequential() 函数帮助我们快速搭建神经网络,通常使用两种不同方式搭建的神经网络没有区别。
1. 准备包
import torch
import torch.nn.functional as F
2.常见搭建神经网络的方法
# replace following class code with an easy sequential network
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
self.predict = torch.nn.Linear(n_hidden, n_output) # output layer
def forward(self, x):
x = F.relu(self.hidden(x)) # activation function for hidden layer
x = self.predict(x) # linear output
return x
net1 = Net(1, 10, 1)
注:net = Net ('param') ,神经网络的参数可以在神经网络搭建好后直接传入
2. 快速搭建神经网络的方法
# easy and fast way to build your network
net2 = torch.nn.Sequential(
torch.nn.Linear(1, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 1)
)
在快速搭建神经网路的过程中,激活函数直接作为一层传入,不需要参数
3. 显示结果
print(net1) # net1 architecture
"""
Net (
(hidden): Linear (1 -> 10)
(predict): Linear (10 -> 1)
)
"""
print(net2) # net2 architecture
"""
Sequential (
(0): Linear (1 -> 10)
(1): ReLU ()
(2): Linear (10 -> 1)
)
"""
网友评论