liveBook · Manning

Transforms

As explained in Deep Learning with PyTorch, Second Edition

The torchvision submodule containing image transformation utilities used for preprocessing and augmentation.

torchvision.transforms provides composable, function-like image transformations for preparing data before a deep-learning model evaluates it. A pipeline can resize and crop an image, convert it to a tensor, and normalize its color values. section 2.1.4 section 7.1.3

Common jobs for transforms include:

  • Convert PIL images or NumPy arrays into tensors with channel-first C × H × W dimensions. section 7.1.3
  • Scale image values from 0–255 to floating-point values from 0.0 to 1.0. section 7.1.3
  • Compose several preprocessing steps into one callable pipeline. section 2.1.4
  • Apply a transform automatically when a torchvision dataset returns an item. section 7.1.3

Prepare an image for a pretrained model

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] ) ]) img_t = preprocess(img) This produces a tensor resized and shaped for the model, with normalized RGB components matching the model's training conditions. A batch dimension can then be added with torch.unsqueeze(img_t, 0). section 2.1.4

# In[6]:
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]
        )])

Inspect the complete Compose pipeline used to resize, crop, tensorize, and normalize an input image. section 2.1.4

How Deep Learning with PyTorch, Second Edition covers it

How deep it goes
Explains composition, tensor layout, value scaling, and dataset integration, while deferring deeper transform coverage to later model-building work.
Examples
Demonstrates ToTensor on CIFAR10 data and Compose with Resize, CenterCrop, ToTensor, and Normalize on a dog image.
What it assumes
Assumes basic Python images and datasets, while teaching tensor conversion, channel ordering, and pixel-value scaling from the examples.
What you can do after
Apply it via torchvision to convert, shape, scale, normalize, and feed images into models or datasets.
How it connects
Connects image preprocessing with PIL images, NumPy arrays, PyTorch tensors, torchvision datasets, and pretrained vision models.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with PyTorch, Second Edition. The section links point to the parts of the book it draws on.