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

89. 生成 K-fold 训练集和验证集索引切分

MediumData processing and features

交叉验证报告的分数不会依赖于某一次幸运的切分。

编写 kfold_indices(n, k)。将 range(n) 按顺序切分为 k 个连续的 fold。前 n % k 个 fold 各多获得一个元素。返回一个包含 k 个元组的列表 (train_idx, val_idx),每个元组由 int 数组组成,其中第 i 个 fold 作为验证集,其余部分按顺序作为训练集。

函数def kfold_indices(n, k)

示例 1

输入: kfold_indices(5, 2)

输出: val [0, 1, 2] then val [3, 4]

示例 2

输入: [v.tolist() for _, v in kfold_indices(10, 3)]

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

示例 3

输入: [t.tolist() for t, _ in kfold_indices(7, 3)]

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

约束条件

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

Folds are contiguous blocks of range(n), and the leftover n % k elements go one each to the first folds.

提示 2

Build the fold sizes, turn them into boundaries with np.cumsum, and for each fold take the slice between two boundaries as validation and join everything else as training.

提示 3

Start the boundaries with 0, as in np.concatenate([[0], np.cumsum(sizes)]), and build training with np.concatenate of the part before and the part after the validation slice.

理解思路

K-fold 交叉验证将数据切分为 k 份,每次使用其中一份作为验证集,其余部分进行训练,从而使最终得分不依赖于某一次幸运的切分。在这里,fold 是按顺序排列的连续块;当 n 不能被 k 整除时,前 n % k 个 fold 会多获得一个元素,因此所有 fold 的大小差异最多为 1。

Worked example

n = 7, k = 3。7 // 3 = 2 余 1,所以大小为 [3, 2, 2]。Fold 0 验证 [0, 1, 2] 并使用 [3, 4, 5, 6] 进行训练。Fold 1 验证 [3, 4] 并使用 [0, 1, 2, 5, 6] 进行训练。Fold 2 验证 [5, 6] 并使用 [0, 1, 2, 3, 4] 进行训练。

size_i = n // k + (1 if i < n % k else 0); 通过在 range(n) 中移动 start 指针来切割这些大小的块;对于每个 fold,返回 (原始顺序的训练索引, 验证索引) 作为 int 数组。将所有余数都放在最后一个 fold 会使其比其他 fold 更大。常用于数据量较小时的模型选择和超参数调优。
主题
Data processing and features
相似题目
  • 按比例拆分数据集以保持各类别占比Medium
  • 将特征分桶至从训练数据中学习的分位数桶中Medium
  • 对类别进行频率编码,并为稀有和未见值设置共享桶Medium
  • 归一化后去除重复训练文本Medium
所有 Data processing and features 道题目
反馈
89 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def kfold_indices(n, k):
# your code here
pass
​

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

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