Skip to content
Easy Primitives

Implement One-Hot Encoding

One-hot encoding represents a class ID with one row of zeros and a single one. The column containing the one is the class ID, counted from zero.

Your task

Implement one_hot(labels, num_classes) without torch.nn.functional.one_hot or jax.nn.one_hot.

  • labels has shape (N,). Its values are integers in 0 <= label < num_classes, delivered by the runtime as floats.
  • num_classes is a positive integer giving the output width, including classes that do not appear in labels.
  • Return a float32 tensor of shape (N, num_classes) on the input device. Leave labels unchanged.

For each input position i and class column c:

output[i, c] = 1.0 if labels[i] == c else 0.0

For labels=[2, 0, 2] and num_classes=4, return:

[[0, 0, 1, 0],
 [1, 0, 0, 0],
 [0, 0, 1, 0]]

Keep the input order and repeated labels. Each label gets its own row; do not sort, deduplicate or infer the width from the largest label.

For an empty labels vector, return shape (0, num_classes). With one class, all valid labels are zero and every output row is [1]. Negative or out-of-range labels are outside this exercise's input contract.

Two approaches

You can allocate a zero matrix and set one entry per row using integer indices. If you choose this approach, cast labels to an integer dtype before indexing. Alternatively, compare a column of labels with a row of class IDs using broadcasting, then convert the boolean result to float32.