gpt4 book ai didi

python - 如何在 scikit-learn 中正确执行交叉验证?

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:01 25 4
gpt4 key购买 nike

我正在尝试对 k-nn 分类器进行交叉验证,但我对以下两种方法中的哪一种正确进行交叉验证感到困惑。

training_scores = defaultdict(list)
validation_f1_scores = defaultdict(list)
validation_precision_scores = defaultdict(list)
validation_recall_scores = defaultdict(list)
validation_scores = defaultdict(list)

def model_1(seed, X, Y):
np.random.seed(seed)
scoring = ['accuracy', 'f1_macro', 'precision_macro', 'recall_macro']
model = KNeighborsClassifier(n_neighbors=13)

kfold = StratifiedKFold(n_splits=2, shuffle=True, random_state=seed)
scores = model_selection.cross_validate(model, X, Y, cv=kfold, scoring=scoring, return_train_score=True)
print(scores['train_accuracy'])
training_scores['KNeighbour'].append(scores['train_accuracy'])
print(scores['test_f1_macro'])
validation_f1_scores['KNeighbour'].append(scores['test_f1_macro'])
print(scores['test_precision_macro'])
validation_precision_scores['KNeighbour'].append(scores['test_precision_macro'])
print(scores['test_recall_macro'])
validation_recall_scores['KNeighbour'].append(scores['test_recall_macro'])
print(scores['test_accuracy'])
validation_scores['KNeighbour'].append(scores['test_accuracy'])

print(np.mean(training_scores['KNeighbour']))
print(np.std(training_scores['KNeighbour']))
#rest of print statments

第二个模型中的for循环似乎是多余的。

def model_2(seed, X, Y):
np.random.seed(seed)
scoring = ['accuracy', 'f1_macro', 'precision_macro', 'recall_macro']
model = KNeighborsClassifier(n_neighbors=13)

kfold = StratifiedKFold(n_splits=2, shuffle=True, random_state=seed)
for train, test in kfold.split(X, Y):
scores = model_selection.cross_validate(model, X[train], Y[train], cv=kfold, scoring=scoring, return_train_score=True)
print(scores['train_accuracy'])
training_scores['KNeighbour'].append(scores['train_accuracy'])
print(scores['test_f1_macro'])
validation_f1_scores['KNeighbour'].append(scores['test_f1_macro'])
print(scores['test_precision_macro'])
validation_precision_scores['KNeighbour'].append(scores['test_precision_macro'])
print(scores['test_recall_macro'])
validation_recall_scores['KNeighbour'].append(scores['test_recall_macro'])
print(scores['test_accuracy'])
validation_scores['KNeighbour'].append(scores['test_accuracy'])

print(np.mean(training_scores['KNeighbour']))
print(np.std(training_scores['KNeighbour']))
# rest of print statments

我正在使用 StratifiedKFold,我不确定我是否需要像 model_2 函数中那样的循环,或者 cross_validate 函数是否已经在我们传递 时使用了拆分cv=kfold 作为参数。

我没有调用 fit 方法,这样可以吗? cross_validate 是自动调用还是我需要在调用 cross_validate 之前调用 fit

最后,如何创建混淆矩阵?我是否需要为每次折叠创建它,如果是,如何计算最终/平均混淆矩阵?

最佳答案

documentation可以说是您在此类问题上最好的 friend ;从那里的简单示例可以明显看出,您既不应该使用 for 循环,也不应该使用对 fit 的调用。调整示例以像您一样使用 KFold:

from sklearn.model_selection import KFold, cross_validate
from sklearn.datasets import load_boston
from sklearn.tree import DecisionTreeRegressor

X, y = load_boston(return_X_y=True)
n_splits = 5
kf = KFold(n_splits=n_splits, shuffle=True)

model = DecisionTreeRegressor()
scoring=('r2', 'neg_mean_squared_error')

cv_results = cross_validate(model, X, y, cv=kf, scoring=scoring, return_train_score=False)
cv_results

结果:

{'fit_time': array([0.00901461, 0.00563478, 0.00539804, 0.00529385, 0.00638533]),
'score_time': array([0.00132656, 0.00214362, 0.00134897, 0.00134444, 0.00176597]),
'test_neg_mean_squared_error': array([-11.15872549, -30.1549505 , -25.51841584, -16.39346535,
-15.63425743]),
'test_r2': array([0.7765484 , 0.68106786, 0.73327311, 0.83008371, 0.79572363])}

how can I create confusion matrix? Do I need to create it for each fold

如果您需要为每个折叠创建一个混淆矩阵,没有人能告诉您 - 这是您的选择。如果您选择这样做,最好跳过 cross_validate 并“手动”执行该过程 - 请参阅我在 How to display confusion matrix and report (recall, precision, fmeasure) for each cross validation fold 中的回答。 .

if yes, how can the final/average confusion matrix be calculated?

没有“最终/平均”混淆矩阵;如果您想计算链接答案中描述的 k 之外的任何东西(每个 k 折一个),您需要有一个单独的验证集......

关于python - 如何在 scikit-learn 中正确执行交叉验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55270431/

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