首页 > 解决方案 > CNN 时如何检查图像大小?

问题描述

我正在尝试使用 PyTorch 对 CNN 中的猫和狗进行分类。虽然我做了一些图层和处理图像,但我发现最终处理的特征图大小与计算的大小不匹配。因此,我尝试在 CNN 过程中使用打印形状逐步检查特征图大小,但它不起作用。我听说 tensorflow 可以逐步检查张量大小,但我该怎么做呢?

我想要的是:

        def __init__(self):
        super(CNN, self).__init__()
        conv1 = nn.Conv2d(1, 16, 3, 1, 1)
        conv1_1 = nn.Conv2d(16, 16, 3, 1, 1)
        pool1 = nn.MaxPool2d(2)
        conv2 = nn.Conv2d(16, 32, 3, 1, 1)
        conv2_1 = nn.Conv2d(32, 32, 3, 1, 1)
        pool2 = nn.MaxPool2d(2)
        conv3 = nn.Conv2d(32, 64, 3, 1, 1)
        conv3_1 = nn.Conv2d(64, 64, 3, 1, 1)
        conv3_2 = nn.Conv2d(64, 64, 3, 1, 1)
        pool3 = nn.MaxPool2d(2)

        self.conv_module = nn.Sequential(
            conv1,
            nn.ReLU(),
            conv1_1,
            nn.ReLU(),
            pool1,
            # check first result size
            conv2,
            nn.ReLU(),
            conv2_1,
            nn.ReLU(),
            pool2,
            # check second result size
            conv3,
            nn.ReLU(),
            conv3_1,
            nn.ReLU(),
            conv3_2,
            nn.ReLU(),
            pool3,
            # check third result size
            pool4,
            # check fourth result size
            pool5
            # check fifth result size
        )

如果有任何其他方法可以在每一步检查特征大小,请提供一些建议。提前致谢。

标签: pythonpytorchconv-neural-network

解决方案


为此,您不应该使用nn.Sequential. 只需初始化您的图层__init__()并在 forward 函数中调用它们。在 forward 函数中,您可以打印出形状。例如像这样:

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        
        self.conv1 = nn.Conv2d(...)
        self.maxpool1 = nn.MaxPool2d()

        self.conv2 = nn.Conv2d(...)
        self.maxpool2 = nn.MaxPool2d()
    
    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.maxpool1(x)
        print(x.size())

        x = self.conv2(x)
        x = F.relu(x)
        x = self.maxpool2(x)
        print(x.size())

希望这就是你要找的!


推荐阅读