One-Hot Encoding

EasyMachine LearningArrayMath

Description

Given an array of integer class labels and the number of classes, return the one-hot encoding: for each label, a row of that many values that is all zeros except a single 1 at the index equal to the label.

Examples

Input:[0,2,1], 3
Output:[[1,0,0],[0,0,1],[0,1,0]]
Explanation:

Each label becomes a row of 3 values that are all zero except for a single 1 placed at the position equal to that label.

Input:[1,1,0], 2
Output:[[0,1],[0,1],[1,0]]
Explanation:

Each label becomes a row of 2 values that are all zero except for a single 1 placed at the position equal to that label.

Input:[3], 4
Output:[[0,0,0,1]]
Explanation:

Each label becomes a row of 4 values that are all zero except for a single 1 placed at the position equal to that label.

Constraints

  • 1 ≤ labels length ≤ 10³
  • 0 ≤ label < numClasses ≤ 100

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.