v9.1.1
Menu

Create Lambda Transform

mediumFREETransformsPyTorch TransformsPytorch

Problem Statement

Create a Lambda transform that converts integer labels to one-hot encoded tensors.

Background

Lambda transforms let you wrap any custom function as a torchvision transform. One-hot encoding is a common technique that converts a class label into a binary vector — useful for classification tasks.

Your Task

Write a function create_onehot_transform(num_classes) that returns a Lambda transform. When applied to an integer label, the transform should produce a dictionary with the one-hot tensor and its sum.

Output Format

The transform should return a dictionary with keys: "tensor" (one-hot list), "sum" (float, should be 1.0).

Example

Input
num_classes=5, then apply to label=2
Output
{"tensor": [0.0, 0.0, 1.0, 0.0, 0.0], "sum": 1.0}
Reasoning
  • Inputs: num_classes =5= 5 sets the vector length: one slot per class, indexed 00 to 44. The label 2 is this example's class.
  • Math: the one-hot vector ee for label kk has ei=1e_i = 1 when i=ki = k and ei=0e_i = 0 otherwise. With k=2k = 2: e0=0, e1=0, e2=1, e3=0, e4=0e_0 = 0,\ e_1 = 0,\ e_2 = 1,\ e_3 = 0,\ e_4 = 0, which gives [0.0, 0.0, 1.0, 0.0, 0.0].
  • Sum: ∑i=04ei=0+0+1+0+0=1\sum_{i=0}^{4} e_i = 0 + 0 + 1 + 0 + 0 = 1, so sum is 1.0. It is 11 for any valid label, since exactly one slot is lit.
  • Output: a dictionary: tensor is the vector as a plain list of floats, sum is that total. Both are floats (1.01.0, not 11): the vector is a probability distribution with all its mass on one class.
  • Notice: only the position of the 11 depends on the label. Label 0 with 33 classes gives [1.0, 0.0, 0.0], and label 33 with 44 classes gives [0.0, 0.0, 0.0, 1.0], the last slot.

Constraints

  • Use torchvision.transforms.Lambda
  • Use torch.zeros and scatter_ for one-hot encoding
  • num_classes will be between 2 and 10
  • Labels will be valid integers from 0 to num_classes-1

Learn this in

More from Pytorch

solution.py

Test results

Sign in to run your code against the test cases.