MNIST is a collection of black-and-white handwritten digits from 0 through 9. Each image is 28×28 pixels, making it a compact testbed for image-loading code and tensor-shaped data. section 3.1.1
Load and inspect MNIST with torchvision:
- Request predefined training and testing splits with torchvision.datasets.MNIST, optionally downloading data into a local directory. section 3.1.1
- Add transforms.ToTensor() to convert PIL images into tensors with values from 0.0 to 1.0. section 3.1.1
- Read an example as a one-channel tensor with shape (1, 28, 28), then remove the channel dimension for grayscale visualization. section 3.1.1
Tensor experiments
Stack one grayscale image three times to create a 3×28×28 tensor, combine three images as color channels, or randomly shuffle flattened pixels to see how spatial structure affects the image. section 3.1.1
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])
Use the loading snippet to inspect the transformed dataset and verify the first example’s tensor shape. section 3.1.1




