RuntimeError: shape '[-1, 44944]' is invalid for input of size 1628160

Hi,
I am trying to run a basic CNN for binary classification of medical images. I am getting this error:

x = x.view(-1, 16 * 53 * 53)

RuntimeError: shape ‘[-1, 44944]’ is invalid for input of size 1628160

CNN:

class Net(nn.Module):
def init(self):
super(Net, self).init()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 53 * 53, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 2)

def forward(self, x):
    x = self.pool(F.relu(self.conv1(x)))
    x = self.pool(F.relu(self.conv2(x)))
    x = x.view(-1, 16 * 53 * 53)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return x

Images - 3x224X224
Batch Size - 32
Though it works with x = x.view(-1, 16 * 53 * 60). But I don’t understand it why it wouldn’t work with 53*53.
I am new to Pytorch and if anyone can help me out I really appreciate it…

Firstly , your init function should be renamed to

    def __init__(self):
        super(Net, self).__init__()

I tested it works perfectly for me with

    x = x.view(-1, 16 * 53 * 53)

I dont know why it is still not working for me. Here is my transforms and dataloader if it helps…

train_dir = ‘train’
valid_dir = ‘valid’
test_dir = ‘test’

dirs = {
‘train’: train_dir,
‘valid’: valid_dir,
‘test’: test_dir
}

Data Transforms:

data_transforms = {
‘train’: transforms.Compose([

    transforms.RandomRotation(40),
    transforms.RandomHorizontalFlip(),
    transforms.RandomVerticalFlip(),
    transforms.ColorJitter(brightness = [1,1.2]),
    transforms.RandomAffine(20,translate =(0.1,0.1),scale=(0.9,1.25)),
    transforms.Resize(224),

    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], 
                                        [0.229, 0.224, 0.225])
]),
'valid': transforms.Compose([

    transforms.Resize(224),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], 
                                        [0.229, 0.224, 0.225])
]),

}

Load the datasets with ImageFolder - No testset at the moment

image_datasets = {x: datasets.ImageFolder(dirs[x], transform=data_transforms[x]) for x in [‘train’, ‘valid’]}

load the data into batches

dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x],drop_last=True, batch_size=32, shuffle=True) for x in [‘train’, ‘valid’]}
dataset_sizes = {x: len(image_datasets[x])
for x in [‘train’, ‘valid’]}

class_names = image_datasets[‘train’].classes

Check the shape of your image after the transformations , maybe the output size is not 224x224 and there is a problem with view( )

1 Like

Thanks, it worked…
I was using transforms.Resize(224) instead of transforms.Resize([224,224])

1 Like