# Imagenet classes

**URL:** <https://discuss.pytorch.org/t/imagenet-classes/4923>\
**Category:** Uncategorized\
**Created:** [July 15, 2017, 10:02am UTC](https://discuss.pytorch.org/t/imagenet-classes/4923 "2017-07-15T10:02:46Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![arunkumar](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/a/5fc32e/32.png) [@arunkumar](https://discuss.pytorch.org/u/arunkumar)\
**Post date:** [July 15, 2017, 10:02am UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/1 "2017-07-15T10:02:46Z")

</div>

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:])
```

---

<div class="post-metadata">

**Author:** ![moskomule](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/moskomule/32/4429_2.png) [@moskomule](https://discuss.pytorch.org/u/moskomule)\
**Post date:** [July 15, 2017, 12:08pm UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/2 "2017-07-15T12:08:29Z")

</div>

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

```auto
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.

---

<div class="post-metadata">

**Author:** ![tom](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/tom/32/3162_2.png) [@tom](https://discuss.pytorch.org/u/tom)\
**Post date:** [July 15, 2017, 7:38pm UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/3 "2017-07-15T19:38:04Z")

</div>

After downloading this URL used by [keras](https://github.com/fchollet/keras/blob/master/keras/applications/imagenet_utils.py):  
[https://s3.amazonaws.com/deep-learning-models/image-models/imagenet\_class\_index.json](https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json)

you could use:

```python
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

---

<div class="post-metadata">

**Author:** ![Zijun\_Wei](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/zijun_wei/32/29211_2.png) [@Zijun\_Wei](https://discuss.pytorch.org/u/Zijun_Wei)\
**Post date:** [January 20, 2018, 10:47pm UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/4 "2018-01-20T22:47:41Z")

</div>

@tom, thanks!  
A tiny update:slight\_smile:

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

---

<div class="post-metadata">

**Author:** ![sytelus](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/sytelus/32/4689_2.png) [@sytelus](https://discuss.pytorch.org/u/sytelus)\
**Post date:** [March 29, 2019, 1:30am UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/5 "2019-03-29T01:30:09Z")

</div>

This works:

```auto
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))}

```

---

<div class="post-metadata">

**Author:** ![quantum-fusion](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/quantum-fusion/32/27762_2.png) [@quantum-fusion](https://discuss.pytorch.org/u/quantum-fusion)\
**Post date:** [August 12, 2020, 6:27pm UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/6 "2020-08-12T18:27:25Z")

</div>

I want to know where these imagenet\_class\_index.json files originate from, and how to generate them. I find it frustrating that the ONNX model zoo does not publish these artifacts, and I find little documentation on how to create them myself from scratch.

I need to know how to generate them, because I wish to model serve, and I see currently 2 options/choices for this purpose. It appears in the first example it states it needs the index\_to\_name.json file and in the second the model definition file. However, in the case of the second, it also requires a signature.json file input as well. This is all to convert an ONNX model from the model zoo to .MAR format for the model server.

1. PTH to MAR format using TorchServe

Pre-requisites to create a torch model archive (.mar) :

serialized-file (.pt) : This file represents the state\_dict in case of eager mode model.

model-file (.py) : This file contains model class extended from torch nn.modules representing the model architecture. This parameter is mandatory for eager mode models. This file must contain only one class definition extended from torch.nn.modules

index\_to\_name.json : This file contains the mapping of predicted index to class. The default TorchServe handles returns the predicted index and probability. This file can be passed to model archiver using —extra-files parameter.

version : Model’s version.

handler : TorchServe default handler’s name or path to custom inference handler(.py)

PTH to MAR format (TorchServe)

> <https://github.com/pytorch/serve/blob/master/examples/README.md>

2.) ONNX to MAR using Multi-model-server

The downloaded model artifact files are:

Model Definition (json file) - contains the layers and overall structure of the neural network.

Model Params and Weights (params file) - contains the parameters and the weights.

Model Signature (json file) - defines the inputs and outputs that MMS is expecting to hand-off to the API.

assets (text files) - auxiliary files that support model inference such as vocabularies, labels, etc. These vary depending on the model.

ONNX to MAR format (Multi-Model-Server)

> <https://github.com/awslabs/multi-model-server/blob/master/model-archiver/docs/convert_from_onnx.md>

---

<div class="post-metadata">

**Author:** ![Mona\_Jalal](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mona_jalal/32/25715_2.png) [@Mona\_Jalal](https://discuss.pytorch.org/u/Mona_Jalal)\
**Post date:** [March 3, 2022, 6:02am UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/7 "2022-03-03T06:02:51Z")

</div>

Hi Thomas,

I got this error:

```auto
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [47], in <module>
      1 import json
----> 2 class_idx = json.load("imagenet_class_index.json")
      3 idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))]
      5 for idx in out[0].sort()[1][-10:]:

File /usr/lib/python3.8/json/ __init__.py:293, in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    274 def load(fp, *, cls=None, object_hook=None, parse_float=None,
    275 parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    276 """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
    277 a JSON document) to a Python object.
    278 
   (...)
    291 kwarg; otherwise ``JSONDecoder`` is used.
    292 """
--> 293 return loads(fp.read(),
    294 cls=cls, object_hook=object_hook,
    295 parse_float=parse_float, parse_int=parse_int,
    296 parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

AttributeError: 'str' object has no attribute 'read'

```

```auto
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])

```

for

```auto
! wget 'https://www.freeiconspng.com/thumbs/cat-png/cat-png-26.png' 
from PIL import Image

cat_img = Image.open('cat-png-26.png')
cat_img_preprocessed = test_transforms(cat_img)
batch_img_cat_tensor = torch.unsqueeze(cat_img_preprocessed, 0)
out = model_ft(batch_img_cat_tensor.cuda())

```

I have this when I print out:

 ![Screen Shot 2022-03-03 at 1.02.15 AM](https://discuss.pytorch.org/uploads/default/original/3X/2/9/29f3297e35886a3cd54bba78aeed2a789625dbb8.png)

---

<div class="post-metadata">

**Author:** ![tom](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/tom/32/3162_2.png) [@tom](https://discuss.pytorch.org/u/tom)\
**Post date:** [March 3, 2022, 7:38am UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/8 "2022-03-03T07:38:30Z")

</div>

That seems more generally Python and I’m not the best person for this type of question, but the error seems to be that json.load expects an open file instead of a filename.

Best regards

Thomas

---

<div class="post-metadata">

**Author:** ![Rubiel](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/rubiel/32/52163_2.png) [@Rubiel](https://discuss.pytorch.org/u/Rubiel)\
**Post date:** [August 7, 2022, 9:54pm UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/9 "2022-08-07T21:54:54Z")

</div>

I am surprised Pytorch doesn’t have already a dictionary from outputs to classes implemented. Each image classification model should have such a dictionary.

---

<div class="post-metadata">

**Author:** ![barkermrl](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/barkermrl/32/53768_2.png) [@barkermrl](https://discuss.pytorch.org/u/barkermrl)\
**Post date:** [October 5, 2022, 4:54pm UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/10 "2022-10-05T16:54:35Z")

</div>

I came across this same problem! This page in the docs was really helpful: [Models and pre-trained weights — Torchvision main documentation](https://pytorch.org/vision/stable/models.html)

The `resnet50(pretrained=True)` command is deprecated in the latest version (v0.13 as time of writing) and can be replaced by an imported weights object:

```auto
from torchvision.models import resnet50, ResNet50_Weights

weights = ResNet50_Weights.DEFAULT
net = resnet50(weights=weights)

```

The preprocessing transforms and categories are bundled into the weights object:

```auto
centre_crop = weights.transforms()
categories = weights.meta["categories"]

```

Hopefully this is useful! 🙂

---

<div class="post-metadata">

**Author:** ![RickeyPonting](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/rickeyponting/32/47992_2.png) [@RickeyPonting](https://discuss.pytorch.org/u/RickeyPonting)\
**Post date:** [December 22, 2022, 6:47pm UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/11 "2022-12-22T18:47:42Z")

</div>

Yes, it is[,](https://myjdfaccount.top/) thanks for sharing it.

---

<div class="post-metadata">

**Author:** ![GrantElliot](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/grantelliot/32/45450_2.png) [@GrantElliot](https://discuss.pytorch.org/u/GrantElliot)\
**Post date:** [September 21, 2023, 1:43pm UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/12 "2023-09-21T13:43:04Z")

</div>

Does it really work[,](https://raiderlinkttu.us/) can anybody also help me with this?

---

<div class="post-metadata">

**Author:** ![andrewashere](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/andrewashere/32/65160_2.png) [@andrewashere](https://discuss.pytorch.org/u/andrewashere)\
**Post date:** [March 10, 2024, 1:27am UTC](https://discuss.pytorch.org/t/imagenet-classes/4923/13 "2024-03-10T01:27:38Z")

</div>

further up in the thread @tom gives a link for the S3 bucket used by keras that is still active. I used that to receive the class names with this code snippet. I have omitted the processing logic

```auto
import json

with open('imagenet_class_index.json', 'r') as f:
    idx_to_class = json.load(f)

for i, (prob, idx) in enumerate(zip(top5_probabilities[0], top5_class_indices[0])):
    class_name = idx_to_class[str(idx.item())][1] # Convert index to string, get class name
    print(f"Rank {i+1}: {class_name} with probability {prob.item():.2f}%")

```
