BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / NumPy foundations2 of 23 in topic

2. 使用 fancy indexing 进行类别标签的 one-hot 编码

EasyNumPy foundations

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:你提供一个行索引列表和与之对应的列索引列表,它就会精确设置这些单元格。

Worked example

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 目标。
主题
NumPy foundations
相似题目
  • 不使用 Python 循环计算所有成对距离Easy
  • 对排行榜分数进行排名,使并列分数共享名次Easy
  • 使用 argsort 的逆排列撤销长度排序Easy
  • 使用 np.unique 将稀疏 token ids 映射到紧凑的词表Easy
所有 NumPy foundations 道题目
反馈
2 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def one_hot(labels, num_classes):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS