StratifiedShuffleSplit()
实现分层抽样交叉验证
1. K-折交叉验证法
- 交叉验证通常采用K-折交叉验证法–将训练数据拆分成K份,用其中K-1份进行训练,剩下的一份进行预测,从而检测模型的数据泛化能力。
- 使用
cross_val_score
可以实现交叉验证,但在某些场景下,为了解决不同类别的样本间数量差异较大的问题,可以引入sklearn.model_selection
下的StratifiedShuffleSplit
类进行分层抽样和测试数据的分割,从而提高模型的说服力。
2. StratifiedShuffleSplit
的使用
(1) 创建StratifiedShuffleSplit
对象
skfolds = StratifiedKFold(n_splits=3, random_state=25, shuffle=True)
n_split
: 用于后续split
方法中将将数据分成n_split
份,其中测试数据占1份random_state
&shffle
: 随机分割种子,若指定random_state
,则需要设置shuffle
为True。
(2) 数据切割
for train_idx, test_idx in skfolds.split(x_train, y_train):
pass
split
方法会对x_train
和y_train
的数据进行切分,得到train_idx
和test_idx
,即训练数据和测试数据的索引,其中len(train_idx) / len(test_idx)
= n_split
- 1。split
方法会根据y_train
的类别进行分层抽样。
3. 实现分层抽样的交叉验证
cross_score_SKF = []
for train_idx, test_idx in skfolds.split(x_train, y_train):
clone_clf = clone(RFClf)
x_train_folds = x_train.iloc[train_idx]
y_train_folds = y_train.iloc[train_idx]
x_test_fold = x_train.iloc[test_idx]
y_test_fold = y_train.iloc[test_idx]
clone_clf.fit(x_train_folds, y_train_folds)
y_pred_fold = clone_clf.predict(x_test_fold)
accuracy = precision_score(y_test_fold, y_pred_fold)
cross_score_SKF.append(round(accuracy, 8))
print(cross_score_SKF)
- 本例中建立了一个随机森林的基础模型,用
precision_score
即精度作为策略进行评分。 - 在使用
StratifiedShuffleSplit
实现交叉验证中,n_split
参数可理解为cross_val_score()
函数中的cv
参数。 - 最终交叉验证的精度均高于94%,可以说明模型具有较强的数据泛化能力。