How to Classify Single Image using Loaded Net
Hi, I trained, saved, and can load a resnet50 net, but am not sure of how to feed in a single image for classification using the loaded net. I’ve tried using the dataloader function, but I think that is more appropriate for testing a group of images that already have labels, whereas a single image that you are trying to classify obviously would not have a label. If you could point me to the right function to use or to a general methodology to follow, I would greatly appreciate it. 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. Thanks
nikmentenson
I use something like this. I think it’s a mashup of code from various tutorials/examples so my apologies if I should be crediting someone… uses PIL and torchvision.transforms <SCODE>imsize = 256
loader = transforms.Compose([transforms.Scale(imsize), transforms.ToTensor()])

def image_loader(image_name):
    """load image, returns cuda tensor"""
    image = Image.open(image_name)
    image = loader(image).float()
    image = Variable(image, requires_grad=True)
    image = image.unsqueeze(0)  #this is for VGG, may not be needed for ResNet
    return image.cuda()  #assumes that you're using GPU

image = image_loader(PATH TO IMAGE)

your_trained_net(image)
<ECODE> hope that helps
tymokvo
Awesome, thank you so much. That worked.
nikmentenson
Hi again, <SCODE>Variable containing:
0
[torch.LongTensor of size 1]
<ECODE> Many thanks
nikmentenson
<SCODE>variable = Variable(torch.rand(1))
num = variable.data[0]
<ECODE>
fmassa
Thanks
nikmentenson
standard casting <SCODE>int(variable.data[0])<ECODE>
tymokvo
ERROR PyTorch 0.1.11
nikmentenson
xwgeng
One last thing-wanted to confirm this is in fact correct:
nikmentenson
yes, provided the second argument to torch.max is looking at the correct dimension of the output Variable. Which yours should be, if you’re using a pretrained resnet. int(predicted.data[0])
tymokvo
<SCODE># Bunch of imports go here

# Convert image to Variable
def Torchify( aImage ):
    ptLoader = transforms.Compose([transforms.ToTensor()])
    aImage = ptLoader( aImage ).float()
    aImage = Variable( aImage, volatile=True  )
    return aImage.cuda()

# Load model from Checkpoint
print("=> Loading Network")
ptModelAxial = densenet.__dict__['densenet161'](pretrained=False, num_classes=5)
ptModelAxial.classifier = nn.Linear(8832, 5)
ptModelAxial = torch.nn.DataParallel(ptModelAxial).cuda()
dTemp = torch.load("best.pth.tar")
ptModelAxial.load_state_dict(dTemp['state_dict'])
for p in ptModelAxial.parameters():
    p.requires_grad = False
ptModelAxial.eval()

InputImg = skimage.img_as_float(skimage.io.imread(sFileName))
ptModelPreds = ptModelAxial( Torchify(InputImg) )
print( ptModelPreds )
<ECODE> Error: <SCODE>Traceback (most recent call last):
  File "extract.py", line 298
      ptModelPreds = ptModelAxial( Torchify(InputImg) )
File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/modules/module.py", line 206, in __call__
    result = self.forward(*input, **kwargs)
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/parallel/data_parallel.py", line 61, in forward
    outputs = self.parallel_apply(replicas, inputs, kwargs)
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/parallel/data_parallel.py", line 71, in parallel_apply
    return parallel_apply(replicas, inputs, kwargs)
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/parallel/parallel_apply.py", line 45, in parallel_apply
    raise output
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/parallel/parallel_apply.py", line 25, in _worker
    output = module(*input, **kwargs)
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/modules/module.py", line 206, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/keyur/kaggle/densenet.py", line 153, in forward
    features = self.features(x)
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/modules/module.py", line 206, in __call__
    result = self.forward(*input, **kwargs)
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/modules/container.py", line 64, in forward
    input = module(input)
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/modules/module.py", line 206, in __call__
    result = self.forward(*input, **kwargs)
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/modules/conv.py", line 237, in forward
    self.padding, self.dilation, self.groups)
  File "/conda3/envs/idp/lib/python3.5/site-packages/torch/nn/functional.py", line 39, in conv2d
    return f(input, weight, bias)
RuntimeError: expected 3D tensor<ECODE>
FuriouslyCurious
smth
vipin14119
So I have a couple of questions here:
isalirezag
InnovArul
micklexqg
ptrblck
sorry for so late reply, thanks!
micklexqg
Found a weird behavior here (bug), any advice? Common code: <SCODE>normalize = transforms.Normalize(
   mean=[0.485, 0.456, 0.406],
   std=[0.229, 0.224, 0.225]
)
preprocess = transforms.Compose([
   transforms.Resize(256),
   transforms.CenterCrop(224),
   transforms.ToTensor(),
   normalize
   # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

resnet_model = torchvision.models.resnet50(pretrained=True, num_classes=1000)
resnet_model.eval()

for i in range(4):
    # An instance of your model.
    img_pil = Image.open("/home/alejandro/workspace/uav_detection/images/" + str(i + 1) + ".jpg")
    # img_pil.show()
    img_tensor = preprocess(img_pil).float()
    img_tensor = img_tensor.unsqueeze_(0)

    fc_out = resnet_model(Variable(img_tensor))

    output = fc_out.detach().numpy()
    print(output.argmax())
<ECODE> <SCODE>918
918
918
918
<ECODE> Python 2.7 Anaconda and pytorch 0.4.1.post2 (downloaded with pip): <SCODE>834
208
285
478
<ECODE>
alejodosr