如果一个神经网络中,只有卷积层,输入的图像大小是可以任意的。如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层的大小)