K 折交叉验证
您将从最常用的 K 折交叉验证开始动手实践。
本题使用的数据来自 Kaggle 比赛 "Two sigma connect: rental listing inquiries"。该比赛任务是将房源信息进行多分类,共 3 个类别:低关注度、中等关注度和高关注度。为加快运行,您将使用包含 1,000 条观测的子样本。
您需要实现 K 折验证策略,并查看得到的每个折的大小。train DataFrame 已在您的工作区中可用。
本练习是课程的一部分
用 Python 赢下 Kaggle 竞赛
练习说明
- 创建一个包含 3 折的
KFold对象。 - 使用
kf对象遍历每个划分。 - 对于每个划分,使用
train_index和test_index选择训练折与测试折。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import KFold
from sklearn.model_selection import KFold
# Create a KFold object
kf = ____(n_splits=____, shuffle=True, random_state=123)
# Loop through each split
fold = 0
for train_index, test_index in ____.____(train):
# Obtain training and testing folds
cv_train, cv_test = train.iloc[____], train.iloc[____]
print('Fold: {}'.format(fold))
print('CV train shape: {}'.format(cv_train.shape))
print('Medium interest listings in CV train: {}\n'.format(sum(cv_train.interest_level == 'medium')))
fold += 1