Neural Mastery
← Practice
NumPy Vectorized One-Hot Matrix Encodingeasy

NumPy Vectorized One-Hot Matrix Encoding

easy NumPy & Data Wrangling 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Transform integer class label vectors into vectorized binary one-hot matrices using NumPy.

Task

Implement vectorized_one_hot(labels, num_classes). Given integer labels $0 \le \text{label} < \text{num\_classes}$, construct a 2D binary matrix of shape (len(labels), num_classes) where entry [i][labels[i]] = 1 and all others are 0. Return as a list of integer lists.

Function Signature

vectorized_one_hot(labels: list[int], num_classes: int) -> list[list[int]]

Examples

Example 1: Three Classes Sequence
Input: labels = [0, 1, 2, 1] num_classes = 3
Output: [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 0]]
Example 2: Binary Class Labels
Input: labels = [1, 0, 1, 1] num_classes = 2
Output: [[0, 1], [1, 0], [0, 1], [0, 1]]
Example 3: Single Class Category
Input: labels = [0, 0, 0] num_classes = 1
Output: [[1], [1], [1]]

Constraints

  • labels is a list of non-negative integers.
  • num_classes is an integer greater than max(labels).
  • Return 2D list of integers.
  • Return [] if labels is empty or num_classes <= 0.
Python3Saved ✓
import numpy as np

def vectorized_one_hot(labels: list[int], num_classes: int) -> list[list[int]]:
"""Convert 1D integer class labels into a 2D one-hot binary matrix using NumPy.
Shape of returned matrix: (len(labels), num_classes).
If labels is empty or num_classes <= 0, return []."""
# Your implementation here
pass

Case 1: Three Classes Sequence
Input: labels = [0, 1, 2, 1] num_classes = 3
Expected: [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 0]]
Case 2: Binary Class Labels
Input: labels = [1, 0, 1, 1] num_classes = 2
Expected: [[0, 1], [1, 0], [0, 1], [0, 1]]
Case 3: Single Class Category
Input: labels = [0, 0, 0] num_classes = 1
Expected: [[1], [1], [1]]