我们如何获得交叉验证中每个折叠的基线?

数据挖掘 机器学习 Python scikit-学习
2022-03-12 20:55:11

鉴于我正在使用 Scikit 学习和交叉验证,并希望将每次折叠的准确度结果与我的基线进行比较

我正在使用 10 折交叉验证,以及如何为每折返回该折的基线。是否可以?

clf= RandomForestClassifier(n_estimators=100, random_state=20)
# 10-Fold Cross validation
scores = cross_val_score(clf, features, labels, cv=10)
scores

结果:数组([0.45454545, 0.63636364, 0.8, 0.8, 0.6, 0.6, 0.5, 0.9, 0.66666667, 0.33333333])

2个回答

我认为您正在寻找: ,请参阅此处sklearn.model_selection.cross_validate的文档

返回:
scores : dict of float arrays of shape=(n_splits,) 每次交叉验证运行的估计器得分数组。返回包含每个记分器的分数/时间数组的数组字典。此 dict 的可能键是:

test_score每个 cv 拆分的测试分数的分数数组。

train_score每个 cv 拆分的训练分数的分数数组。[...]


最小的例子:

from sklearn import datasets, linear_model
from sklearn.model_selection import cross_validate

# Data
diabetes = datasets.load_diabetes()
X = diabetes.data[:150]
y = diabetes.target[:150]

# Model
lasso = linear_model.Lasso()
cv_results = cross_validate(lasso, X, y, cv=10)

# Print keys
print(sorted(cv_results.keys()))
# Print test_scores
print(cv_results['test_score'])

回报:

['fit_time', 'score_time', 'test_score', 'train_score']
[ 0.34557351  0.34848715  0.26654262 -0.01126674  0.24875619  0.08731544
  0.13386583  0.14000888  0.2873109   0.00960079]

我找到了一个解决方案,但我不知道这是否正确:

X = np.array(features)
y = np.array(labels)
kf = KFold(n_splits=10, random_state=20)
kf.get_n_splits(features)

print(kf)

for train_index, test_index in kf.split(X):
    # print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    print(np.mean(y_test))

如果得到相同的randon_state,我希望得到相同的折叠。