You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Stratified K-Fold CV时,最终预测模型该如何选择?

关于Stratified K-Fold交叉验证的模型选择问题

使用Stratified K-Fold交叉验证时,我们会为每个折(比如5折)分别训练模型,得到对应数量的模型。请问最终用于预测的模型该如何选择?比如在下方代码中,已经得到10折的准确率结果,训练完成后该选用哪个折的模型?是否直接选用准确率最高的那个模型?

# 导入所需模块
from statistics import mean, stdev
from sklearn import preprocessing
from sklearn.model_selection import StratifiedKFold
from sklearn import linear_model
from sklearn import datasets
  
# 加载特征与目标变量
cancer = datasets.load_breast_cancer()
# 输入特征
x = cancer.data                         
# 目标变量
y = cancer.target                       
  
# 特征缩放
scaler = preprocessing.MinMaxScaler()
x_scaled = scaler.fit_transform(x)
  
# 创建分类器
lr = linear_model.LogisticRegression()
  
# 创建StratifiedKFold对象
skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=1)
lst_accu_stratified = []
  
for train_index, test_index in skf.split(x, y):
    x_train_fold, x_test_fold = x_scaled[train_index], x_scaled[test_index]
    y_train_fold, y_test_fold = y[train_index], y[test_index]
    lr.fit(x_train_fold, y_train_fold)
    lst_accu_stratified.append(lr.score(x_test_fold, y_test_fold))
  
# 输出结果
print('各折准确率列表:', lst_accu_stratified)
print('\n该模型能达到的最高准确率:',
      max(lst_accu_stratified)*100, '%')
print('\n最低准确率:',
      min(lst_accu_stratified)*100, '%')
print('\n平均准确率:',
      mean(lst_accu_stratified)*100, '%')
print('\n准确率标准差:', stdev(lst_accu_stratified))

核心结论:不要直接选单折的最高准确率模型

Stratified K-Fold交叉验证的核心目的不是生成可用的预测模型,而是评估模型在未知数据上的泛化能力——你打印出的平均准确率、标准差这些指标,就是用来判断当前模型架构(比如这里的逻辑回归)在数据集上的表现是否稳定可靠。

正确的做法

  1. 用全量数据训练最终模型
    当你通过交叉验证确认了模型架构、参数的有效性后,应该用全部的训练数据(整个x_scaled和y)重新训练一个模型,这才是最终用来做预测的模型。
    比如在现有代码末尾加上:

    # 用全量数据训练最终模型
    lr_final = linear_model.LogisticRegression()
    lr_final.fit(x_scaled, y)
    

    这个lr_final就是你用来预测新数据的模型。

  2. 为什么不选单折的最高准确率模型?

    • 单折的高准确率可能是因为该折的测试集刚好和训练集分布更契合,属于运气成分,换其他数据可能表现拉胯。
    • 单折模型只用了K-1/K的数据训练,全量数据训练的模型能学习到更全面的数据模式,泛化能力更强。

补充说明

如果你的场景需要模型集成(比如模型融合),可以考虑保留所有K折的模型,用投票、平均等方式生成预测结果,但这属于进阶用法,大部分常规场景用全量数据训练的单模型就足够了。


内容的提问来源于stack exchange,提问作者roudan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 20:38:28