Expected 4D tensor as input, got 3D tensor instead

I am using pretrained network Resnet-18, all goes well but at the time of testing an image it giving the error :Expected 4D tensor as input, got 3D tensor instead.

Code:
params = torch.load(‘resnet18-5c106cde.pth’)
model_ft = models.resnet18(pretrained=False)
model_ft.load_state_dict(params)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 2)

if use_gpu:
model_ft = model_ft.cuda()

criterion = nn.CrossEntropyLoss()

Observe that all parameters are being optimized

optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)

Testing Code:
tn = transforms.Compose([
transforms.RandomSizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
print(tn)

img = Image.open(‘test/horlicks1.jpg’)
test1 = tn(img)
print(test1)
predict = model_ft1(test1)
#print(predict)

Error:
<torchvision.transforms.Compose object at 0x7fd2c7ddfe10>

( 0 ,.,.) =
-1.0048 -1.0219 -1.0562 … -1.4843 -1.5014 -1.5185
-1.0048 -1.0219 -1.0562 … -1.4843 -1.5014 -1.5185
-1.0219 -1.0390 -1.0562 … -1.4672 -1.4843 -1.5014
… ⋱ …
0.4508 0.2111 -0.0972 … -0.8678 -1.1760 -1.4158
0.4851 0.2624 -0.0458 … -0.9020 -1.2103 -1.4329
0.5022 0.2967 -0.0116 … -0.9192 -1.2274 -1.4500

( 1 ,.,.) =
-1.0903 -1.1078 -1.1429 … -1.1429 -1.1429 -1.1429
-1.0903 -1.1078 -1.1429 … -1.1429 -1.1429 -1.1429
-1.1078 -1.1253 -1.1429 … -1.1429 -1.1604 -1.1604
… ⋱ …
-0.8102 -1.0378 -1.3179 … -0.4251 -0.8452 -1.1779
-0.7927 -1.0028 -1.2829 … -0.4951 -0.9153 -1.2304
-0.7927 -0.9853 -1.2654 … -0.5301 -0.9503 -1.2654

( 2 ,.,.) =
-1.4210 -1.4384 -1.4733 … -1.5430 -1.5430 -1.5430
-1.4210 -1.4384 -1.4733 … -1.5430 -1.5430 -1.5430
-1.4384 -1.4559 -1.4559 … -1.5430 -1.5604 -1.5604
… ⋱ …
-0.8110 -1.0027 -1.2641 … 0.3393 -0.0964 -0.4275
-0.7936 -0.9678 -1.2119 … 0.2522 -0.1835 -0.4973
-0.7761 -0.9504 -1.1944 … 0.1999 -0.2184 -0.5321
[torch.FloatTensor of size 3x224x224]


ValueError Traceback (most recent call last)
in ()
12 #X = test1.resize_(1, 3, 224, 224)
13 test1 = Variable(test1.cpu())
—> 14 predict = model_ft1(test1)
15 #print(predict)

/home/rj/anaconda2/lib/python2.7/site-packages/torch/nn/modules/module.pyc in call(self, *input, **kwargs)
222 for hook in self._forward_pre_hooks.values():
223 hook(self, input)
–> 224 result = self.forward(*input, **kwargs)
225 for hook in self._forward_hooks.values():
226 hook_result = hook(self, input, result)

/home/rj/anaconda2/lib/python2.7/site-packages/torchvision-0.1.9-py2.7.egg/torchvision/models/resnet.py in forward(self, x)
137
138 def forward(self, x):
–> 139 x = self.conv1(x)
140 x = self.bn1(x)
141 x = self.relu(x)

/home/rj/anaconda2/lib/python2.7/site-packages/torch/nn/modules/module.pyc in call(self, *input, **kwargs)
222 for hook in self._forward_pre_hooks.values():
223 hook(self, input)
–> 224 result = self.forward(*input, **kwargs)
225 for hook in self._forward_hooks.values():
226 hook_result = hook(self, input, result)

/home/rj/anaconda2/lib/python2.7/site-packages/torch/nn/modules/conv.pyc in forward(self, input)
252 def forward(self, input):
253 return F.conv2d(input, self.weight, self.bias, self.stride,
–> 254 self.padding, self.dilation, self.groups)
255
256

/home/rj/anaconda2/lib/python2.7/site-packages/torch/nn/functional.pyc in conv2d(input, weight, bias, stride, padding, dilation, groups)
46 “”"
47 if input is not None and input.dim() != 4:
—> 48 raise ValueError(“Expected 4D tensor as input, got {}D tensor instead.”.format(input.dim()))
49
50 f = ConvNd(_pair(stride), _pair(padding), _pair(dilation), False,

ValueError: Expected 4D tensor as input, got 3D tensor instead.

1 Like

If you are passing one image as the input, you will have to reshape it such that it has a batch dimension, be it 1 as would be in this case.
or better
test1 = test1.unsqueeze(0)
print test1.size()

5 Likes

Thanxx a lot. Problem Solved.