【问题标题】:PyTorch RuntimeError Invalid argument 2 of sizePyTorch RuntimeError 大小的参数 2 无效
【发布时间】:2019-03-16 15:08:24
【问题描述】:

我正在尝试使用神经网络 (PyTorch),但出现此错误。

RuntimeError: invalid argument 2: size '[32 x 9216]' 对于 /pytorch/aten/src/TH/THStorage.cpp:84 中的 8192 个元素的输入无效

我的任务是使用 AlexNet 进行图像分类,我将误差回溯到提供给神经网络的图像大小。我的问题是,鉴于网络架构及其参数,如何确定网络所需的正确图像大小?

根据我下面的代码,我首先转换训练图像,然后再输入神经网络。但我注意到神经网络只能接受224 的大小,否则会出现上述错误。例如,我的直觉是应用大小为 64 的transforms.RandomResizedCrop,但显然这是错误的。是否有确定所需尺寸的公式?

代码

# transformation to be done on images
transform_train = transforms.Compose([
    transforms.RandomResizedCrop(64),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

class AlexNet(nn.Module):

    def __init__(self, num_classes=1000):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        self.classifier = nn.Sequential(
            nn.Dropout(),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes),
        )

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), 256 * 6 * 6)
        x = self.classifier(x)
        return x

【问题讨论】:

    标签: python neural-network deep-learning conv-neural-network pytorch


    【解决方案1】:

    我已经找到了获得正确输入大小的算法。

    Out = float(((W−F+2P)/S)+1)
    

    在哪里

    • Out = 输出形状
    • W = 图像体积大小(图像大小)
    • F = 感受野(过滤器大小)
    • P = 填充
    • S = 步幅

    考虑给定的网络超参数,

    我需要的图片尺寸是

    W = (55 - 1) * 4 - 2(2) + 11
      =  223
      ⩰  224
    

    【讨论】:

      【解决方案2】:

      实际计算卷积层后输出形状的公式为:

      out_size= floor((in_size + 2p -f)/s + 1)

      【讨论】:

        猜你喜欢
        • 2022-01-15
        • 1970-01-01
        • 2020-02-07
        • 1970-01-01
        • 2019-06-20
        • 2020-06-11
        • 2015-11-25
        • 2019-07-31
        • 1970-01-01
        相关资源
        最近更新 更多