1. 程式人生 > >NetScope:基於 prototxt 視覺化模型結構

NetScope:基於 prototxt 視覺化模型結構

如果一個神經網路中,只有卷積層,輸入的影象大小是可以任意的。如FCN,全卷積網路。

如果一個神經網路中,既有卷積層,也有全連線層,那麼輸入的影象的大小必須是固定的。目前大部分常見的神經網路模型都帶有全連線層,如LeNet、AlexNet、ResNet、google-net等等。

最近剛接觸pytorch,VGG模型的原始碼如下所示:

class VGG(nn.Module):

    def __init__(self, features, num_classes=1000, init_weights=True):
        super(VGG, self).__init__()
        self.features = features
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, num_classes),
        )

        if init_weights:
            self._initialize_weights()

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), -1)
        x = self.classifier(x)
        return x

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
                if m.bias is not None:
                    m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                m.weight.data.normal_(0, 0.01)
                m.bias.data.zero_()

其中,nn.Linear(512 * 7 * 7, 4096),表示VGG的第一個全連線層。nn.Linear(infeature, outfeature),如下圖所示:


512 * 7 * 7 就是VGG網路最後一個卷積層的輸出size,那麼如何檢視VGG模型各層的size呢?

step 1:在google上輸入“vgg prototxt”,得到vgg的模型結構程式碼;

step 2:開啟Netscope網址,並複製模型結構程式碼;

step 3:按“shift + enter”視覺化模型結構,如下圖所示,可以看到VGG的第一層全連線之前的pool5的size為[1, 512,7, 7],表示512張大小為7x7的影象。


(當然,也可以直接檢視prototxt檔案得知pool5層的大小)