Ashish Rao
Ashish Rao

Reputation: 91

RuntimeError: Expected 4-dimensional input for 4-dimensional weight [64, 3, 7, 7], but got 3-dimensional input of size [3, 32, 32] instead

I am new to PyTorch and neural networks in general. I was trying to implement the resnet-50 model from torchvision on the CIFAR-10 dataset.

import torchvision
import torch
import torch.nn as nn
from torch import optim
import os
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import numpy as np
from collections import OrderedDict
import matplotlib.pyplot as plt

transformations=transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])
trainset=torchvision.datasets.CIFAR10(root='./CIFAR10',download=True,transform=transformations,train=True)

testset=torchvision.datasets.CIFAR10(root='./CIFAR10',download=True,transform=transformations,train=False)

trainloader=DataLoader(dataset=trainset,batch_size=4)
testloader=DataLoader(dataset=testset,batch_size=4)

inputs,labels=next(iter(trainset))
inputs.size()
resnet=torchvision.models.resnet50(pretrained=True)

if torch.cuda.is_available():
  resnet=resnet.cuda()
  inputs,labels=inputs.cuda(),torch.Tensor(labels).cuda()

outputs=resnet(inputs)

OUTPUT

--------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-6-904acb410fe4> in <module>()
      6   inputs,labels=inputs.cuda(),torch.Tensor(labels).cuda()
      7 
----> 8 outputs=resnet(inputs)

5 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in _conv_forward(self, input, weight)
    344                             _pair(0), self.dilation, self.groups)
    345         return F.conv2d(input, weight, self.bias, self.stride,
--> 346                         self.padding, self.dilation, self.groups)
    347 
    348     def forward(self, input):

RuntimeError: Expected 4-dimensional input for 4-dimensional weight [64, 3, 7, 7], but got 3-dimensional input of size [3, 32, 32] instead

Is there a problen with the dataset for some reason and if not, how do i give a 4 dimensional input? Is the torchvision implementation of ResNet-50 not usable for CIFAR-10?

Upvotes: 1

Views: 4611

Answers (1)

Kaushik Roy
Kaushik Roy

Reputation: 1685

Currently you are iterating over dataset that's why you are getting a (3-dimensional) single image. You actually need to iterate over dataloader to get a 4-dimensional image batch. Therefore, you just need to change the following line:

inputs,labels=next(iter(trainset))

to

inputs,labels=next(iter(trainloader))

Upvotes: 2

Related Questions