2. 使用 fancy indexing 进行类别标签的 one-hot 编码
Cross-entropy 和大多数分类器都要求标签为 one-hot 行:例如 4 个类别中的标签 2 会变成 [0, 0, 1, 0]。
编写 one_hot(labels, num_classes),返回一个 shape 为 (len(labels), num_classes) 的 float 数组,每行包含一个 1.0。
不要使用 Python 循环来实现。
def one_hot(labels, num_classes)示例 1
输入: one_hot([0, 2], 3)
输出: [[1, 0, 0], [0, 0, 1]]
示例 2
输入: labels = [1, 1, 0, 3], num_classes = 4
输出: [[0.0, 1.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
示例 3
输入: labels = [0], num_classes = 1
输出: [[1.0]]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Each row has exactly one 1.0, and its column is the label, so you only need to write n values into an all-zeros array.
提示 2
Create a float zeros array of shape (n, num_classes), then use fancy indexing with one row index and one column index per sample to set the ones in a single assignment.
提示 3
Pair np.arange(n) as the row indices with the labels as the column indices: out[np.arange(n), labels] = 1.0. Convert labels with np.asarray(labels, dtype=int) first so a plain list works.
常见错误
- 使用
out[:, labels]进行索引会导致每一行都设置了整列,这是错误版本中的 bug。
理解思路
One-hot 编码将类别编号转换为一行零,并在该类别位置设置一个 1。这就像一排电灯开关,只有选中类别的开关是打开的。NumPy fancy indexing 可以通过一行代码设置所有的 1:你提供一个行索引列表和与之对应的列索引列表,它就会精确设置这些单元格。
labels [1, 0, 3], num_classes 4。从一个 3 by 4 的零数组开始。行索引 [0, 1, 2] 与列 [1, 0, 3] 配对,设置单元格 (0,1), (1,0), (2,3)。结果: [[0,1,0,0], [1,0,0,0], [0,0,0,1]]。一个常见的错误是在列索引处仅使用 label 数组而没有行索引,这会导致整列被置为 1。
out = zeros(n, C); out[arange(n), labels] = 1.0。分类器和 cross-entropy loss 使用 one-hot 目标。