How To Fix: RuntimeError: size mismatch in pyTorch

房东的猫 提交于 2020-01-24 16:45:07

问题


I am new to pyTorch and getting following Size Mismatch error:

RuntimeError: size mismatch, m1: [7 x 2092500], m2: [180 x 120] at ..\aten\src\TH/generic/THTensorMath.cpp:961

Model:

class Net(nn.Module):
def __init__(self):
    super(Net, self).__init__()
    self.conv1 = nn.Conv2d(3, 200, 5)
    self.pool = nn.MaxPool2d(2, 2)
    self.conv2 = nn.Conv2d(200, 180, 5)
    self.fc1 = nn.Linear(180, 120)
    self.fc2 = nn.Linear(120, 84)
    self.fc3 = nn.Linear(84,5)     

def forward(self, x):
    x = self.pool(F.relu(self.conv1(x)))
    x = self.pool(F.relu(self.conv2(x)))
    x = x.view(x.shape[0], -1)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return x

How ever I tried changing x = x.view(x.shape[0], -1) to x = x.view(x.size(0), -1) but that also did'nt work. Dimension of images is 512x384. and have used following transformation:

def load_dataset():
data_path = './dataset/training'

transform = transforms.Compose(
               [transforms.Resize((512,384)),
                transforms.ToTensor(),
                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])


train_dataset = torchvision.datasets.ImageFolder(root=data_path,transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=7,num_workers=0,shuffle=True)

return train_loader

回答1:


The problem is that the dimensions of the output of your last max pooling layer don't match the input of the first fully connected layer. This is the network structure until the last max pool layer for input shape (3, 512, 384):

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1        [-1, 200, 508, 380]          15,200
         MaxPool2d-2        [-1, 200, 254, 190]               0
            Conv2d-3        [-1, 180, 250, 186]         900,180
         MaxPool2d-4         [-1, 180, 125, 93]               0
================================================================

The last row of the table means that MaxPool2d-4 outputs 180 channels (filter outputs) of 125 width and 93 height. So you need your first fully connected layer to have 180 * 125 * 93 = 2092500 input size. This is a lot, so I'd advise you to refine your architecture. In any case, if you change the input size of the first fully connected layer to 2092500, it works:

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 200, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(200, 180, 5)
        #self.fc1 = nn.Linear(180, 120)
        self.fc1 = nn.Linear(2092500, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84,5)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(x.shape[0], -1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

Giving the following architecture:

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1        [-1, 200, 508, 380]          15,200
         MaxPool2d-2        [-1, 200, 254, 190]               0
            Conv2d-3        [-1, 180, 250, 186]         900,180
         MaxPool2d-4         [-1, 180, 125, 93]               0
            Linear-5                  [-1, 120]     251,100,120
            Linear-6                   [-1, 84]          10,164
            Linear-7                    [-1, 5]             425
================================================================
Total params: 252,026,089
Trainable params: 252,026,089
Non-trainable params: 0

(You can use the torchsummary package to generate these tables.)



来源:https://stackoverflow.com/questions/57534072/how-to-fix-runtimeerror-size-mismatch-in-pytorch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!