RuntimeError:给定组= 1,权重为[64,3,3,3],预期输入[4,5000,5000,3]具有3个通道,但改为5000个通道

时间:2019-06-27 10:28:08

标签: python image-processing deep-learning computer-vision pytorch

因此,我有一个U-Net模型,并将5000x5000x3的图像输入该模型,然后得到上面的错误。

这是我的模特。

import torch
import torch.nn as nn


def double_conv(in_channels, out_channels):
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, 3, padding=1),
        nn.ReLU(inplace=True),
        nn.Conv2d(out_channels, out_channels, 3, padding=1),
        nn.ReLU(inplace=True)
    )


class UNeT(nn.Module):
    def __init__(self, n_class):
        super().__init__()
        self.dconv_down1 = double_conv(3, 64)
        self.dconv_down2 = double_conv(64, 128)
        self.dconv_down3 = double_conv(128, 256)
        self.dconv_down4 = double_conv(256, 512)
        self.maxpool = nn.MaxPool2d(2)
        self.upsample = nn.Upsample(scale_factor=2, mode='bilinear',
                                    align_corners=True)
        self.dconv_up3 = double_conv(256 + 512, 256)
        self.dconv_up2 = double_conv(128 + 256, 128)
        self.dconv_up1 = double_conv(128 + 64, 64)
        self.conv_last = nn.Conv2d(64, n_class, 1)

    def forward(self, x):
        conv1 = self.dconv_down1(x)
        x = self.maxpool(conv1)
        conv2 = self.dconv_down2(x)
        x = self.maxpool(conv2)
        conv3 = self.dconv_down3(x)
        x = self.maxpool(conv3)
        x = self.dconv_down4(x)
        x = self.upsample(x)
        x = torch.cat([x, conv3], dim=1)
        x = self.dconv_up3(x)
        x = self.upsample(x)
        x = torch.cat([x, conv2], dim=1)
        x = self.dconv_up2(x)
        x = self.upsample(x)
        x = torch.cat([x, conv1], dim=1)
        x = self.dconv_up1(x)
        out = self.conv_last(x)
        return out


我试图做模型(inputs.unsqueeze_(0)),但是出现了另一个错误。

1 个答案:

答案 0 :(得分:0)

pytorch中的尺寸顺序与您期望的不同。您的输入张量具有shape的{​​{1}},您将其解释为大小为4x5000x5000x3的一批,具有4像素的图像,每个像素有3个通道。也就是说,您的尺寸为5000x5000-batch-height-width

但是,pytorch期望张量尺寸的顺序不同:channel-batch-channel-height。也就是说,width维应该在宽度和高度空间维之前。

您需要permute输入张量的尺寸来解决问题:

channel

有关更多信息,请参见nn.Conv2d的文档。