在前兩次的學習中搭建一個網絡分爲了兩部分。首先定義該網絡中存在的各層,並設定好每層的參數,然後構建前向傳播關係,這樣才能形成一個有效的網絡架構。例如下面這一簡單的網絡結構。
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.out = 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.out(x)
return x
在這裏將使用一種簡單的搭建方法,可以將上述兩部和起來,那就是使用Sequential,直接按照結構順序排列每一層,並設定每層的參數,這樣就會按照網絡層的順序構建一個網絡。可以打印出來看一下。
net = torch.nn.Sequential(
torch.nn.Linear(1, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 1)
)
print(net)
打印結果如下:
Sequential(
(0): Linear(in_features=1, out_features=10, bias=True)
(1): ReLU()
(2): Linear(in_features=10, out_features=1, bias=True)
)
原來方式構建網絡的網絡結構如下,這裏每一層我們都爲其命名了,所以每一層都有一個名字,而簡單構建法則顯示出了第幾層。
Net(
(hidden): Linear(in_features=1, out_features=10, bias=True)
(predict): Linear(in_features=10, out_features=1, bias=True)
)