torch.nn 是專門為神經網絡設計的模塊化接口,nn構建於autgrad之上,可以用來定義和運行神經網絡
nn.Module 是nn中重要的類,包含網絡各層的定義,以及forward方法
對於自己定義的網絡,需要注意以下幾點:
1)需要繼承nn.Module類,並實現forward方法,只要在nn.Module的子類中定義forward方法,backward函數就會被自動實現(利用autograd機制)
2)一般把網絡中可學習參數的層放在構造函數中__init__(),沒有可學習參數的層如Relu層可以放在構造函數中,也可以不放在構造函數中(在forward函數中使用nn.Functional)
3)在forward中可以使用任何Variable支持的函數,在整個pytorch構建的圖中,是Variable在流動,也可以使用for,print,log等
4)基於nn.Module構建的模型中,只支持mini-batch的Variable的輸入方式,如,N*C*H*W
代碼示例:
class LeNet(nn.Module): def __init__(self): # nn.Module的子類函數必須在構造函數中執行父類的構造函數 super(LeNet, self).__init__() # 等價與nn.Module.__init__() # nn.Conv2d返回的是一個Conv2d class的一個對象,該類中包含forward函數的實現 # 當調用self.conv1(input)的時候,就會調用該類的forward函數 self.conv1 = nn.Conv2d(1, 6, (5, 5)) # output (N, C_{out}, H_{out}, W_{out})` self.conv2 = nn.Conv2d(6, 16, (5, 5)) self.fc1 = nn.Linear(256, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # F.max_pool2d的返回值是一個Variable, input:(10,1,28,28) ouput:(10, 6, 12, 12) x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # input:(10, 6, 12, 12) output:(10,6,4,4) x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2)) # 固定樣本個數,將其他維度的數據平鋪,無論你是幾通道,最終都會變成參數, output:(10, 256) x = x.view(x.size()[0], -1) # 全連接 x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) # 返回值也是一個Variable對象 return x def output_name_and_params(net): for name, parameters in net.named_parameters(): print('name: {}, param: {}'.format(name, parameters)) if __name__ == '__main__': net = LeNet() print('net: {}'.format(net)) params = net.parameters() # generator object print('params: {}'.format(params)) output_name_and_params(net) input_image = torch.FloatTensor(10, 1, 28, 28) # 和tensorflow不一樣,pytorch中模型的輸入是一個Variable,而且是Variable在圖中流動,不是Tensor。 # 這可以從forward中每一步的執行結果可以看出 input_image = Variable(input_image) output = net(input_image) print('output: {}'.format(output)) print('output.size: {}'.format(output.size()))