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

86. 按比例拆分数据集以保持各类别占比

MediumData processing and features

对于稀有类别,随机拆分可能会导致测试集中几乎没有这些类别。分层拆分(stratified split)则从每个类别中提取相同的比例。

编写 stratified_split(labels, test_frac)。按照类别首次出现的顺序,对于每个类别,按其原始顺序提取索引,并将最后 round(count * test_frac) 个索引放入测试集。返回 (train_idx, test_idx) 作为排序后的 int 列表。

使用 Python 的 round 函数(使用 banker's rounding 即可)。

函数def stratified_split(labels, test_frac)

示例 1

输入: labels = ['a'] * 8 + ['b'] * 2, test_frac = 0.5

输出: ([0, 1, 2, 3, 8], [4, 5, 6, 7, 9])

示例 2

输入: labels = [0, 1, 0, 1, 0, 1, 0, 1], test_frac = 0.25

输出: ([0, 1, 2, 3, 4, 5], [6, 7])

示例 3

输入: labels = [1, 2, 3], test_frac = 0.0

输出: ([0, 1, 2], [])

约束条件

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

Treat each class separately: split it on its own and then merge the pieces.

提示 2

Group indices by label in a dict (insertion order keeps first appearance), compute how many of each group go to test, slice the tail of each group into test and the rest into train, then sort both lists.

提示 3

With k = round(len(group) * test_frac), the test part is group[len(group) - k:]; slicing with len(group) - k instead of -k keeps k = 0 from putting the whole group in test.

常见错误
  • 对整个列表进行普通拆分(错误的实现方式)可能会导致稀有类别完全不在测试集中。
理解思路

分层拆分在测试集中为每个类别提取相同的比例,因此不会因为偶然因素丢失稀有类别。这就像从每个班级选出一名代表,而不是从一个帽子里随机抽名字。按类别首次出现的顺序对索引进行分组。从每个组中,保持原始顺序,将最后 round(count * test_frac) 个索引分配给 test,其余分配给 train。

Worked example

labels [a, a, a, a, b, b], test_frac 0.5。类别 a 的索引为 [0, 1, 2, 3]; round(2.0) = 2,所以 2 和 3 进入 test。类别 b 的索引为 [4, 5]; round(1.0) = 1,所以 5 进入 test。Test = [2, 3, 5], train = [0, 1, 4],两者均已排序。注意 Python 的 round 使用 banker's rounding:round(2.5) 是 2,round(0.5) 是 0。

每个类别中,test 获取最后 round(n_c * frac) 个索引。像欺诈检测这样的不平衡问题非常依赖分层拆分。
主题
Data processing and features
相似题目
  • 将特征分桶至从训练数据中学习的分位数桶中Medium
  • 对类别进行频率编码,并为稀有和未见值设置共享桶Medium
  • 生成 K-fold 训练集和验证集索引切分Medium
  • 归一化后去除重复训练文本Medium
所有 Data processing and features 道题目
反馈
86 / 903
Python 3solution.pyPython 空闲
1
2
3
4
def stratified_split(labels, test_frac):
# your code here
pass
​

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

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