One-Hot Encode Categorical Labels

~15 mincode completion

Implement one_hot_encode(labels, num_classes) that returns a float matrix of shape (n, num_classes).

Examples

3-class identity case: each sample gets one distinct 1

Input
one_hot_encode([0, 1, 2], 3)
Output
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Binary encoding with repeated labels

Input
one_hot_encode([1, 1, 0], 2)
Output
[[0, 1], [0, 1], [1, 0]]

Hints

Hint 1

Work directly with the arguments labels, num_classes and return the result rather than printing it.

Hint 2

Watch for this: used np eye with wrong row indexing.

Requirements

  • labels: 1D integer array of class indices in [0, num_classes-1], shape (n,)

  • num_classes: Total number of classes k

  • Return Float matrix of shape (n, num_classes) with exactly one 1.0 per row.

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~15 min

8 employers weight this skill

3 big tech firms, 2 AI product companies, 1 defense company, 1 enterprise vendor, 1 quant fund. Top match scores 87.

Python
import numpy as np

def one_hot_encode(labels: np.ndarray, num_classes: int) -> np.ndarray:
    """
    Convert integer class labels to a one-hot encoded matrix.

    Args:
        labels:      1D integer array of class indices in [0, num_classes-1], shape (n,)
        num_classes: Total number of classes k

    Returns:
        Float matrix of shape (n, num_classes) with exactly one 1.0 per row.
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.