Test network on own image

Following the example from:

This code trains successfully. I ran this code and saved model.

Now I want to predict my own image. I used the following code

import torch
from mod1 import Net
from PIL import Image
import numpy

image = Image.open("plane.png")

pix = numpy.array(image) #convert image to numpy array
image.show()
net = Net()
net.eval()
img = torch.Tensor(pix) #convert numpy array to tensor
net = torch.load('pytorch_Network.h5')
print(net(img))

But I got this error:

Traceback (most recent call last):
  File "/home/ihor/Tasks/try1/pytorch_load_model.py", line 14, in <module>
    print(net(img))
  File "/home/ihor/anaconda3/envs/tensorflow/lib/python3.6/site-packages/torch/nn/modules/module.py", line 477, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/ihor/Tasks/try1/pytorch.py", line 51, in forward
    x = self.pool(F.relu(self.conv1(x)))
  File "/home/ihor/anaconda3/envs/tensorflow/lib/python3.6/site-packages/torch/nn/modules/module.py", line 477, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/ihor/anaconda3/envs/tensorflow/lib/python3.6/site-packages/torch/nn/modules/conv.py", line 301, in forward
    self.padding, self.dilation, self.groups)
RuntimeError: Expected 4-dimensional input for 4-dimensional weight [6, 3, 5, 5], but got input of size [368, 860] instead

Sorry if this is a bit basic of a question, but for some reason I could not find much online to guide me on this. I have googled a lot, read different articles but nothing helps me.

Thanks

Your model expects a 4 dimensional input, i.e. [batch_size, channels, height, width].
Since you are loading a single image, the batch dimension is missing.
You can add it with img = img.unsqueeze(0).
Also, I would recommend to transform your numpy array to a tensor using torch.from_numpy.
Note that you are not normalizing the image either, which will yield bad results.
In the code you’re using, the data is transformed using:

[transforms.ToTensor(), 
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

I would suggest to do the same in your test phase. :wink:

2 Likes

Great! Thank you!:grin: