v9.1.1
Menu

Apply ToTensor Transform

easyFREETransformsPyTorch TransformsPytorch

Problem Statement

Apply the ToTensor transform to convert a NumPy array (simulating an image) into a PyTorch tensor.

Background

ToTensor from torchvision.transforms converts image data (PIL Image or NumPy array) into a normalized FloatTensor. It handles both the type conversion and value scaling automatically.

Your Task

Write a function apply_to_tensor(numpy_array) that applies the ToTensor transform and returns a dictionary describing the resulting tensor's shape, dtype, and value range.

Output Format

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

Example

Input
numpy array of shape (2, 2, 3) with values 0-255
Output
{"shape": [3, 2, 2], "dtype": "torch.float32", "min_val": 0.0, "max_val": 1.0}
Reasoning
  • Input: a tiny 2×22 \times 2 image with 3 colour channels, laid out height × width × channels, (H,W,C)=(2,2,3)(H, W, C) = (2, 2, 3), as unsigned 8-bit integers in [0,255][0, 255]. The top-left pixel is the colour triple (0,128,255)(0, 128, 255).
  • Layout: the tensor is channels-first, (C,H,W)(C, H, W), so the shape becomes [3, 2, 2]. Channel 0 is a 2×22 \times 2 grid holding the first value of every pixel: 0,64,255,1000, 64, 255, 100.
  • Scaling: every value is divided by 255255 and stored as 32-bit floating-point numbers: 64/255≈0.25164/255 \approx 0.251, 128/255≈0.502128/255 \approx 0.502, 255/255=1255/255 = 1.
  • Range: the smallest raw value is 0→0/255=00 \to 0/255 = 0, the largest is 255→1255 \to 1. Rounded to 2 decimal places, min_val is 0.0 and max_val is 1.0.
  • Output: a dictionary whose "shape" is a plain list of the three dimension sizes and whose "dtype" names the 32-bit float type as text.
  • Notice: values are only rearranged and rescaled. A uniform image of 127127s gives 127/255≈0.498127/255 \approx 0.498, so both min_val and max_val round to 0.5.

Constraints

  • Use torchvision.transforms.ToTensor
  • Input will be a NumPy array with shape (H, W, C) and dtype uint8
  • Values are in range [0, 255]
  • Round min_val and max_val to 2 decimal places

Learn this in

More from Pytorch

solution.py

Test results

Sign in to run your code against the test cases.