gpt4 book ai didi

python - 为什么 cross_val_score 和我手动计算的不一样?

转载 作者:行者123 更新时间:2023-12-04 01:07:47 25 4
gpt4 key购买 nike

这是可重现示例代码:

from numpy import mean
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_validate
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import balanced_accuracy_score

# define dataset
X, y = make_classification(n_samples=1000, weights = [0.3,0.7], n_features=100, n_informative=75, random_state=0)
# define the model
model = RandomForestClassifier(n_estimators=10, random_state=0)
# evaluate the model
n_splits=10
cv = StratifiedShuffleSplit(n_splits, random_state=0)
n_scores = cross_validate(model, X, y, scoring='balanced_accuracy', cv=cv, n_jobs=-1, error_score='raise')
# report performance
print('Accuracy: %0.4f' % (mean(n_scores['test_score'])))

bal_acc_sum = []
for train_index, test_index in cv.split(X,y):
model.fit(X[train_index], y[train_index])
bal_acc_sum.append(balanced_accuracy_score(model.predict(X[test_index]),y[test_index]))

print(f"Accuracy: %0.4f" % (mean(bal_acc_sum)))

结果:

Accuracy: 0.6737
Accuracy: 0.7113

我自己计算的准确度结果总是高于交叉验证给我的结果。但它应该是一样的还是我遗漏了什么?相同的指标,相同的拆分(KFold 带来相同的结果),相同的固定模型(其他模型表现相同),相同的随机状态,但结果不同?

最佳答案

这是因为,在您的手动计算中,您翻转了 balanced_accuracy_score 中参数的顺序,这很重要 - 它应该是 (y_true, y_pred) ( docs ) .

改变这个,你的手动计算变成:

bal_acc_sum = []
for train_index, test_index in cv.split(X,y):
model.fit(X[train_index], y[train_index])
bal_acc_sum.append(balanced_accuracy_score(y[test_index], model.predict(X[test_index]))) # change order of arguments here

print(f"Accuracy: %0.4f" % (mean(bal_acc_sum)))

结果:

Accuracy: 0.6737

import numpy as np
np.all(bal_acc_sum==n_scores['test_score'])
# True

关于python - 为什么 cross_val_score 和我手动计算的不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65848571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com