Before you start
Turn integer class labels into one-hot rows.
Given labels of shape (n,) with values in [0, num_classes), return an
(n, num_classes) array where row i is all zeros except for a 1.0 in column
labels[i].
Feeding raw integer labels to a model implies an ordering that is not there:
class 3 is not three times class 1, and it is not "between" 2 and 4.
One-hot removes that by giving every class its own axis.
Do it with advanced indexing rather than a loop. Allocating zeros and assigning
out[np.arange(n), labels] = 1.0 is the idiomatic one-liner, and it is the same
indexing trick the cross entropy problem uses to pull out the true class
probabilities.
def one_hot(labels, num_classes):
Input
one_hot(np.array([0, 2, 1]), 3)
Output
array([[1., 0., 0.],
[0., 0., 1.],
[0., 1., 0.]])
Reasoning
Each row has a single 1.0 in the column given by its label: column 0, then column 2, then column 1.
(n, num_classes).Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell