<jupyter_start><jupyter_text>Apply a Resnet image classifier that has been pre-trained on ImageNet<jupyter_code>import torch
from torchvision import models
torch.__version__<jupyter_output><empty_output><jupyter_text>List of pre-trained models.<jupyter_code>dir(models)
resnet = models.resnet101(pretrained=True)
resnet
resnet.fc
from torchvision import transforms
preprocess = transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize(
            mean=[0.485, 0.456, 0.406],
            std=[0.229, 0.224, 0.225]
        )])
!wget https://github.com/probml/pyprobml/blob/master/images/cat_dog.jpg?raw=true -q -O img.jpg
from PIL import Image
img = Image.open('img.jpg')
display(img)
print(type(img))
img_t = preprocess(img) # convert to tensor
print(type(img_t))
import torch
batch_t = torch.unsqueeze(img_t, 0)
print(img_t.shape)
print(batch_t.shape)
resnet.eval(); # set to eval mode (not training)
out = resnet(batch_t)
print(out.shape)

import urllib
import requests
url = "https://raw.githubusercontent.com/probml/pyprobml/master/data/imagenet_classes.txt"
response = requests.get(url)
file = urllib.request.urlopen(url)
labels = [line.strip() for line in file.readlines()]
print(labels)
# Show top 5 labels
_, indices = torch.sort(out, descending=True)
[(labels[idx], percentage[idx].item()) for idx in indices[0][:5]]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13061506565307532, 'fraction_numerical': 0.025570145127850726, 'mean_word_length': 5.008298755186722, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '601411', 'license': 'MIT', 'n_tokens_mistral': 528, 'n_tokens_neox': 502, 'n_words': 106, 'path': 'notebooks/pre_trained_image_classifier_torch.ipynb', 'repo_name': 'susnato/probml-notebooks', 'size': '1447'}