pytorch出现RuntimeError: size mismatch, m1: [2560 x 5], m2: [12800 x 4096] at /pytorch/aten/src/TH/gen

import torch
import torch.nn as nn
import torch.nn.functional as F
class VGG(nn.Module):
    def __init__(self):
        super(VGG,self).__init__()
        self.conv1=nn.Sequential(
            nn.Conv2d(3,64,3),
            nn.Conv2d(64,64,3,padding=1)
        )
        self.max1=nn.MaxPool2d(2,2)

        self.conv2=nn.Sequential(
            nn.Conv2d(64,128,3),
            nn.Conv2d(128,128,3,padding=1)
        )
        self.max2=nn.MaxPool2d(2,2)

        self.conv3=nn.Sequential(
            nn.Conv2d(128,256,3),
            nn.Conv2d(256,256,3,padding=1),
            nn.Conv2d(256,256,3,padding=1)
        )
        self.max3=nn.MaxPool2d(2,2)


        self.conv4=nn.Sequential(
            nn.Conv2d(256,512,3),
            nn.Conv2d(512,512,3,padding=1),
            nn.Conv2d(512,512,3,padding=1)
        )
        self.max4=nn.MaxPool2d(2,2)

        self.conv5=nn.Sequential(
            nn.Conv2d(512,512,3),
            nn.Conv2d(512,512,3,padding=1),
            nn.Conv2d(512,512,3,padding=1)
        )
        self.max5=nn.MaxPool2d(2,2)

        self.fc1=nn.Linear(512*5*5,4096)
        self.fc2=nn.Linear(4096,4096)
        self.fc3=nn.Linear(4096,10)
        self.softmax=nn.Softmax(10)


    def forward(self, x):
        x=self.conv1(x)
        print('conv1:',x.size())
        x=self.max1(x)
        print('conv_max1:', x.size())
        x=self.conv2(x)
        print('conv2:', x.size())
        x = self.max2(x)

        x=self.conv3(x)
        x = self.max3(x)

        x = self.conv4(x)
        x = self.max4(x)

        x = self.conv5(x)
        x = self.max5(x)
        # print('conv_max5:', x.size())
        # print('ccccccc',x.size(0))

        x=x.view(x.size(0),-1)####
        # print(x.size())

        x=self.fc1(x)
        x = self.fc2(x)
        x = self.fc3(x)
        x= F.log_softmax(x, dim=1)
        return x

def test():
    net = VGG()
    print(net)
    x = torch.randn(1, 3, 224, 224)
    y = net(x)
    
    print(y.size())

test()





复现VGG时出现如下错误:

RuntimeError: size mismatch, m1: [2560 x 5], m2: [12800 x 4096] at /pytorch/aten/src/TH/generic/THTe

一开始的代码:

x.view(x.size(0),-1)

出现如上的问题。后来将该代码改成如下形式:

x=x.view(x.size(0),-1)

代码运行成功

你可能感兴趣的:(pytorch)