【问题标题】:How to interpret nested-cross validation for iris data set?如何解释 iris 数据集的嵌套交叉验证?
【发布时间】:2020-08-12 15:39:27
【问题描述】:

我想更好地理解嵌套交叉验证。我查看了 sci-kit learn 中提供的示例,该示例比较了 iris 数据集分类器上的非嵌套和嵌套交叉验证策略。

我不明白这里的嵌套交叉验证和非嵌套交叉验证有什么区别,以及使用其中一个比另一个有什么优势。

非嵌套是否意味着您没有使用交叉验证优化超参数,而是通过简单的训练验证拆分?或者这是否意味着您没有评估不同交叉验证拆分的测试准确性,而是通过简单的验证测试拆分?使用这种方法,我观察到非嵌套交叉验证的准确性更高。为什么会这样?嵌套交叉验证不应该有更好的基础来估计对测试集的泛化或更好的超参数选择吗?非嵌套的更好性能难道不是仅仅反映了幸运的训练验证或验证测试拆分吗?

from sklearn.datasets import load_iris
from matplotlib import pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV, cross_val_score, KFold
import numpy as np

print(__doc__)

# Number of random trials
NUM_TRIALS = 30

# Load the dataset
iris = load_iris()
X_iris = iris.data
y_iris = iris.target

# Set up possible values of parameters to optimize over
p_grid = {"C": [1, 10, 100],
          "gamma": [.01, .1]}

# We will use a Support Vector Classifier with "rbf" kernel
svm = SVC(kernel="rbf")

# Arrays to store scores
non_nested_scores = np.zeros(NUM_TRIALS)
nested_scores = np.zeros(NUM_TRIALS)

# Loop for each trial
for i in range(NUM_TRIALS):

    # Choose cross-validation techniques for the inner and outer loops,
    # independently of the dataset.
    # E.g "GroupKFold", "LeaveOneOut", "LeaveOneGroupOut", etc.
    inner_cv = KFold(n_splits=4, shuffle=True, random_state=i)
    outer_cv = KFold(n_splits=4, shuffle=True, random_state=i)

    # Non_nested parameter search and scoring
    clf = GridSearchCV(estimator=svm, param_grid=p_grid, cv=inner_cv)
    clf.fit(X_iris, y_iris)
    non_nested_scores[i] = clf.best_score_

    # Nested CV with parameter optimization
    nested_score = cross_val_score(clf, X=X_iris, y=y_iris, cv=outer_cv)
    nested_scores[i] = nested_score.mean()

score_difference = non_nested_scores - nested_scores

print("Average difference of {:6f} with std. dev. of {:6f}."
      .format(score_difference.mean(), score_difference.std()))

# Plot scores on each trial for nested and non-nested CV
plt.figure()
plt.subplot(211)
non_nested_scores_line, = plt.plot(non_nested_scores, color='r')
nested_line, = plt.plot(nested_scores, color='b')
plt.ylabel("score", fontsize="14")
plt.legend([non_nested_scores_line, nested_line],
           ["Non-Nested CV", "Nested CV"],
           bbox_to_anchor=(0, .4, .5, 0))
plt.title("Non-Nested and Nested Cross Validation on Iris Dataset",
          x=.5, y=1.1, fontsize="15")

# Plot bar chart of the difference.
plt.subplot(212)
difference_plot = plt.bar(range(NUM_TRIALS), score_difference)
plt.xlabel("Individual Trial #")
plt.legend([difference_plot],
           ["Non-Nested CV - Nested CV Score"],
           bbox_to_anchor=(0, 1, .8, 0))
plt.ylabel("score difference", fontsize="14")

plt.show()

【问题讨论】:

    标签: python machine-learning scikit-learn cross-validation


    【解决方案1】:

    就像你一样,起初我对这个例子感到困惑,但在我查看this thread 之后一切都变得清晰了。总而言之,在循环的每次迭代中都会计算两个分数:

    1. 非嵌套分数:
    clf = GridSearchCV(estimator=svm, param_grid=p_grid, cv=inner_cv)
    clf.fit(X_iris, y_iris)
    non_nested_scores[i] = clf.best_score_
    

    这是通过对整个数据集执行 4 倍交叉验证调整的最佳模型的得分。

    1. 嵌套分数:
    nested_score = cross_val_score(clf, X=X_iris, y=y_iris, cv=outer_cv)
    nested_scores[i] = nested_score.mean()
    

    这里是我一开始没有得到的关键点:cross_val_score 计算 clf 的 4 倍交叉验证分数,这是一个 GridSearchCV 对象,不是之前找到的最佳估计器。这意味着代码

    cross_val_score(clf, X=X_iris, y=y_iris, cv=outer_cv)
    

    将整个数据集分成 4 份(因此您有 4 种不同的训练/测试拆分)。然后在每次拆分时,它调用训练集上的clf.fit(),执行另一个独立的网格搜索。最后,它在测试集上调用clf.score(),计算在网格搜索中找到的最佳估计器在测试集上的得分。

    请注意,嵌套交叉验证的目的是找到对模型泛化误差的无偏估计。非嵌套分数更高,因为它们是根据训练中使用的数据子集计算的,因此它们过于乐观。另一方面,嵌套分数是在不用于模型选择的单独测试集上计算的,因此当您将模型应用于不可见的数据时,它们可以提供对模型准确性的更真实的估计。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-03
      • 2021-04-11
      • 2017-06-12
      • 1970-01-01
      • 2021-02-10
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多