Building a Simple Image Classifier with a Pretrained Model

Building an image classifier from scratch used to require substantial machine learning expertise — transfer learning from a pretrained model now makes it genuinely achievable with surprisingly little code.

import torch
from torchvision import models, transforms
from PIL import Image

# Start from a model already pretrained on millions of general images (ImageNet)
model = models.resnet18(weights='DEFAULT')
model.eval()

transform = 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]),
])

def classify(image_path):
    image = Image.open(image_path)
    input_tensor = transform(image).unsqueeze(0)
    with torch.no_grad():
        output = model(input_tensor)
    predicted_class = output.argmax(dim=1).item()
    return predicted_class

Why Transfer Learning Works So Well

A model pretrained on millions of general images has already learned genuinely useful, transferable low-level features (edges, textures, shapes, common object parts) — fine-tuning just the final layers on your own, much smaller, specific dataset (say, 500 photos of your own product categories) reuses all that already-learned general knowledge, rather than learning everything from scratch, which would require vastly more data and compute than most projects realistically have available.

Fine-Tuning for a Custom Task

Replacing the model’s final classification layer and training just that layer (or a few final layers) on your own labeled dataset adapts the pretrained model to your specific categories — a small fraction of the effort of training a comparable model completely from scratch.