在数据集不平衡的情况下,我们可以在拆分数据时使用分层,或使用交叉验证,或两者兼而有之。预先分层/CV有助于通过开发人员确认偏差来减轻这种数据泄漏。
分层
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
stratify=y,
test_size=0.25)
交叉验证
>>> from sklearn.model_selection import cross_val_score
>>> clf = svm.SVC(kernel='linear', C=1, random_state=42)
>>> scores = cross_val_score(clf, X, y, cv=5)
>>> scores
array([0.96..., 1. , 0.96..., 0.96..., 1. ])
在这个例子中,有 5 个随机拆分,5 个模型得分。
RepeatedStratifiedKFold 有帮助。
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=2, random_state=42)
scores = cross_val_score(model, X, y, scoring='mean_squared_error', cv=cv, n_jobs=-1)
print('Mean MSE: %.4f' % mean(scores))
在这个例子中,有 5 次拆分和两次迭代,总共 10 个模型的总得分。