分层 K 折
正如您刚刚看到的,由于随机划分,不同折中的目标变量分布差异较大。对于本次竞赛影响不大,但在目标变量高度不平衡的分类竞赛中可能会成为问题。
为了解决这个问题,我们来实现基于目标变量分层的 K 折交叉验证策略。train DataFrame 已在您的工作区中可用。
本练习是课程的一部分
用 Python 赢下 Kaggle 竞赛
练习说明
- 创建一个带有 3 折且启用打乱的
StratifiedKFold对象。 - 使用
str_kf对象循环遍历每个划分。分层基于 "interest_level" 列。 - 对于每个划分,使用
train_index和test_index选择训练折与测试折。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import StratifiedKFold
from sklearn.model_selection import StratifiedKFold
# Create a StratifiedKFold object
str_kf = ____(n_splits=____, shuffle=____, random_state=123)
# Loop through each split
fold = 0
for train_index, test_index in ____.____(train, train['interest_level']):
# Obtain training and testing folds
cv_train, cv_test = ____.iloc[____], ____.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