Imagenet classes

(Arun Kumar) #1

I am trying to use a pretrained resnet model to test on a elephant image. How do we get the class name after getting class id. Also I am not sure I am doing preprocessing correctly. Is this the right approach?

import torch
import torchvision.transforms as transforms
from torch.autograd import Variable
from torchvision.models import resnet50
from PIL import Image

net = resnet50(pretrained=True)
centre_crop = transforms.Compose([
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
img ='elephant.jpg')
out = net(Variable(centre_crop(img).unsqueeze(0)))

(Moskomule) #2

I found a map of id -> label .
So for example

with open("imagenet1000_clsid_to_human.txt") as f:
    idx2label = eval(

for idx in out[0].sort()[1][-10:]:

will work, though eval may be not good way.

Trouble getting pretrained ResNet152 to classify images properly
What is the list of Classes for any Pre-Trained Model
(Thomas V) #3

After downloading this URL used by keras:

you could use:

import json
class_idx = json.load("imagenet_class_index.json")
idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))]

for idx in out[0].sort()[1][-10:]:

Best regards


(Zijun Wei) #4

@tom, thanks!
A tiny update:slight_smile:

import json
class_idx = json.load(open("imagenet_class_index.json"))