InterviewPrepKit

Home / Coding / Machine Learning Coding / Numerical & Data / One-Hot Encoding

One-Hot Encoding

easy 00:00
Solving tips
  • A one-hot matrix is mostly zeros with a single 1 per row — start from a zero matrix and place the ones.
  • NumPy fancy indexing sets all the ones at once: rows[np.arange(n), labels] = 1, no Python loop.
  • The identity trick np.eye(num_classes)[labels] is an even shorter vectorized route to the same result.

Convert a 1-D array of integer class labels into a one-hot encoded matrix. One-hot encoding is the standard way to feed categorical labels into models that expect a vector target (softmax classifiers, cross-entropy loss), and interviewers use it to check that you can turn a per-row index into a matrix with NumPy indexing instead of a loop.

Definition

Given n labels and num_classes columns, the output is an (n, num_classes) matrix where row i is all zeros except for a single 1 in column labels[i].

Task

Complete one_hot_encode(labels, num_classes) so it returns the (n, num_classes) one-hot matrix. labels is a 1-D NumPy array of integers, each in [0, num_classes). Use vectorized NumPy indexing; do not write a Python loop and do not call sklearn or any built-in one-hot helper.

Example

labels = np.array([0, 2, 1, 2])
one_hot_encode(labels, 3)
# -> array([[1, 0, 0],
#           [0, 0, 1],
#           [0, 1, 0],
#           [0, 0, 1]])

Row 0 has its 1 in column 0, row 1 in column 2, row 2 in column 1, and row 3 in column 2.

Constraints

  • 1 <= n <= 10^6 and 1 <= num_classes <= 10^4; use vectorized NumPy, not a Python loop.
  • Every value in labels is a valid class index in [0, num_classes).

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug