【问题标题】:How to run only one fold of cross validation in sklearn?如何在 sklearn 中只运行一次交叉验证?
【发布时间】:2017-10-28 10:17:49
【问题描述】:

我有他在 SkLearn 中运行 10 倍交叉验证的代码:

cv = model_selection.KFold(n_splits=10, shuffle=True, random_state=0)
scores = model_selection.cross_val_score(MyEstimator(), x_data, y_data, cv=cv, scoring='mean_squared_error') * -1

出于调试目的,当我试图让 MyEstimator 工作时,我想只运行这个交叉验证的一个折叠,而不是全部 10 个。有没有一种简单的方法来保留这个代码,但只是说运行先折叠再退出?

我仍然希望将数据分成 10 个部分,但只对这 10 个部分的一个组合进行拟合和评分,而不是 10 个组合。

【问题讨论】:

    标签: scikit-learn


    【解决方案1】:

    不,我想不是cross_val_score。您可以将n_splits 设置为最小值 2,但这仍然是火车的 50:50 拆分,测试您可能不想要。

    如果您想保持 90:10 的比例并测试代码的其他部分,例如 MyEstimator(),那么您可以使用解决方法。

    您可以使用KFold.split() 获取第一组训练和测试索引,然后在第一次迭代后中断循环。

    cv = model_selection.KFold(n_splits=10, shuffle=True, random_state=0)
    for train_index, test_index in cv.split(x_data):
        print("TRAIN:", train_index, "TEST:", test_index)
        X_train, X_test = x_data[train_index], x_data[test_index]
        y_train, y_test = y_data[train_index], y_data[test_index]
        break
    

    现在使用这个 X_train, y_train 来训练估计器,并使用 X_test, y_test 对其进行评分。

    而不是:

    scores = model_selection.cross_val_score(MyEstimator(), 
                                             x_data, y_data, 
                                             cv=cv, 
                                             scoring='mean_squared_error')
    

    你的代码变成:

    myEstimator_fitted = MyEstimator().fit(X_train, y_train)
    y_pred = myEstimator_fitted.predict(X_test)
    
    from sklearn.metrics import mean_squared_error
    
    # I am appending to a scores list object, because that will be output of cross_val_score.
    scores = []
    scores.append(mean_squared_error(y_test, y_pred))
    

    请放心,cross_val_score 只会在内部执行此操作,只是对并行处理进行一些增强。

    【讨论】:

      猜你喜欢
      • 2013-12-13
      • 2012-12-31
      • 2016-04-13
      • 2018-05-19
      • 2018-08-16
      • 2017-04-10
      • 2015-06-11
      • 2018-04-26
      • 2021-11-24
      相关资源
      最近更新 更多