PIXELBANKv8.2.1
Menu

Create Lambda Transform

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:

Lambda transform creates a zero tensor and sets index 2 to 1.0

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
Editor

Test Results

0/0
Run code to see test results.