Lesson 6 of 12
Using a Pretrained CNN
Pretrained CNNs have already been trained on millions of images. You can use them directly for classification or as a starting point for your own task.
Image Classification with ResNet
Image Classification with ResNet
# pip install torch torchvision Pillow
import torch
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
import json
def classify_image_resnet(image_path, top_k=5):
"""Classify an image using pretrained ResNet50."""
# Load pretrained ResNet50 (trained on ImageNet — 1000 classes)
model = models.resnet50(weights=models.ResNet50_Weights.IMAGENET1K_V1)
model.eval() # Set to inference mode
# Image preprocessing must match ImageNet training settings
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], # ImageNet mean
std=[0.229, 0.224, 0.225] # ImageNet std
),
])
# Load and preprocess image
image = Image.open(image_path).convert("RGB")
input_tensor = transform(image).unsqueeze(0) # Add batch dimension
# Run inference
with torch.no_grad():
output = model(input_tensor)
# Get probabilities
probabilities = torch.nn.functional.softmax(output[0], dim=0)
# Load ImageNet class labels
# In practice: download from https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json
# For this demo, we show the top indices
top_probs, top_indices = torch.topk(probabilities, top_k)
print(f"=== ResNet50 Classification: {image_path} ===")
for i, (prob, idx) in enumerate(zip(top_probs, top_indices)):
print(f" #{i+1}: Class index {idx.item():4d} — probability: {prob.item():.4f} ({prob.item()*100:.1f}%)")
print(f"\nTop class index: {top_indices[0].item()}")
print("Download imagenet_class_index.json to see class names")
return top_probs, top_indices
classify_image_resnet("photo.jpg")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment
Finished this lesson?
0 of 12 in Module 11