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.Scale(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
img = Image.open('elephant.jpg')
out = net(Variable(centre_crop(img).unsqueeze(0)))
print(out[0].sort()[1][-10:])
1 Like
(Moskomule) #2

I found a map of id -> label https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a .
So for example

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

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

will work, though eval may be not good way.

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

After downloading this URL used by keras:
https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json

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:]:
    print(idx2label[idx])

Best regards

Thomas

6 Likes
(Zijun Wei) #4

@tom, thanks!
A tiny update:slight_smile:

import json
class_idx = json.load(open("imagenet_class_index.json"))
1 Like
(Shital Shah) #5

This works:

import json
idx2label = []
cls2label = {}
with open("../../data/imagenet_class_index.json", "r") as read_file:
    class_idx = json.load(read_file)
    idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))]
    cls2label = {class_idx[str(k)][0]: class_idx[str(k)][1] for k in range(len(class_idx))}