v9.1.1
Menu

Compose Multiple Transforms

mediumFREETransformsPyTorch TransformsPytorch

Problem Statement

Use Compose to chain multiple transforms together into a single transform pipeline.

Background

In practice, you often need to apply multiple transforms in sequence. Compose lets you define a pipeline where the output of each transform becomes the input to the next one.

Your Task

Write a function create_transform_pipeline() that creates a Compose pipeline to:

  1. Convert the input to a tensor
  2. Normalize it with mean=0.5 and std=0.5 for each of 3 channels

The function should return a dictionary with the output's shape, value range, and mean when applied to an image.

Output Format

Return a dictionary with keys: "shape" (list), "min_val" (float, 2 decimals), "max_val" (float, 2 decimals), "mean" (float, 2 decimals).

Example

Input
numpy array of shape (2, 2, 3) with all values 127 (mid-gray)
Output
{"shape": [3, 2, 2], "min_val": -0.0, "max_val": -0.0, "mean": -0.0}
Reasoning
  • Input: a 2×22 \times 2 image with 3 colour channels, stored height × width × channels, every value the 8-bit integer 127 (mid-gray).
  • Stage 1, rescale and reorder: each value is divided by 255, so 127/255≈0.49804127 / 255 \approx 0.49804, and the axes move to channels × height × width. That is why the shape becomes [3, 2, 2]: channel count first, then the spatial size.
  • Stage 2, standardise per channel: with mean μ=0.5\mu = 0.5 and standard deviation σ=0.5\sigma = 0.5, each value becomes x−μσ=0.49804−0.50.5≈−0.00392\frac{x - \mu}{\sigma} = \frac{0.49804 - 0.5}{0.5} \approx -0.00392.
  • Statistics: every entry is identical, so the minimum, maximum and mean are all −0.00392-0.00392. Rounded to 2 decimal places that is −0.0-0.0 (the sign survives), so -0.0 for min_val, max_val and mean.
  • Notice: these two stages map [0,255][0, 255] onto [−1,1][-1, 1]. Pure black (0) lands at 0−0.50.5=−1\frac{0 - 0.5}{0.5} = -1 and pure white (255) at 1−0.50.5=1\frac{1 - 0.5}{0.5} = 1, while 127 sits just below the midpoint because the exact middle would be 127.5.

Constraints

  • Use torchvision.transforms.Compose, ToTensor, Normalize
  • Use mean=[0.5, 0.5, 0.5] and std=[0.5, 0.5, 0.5] for Normalize
  • Round all numeric values to 2 decimal places
  • Input will be a numpy array of shape (H, W, 3)

Learn this in

More from Pytorch

solution.py

Test results

Sign in to run your code against the test cases.