liveBook · Manning

ToTensor

As explained in Inside Deep Learning: Math, Algorithms, Models

A torchvision transform that converts a PIL image into a PyTorch tensor with values scaled to a numeric range suitable for learning.

ToTensor converts a PIL image into a PyTorch tensor with values in the possible range 0.0–1.0, making image data ready for model input. For MNIST, the result uses channel-first shape (C, H, W), such as (1, 28, 28) for grayscale images. section 3.1.1

Apply ToTensor while loading MNIST

mnist_train = torchvision.datasets.MNIST("./data", train=True, download=True, transform=transforms.ToTensor()) x_example, y_example = mnist_train[0] print(x_example.shape) # torch.Size([1, 28, 28]) Place ToTensor inside transforms.Compose when combining it with augmentation. Keep the test transform as transforms.ToTensor() so evaluation remains deterministic. section 3.1.1 section 3.6

mnist_data_train = torchvision.datasets.MNIST("./data", train=True, 
 download=True, transform=transforms.ToTensor()) 
mnist_data_test = torchvision.datasets.MNIST("./data", train=False, 
 download=True, transform=transforms.ToTensor()) 
x_example, y_example = mnist_data_train[0] 
print(x_example.shape)

torch.Size([1, 28, 28])

Shows the complete MNIST dataset configuration and the resulting tensor shape. section 3.1.1

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Defines the conversion, numeric range, channel-first shape, and pipeline placement without explaining conversion internals.
Examples
Uses MNIST grayscale images, a (1, 28, 28) tensor, and a Compose pipeline combining RandomAffine with ToTensor.
What it assumes
Assumes basic dataset loading and image concepts while establishing PIL-to-tensor conversion from the returned dataset type.
What you can do after
Apply it via torchvision.transforms to make image datasets return normalized PyTorch tensors for training and evaluation.
How it connects
Connects PIL images, PyTorch tensors, torchvision transforms, data augmentation, and deterministic test preprocessing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.