86. 按比例拆分数据集以保持各类别占比
对于稀有类别,随机拆分可能会导致测试集中几乎没有这些类别。分层拆分(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。
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) 个索引。像欺诈检测这样的不平衡问题非常依赖分层拆分。