One-Hot Encoding (Multi-class)
One-Hot Encoding (Multi-class)
Convert integer labels y ∈ {0,…,K-1} into one-hot matrix of shape (N, K).
One-hot encoding transforms categorical labels into binary vectors where each category is represented by a unique position. For each sample, create a row with zeros everywhere except a single 1 at the position corresponding to that sample's class label.
Function Arguments
y: array-like, shape (N,)- Non-negative integer labelsnum_classes: optional int- If None, use max(y)+1
Examples
Input: y=[0, 2, 1], num_classes=None
Output: [[1,0,0], [0,0,1], [0,1,0]]
Auto-detect: max(y)+1 = 3 classes. Each row has a 1 at the index matching the label.
Input: y=[1, 1, 0], num_classes=4
Output: [[0,1,0,0], [0,1,0,0], [1,0,0,0]]
Explicit 4 classes → 4 columns, even though max label is 1. Extra columns are all zeros.
Hint 1
Create zeros matrix, then use advanced indexing: Y[np.arange(), y] = 1.
Hint 2
If num_classes is None, compute it as np.max() + 1.
Hint 3
Validate labels with np.any() to check bounds.
Requirements
- Return NumPy array, shape (N, K), dtype float
- Rows sum to 1 (exactly one 1 per row)
- Vectorized index assignment (no Python loops)
- Validate that all labels < num_classes
- Stable for num_classes > max(y)+1 (extra zero columns)
Constraints
- N ≥ 1, K ≥ 1
- NumPy only; time limit: 300ms
Log in to take notes on this problem
Accepts: array
Accepts: any
One-Hot Encoding (Multi-class)
One-Hot Encoding (Multi-class)
Convert integer labels y ∈ {0,…,K-1} into one-hot matrix of shape (N, K).
One-hot encoding transforms categorical labels into binary vectors where each category is represented by a unique position. For each sample, create a row with zeros everywhere except a single 1 at the position corresponding to that sample's class label.
Function Arguments
y: array-like, shape (N,)- Non-negative integer labelsnum_classes: optional int- If None, use max(y)+1
Examples
Input: y=[0, 2, 1], num_classes=None
Output: [[1,0,0], [0,0,1], [0,1,0]]
Auto-detect: max(y)+1 = 3 classes. Each row has a 1 at the index matching the label.
Input: y=[1, 1, 0], num_classes=4
Output: [[0,1,0,0], [0,1,0,0], [1,0,0,0]]
Explicit 4 classes → 4 columns, even though max label is 1. Extra columns are all zeros.
Hint 1
Create zeros matrix, then use advanced indexing: Y[np.arange(), y] = 1.
Hint 2
If num_classes is None, compute it as np.max() + 1.
Hint 3
Validate labels with np.any() to check bounds.
Requirements
- Return NumPy array, shape (N, K), dtype float
- Rows sum to 1 (exactly one 1 per row)
- Vectorized index assignment (no Python loops)
- Validate that all labels < num_classes
- Stable for num_classes > max(y)+1 (extra zero columns)
Constraints
- N ≥ 1, K ≥ 1
- NumPy only; time limit: 300ms
Log in to take notes on this problem
Accepts: array
Accepts: any