代碼如下:
%matplotlib inline import torch import torch.nn as nn import torch.nn.functional as F from torchsummary import summary from torchvision import models class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) #此處的16*5*5為conv2經過pooling之后的尺寸,即為fc1的輸入尺寸,在這里寫死了,因此后面的輸入圖片大小不能任意調整 self.fc1 = nn.Linear(16*5*5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): size = x.size()[1:] num_features = 1 for s in size: num_features *= s return num_features net = Net() print(net) params = list(net.parameters()) print (len(params)) print(params[0].size()) print(params[1].size()) print(params[2].size()) print(params[3].size()) print(params[4].size()) print(params[5].size()) print(params[6].size()) print(params[7].size()) print(params[8].size()) print(params[9].size()) input = torch.randn(1, 1, 32, 32) out = net(input) print(out) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') vgg = net.to(device) summary(vgg, (1, 32, 32))
上述代碼完成了以下功能:
1、建立一個簡單的網絡,並給各個網絡層的參數size進行賦值;
2、查看各個網絡層參數量;
3、給網路一個隨機的輸入,查看網絡輸出;
4、查看網絡每一層的額輸出blob的大小;
這里需要注意的是,在進行第一個全連接層的定義時,self.fc1 = nn.Linear(16*5*5, 120)
第一個參數是根據網絡結構計算出來的到達該層的feature map的尺寸,因此后面在給定網絡輸入的時候,不能任意調整網絡的輸入尺寸,該尺寸經過conv1+pooling+conv2+pooling之后的尺寸必須要為5*5才可以;