sklearn.model_selection Part 2: Model validation

1. check_cv()

def check_cv(cv=3, y=None, classifier=False):
    if cv is None:
        cv = 3

    if isinstance(cv, numbers.Integral):
        # 如果classifier为True 并且y 是 二类或者多类,就返回 StratifiedKFold,否则返回KFold
        if (classifier and (y is not None) and
                (type_of_target(y) in ('binary', 'multiclass'))):
            return StratifiedKFold(cv)
        else:
            return KFold(cv)

    # if not hasattr(cv, 'split') or isinstance(cv, str):
    #     if not isinstance(cv, Iterable) or isinstance(cv, str):
    #         raise ValueError("Expected cv as an integer, cross-validation "
    #                          "object (from sklearn.model_selection) "
    #                          "or an iterable. Got %s." % cv)
    #     return _CVIterableWrapper(cv)

    return cv  # New style cv objects are passed without any modification

阅读源代码要抓主干,所以我把细枝末节的代码注释掉了。

2. cross_validate()

这个函数的代码有点复杂,讲解其他有用的代码。

这里 可以找到 scoring的名字对应的函数

注意

得分函数(score function)是返回的值越高越好,而损失函数(loss function)是返回的值越低越好。原来scoring中的"mean_squared_error"已经改成了"neg_mean_squared_error"。

3. cross_val_score()

返回一个 estimator 做 k 折交叉验证后产生的 k 个 在测试集上的得分。返回值是一个有k个元素的数组。

4. cross_val_predict()

cross_val_predict提供了和cross_val_score相似的接口,但是后者返回k次得分,而前者返回所有数据集上的预测结果。如果传入的参数 method = 'predict'(默认情况),那么返回(n_samples, ) 形状的ndarray,如果传入的参数 method = 'predict_proba',那么返回(n_samples, n_classes) 形状的ndarray。

5. learning_curve()

def learning_curve(estimator, X, y, groups=None,
                   train_sizes=np.linspace(0.1, 1.0, 5), cv=None, scoring=None,
                   exploit_incremental_learning=False, n_jobs=1,
                   pre_dispatch="all", verbose=0, shuffle=False,
                   random_state=None):
    # if exploit_incremental_learning and not hasattr(estimator, "partial_fit"):
    #     raise ValueError("An estimator must support the partial_fit interface "
    #                      "to exploit incremental learning")
    X, y, groups = indexable(X, y, groups)

    cv = check_cv(cv, y, classifier=is_classifier(estimator))  # 默认是KFold(3)
    # Store it as list as we will be iterating over the list multiple times
    cv_iter = list(cv.split(X, y, groups))

    scorer = check_scoring(estimator, scoring=scoring)

    n_max_training_samples = len(cv_iter[0][0])  # 取出的是第一折中的train的数目
    # Because the lengths of folds can be significantly different, it is
    # not guaranteed that we use all of the available training data when we
    # use the first 'n_max_training_samples' samples.
    # 因为不同折中的数据数目可能会是不同的,当我们使用第一个 'n_max_training_samples'
    # 并不能保证我们使用所有可用的训练数据。(第一折长度一定是最短的)
    train_sizes_abs = _translate_train_sizes(train_sizes,  # 将train_sizes中样本比例转换为具体数目(绝对size)
                                             n_max_training_samples)
    n_unique_ticks = train_sizes_abs.shape[0]
    if verbose > 0:
        print("[learning_curve] Training set sizes: " + str(train_sizes_abs))

    parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch,
                        verbose=verbose)

    if shuffle:
        rng = check_random_state(random_state)
        cv_iter = ((rng.permutation(train), test) for train, test in cv_iter)

    # if exploit_incremental_learning:  # 默认为False,暂时先忽略
    #     classes = np.unique(y) if is_classifier(estimator) else None
    #     out = parallel(delayed(_incremental_fit_estimator)(
    #         clone(estimator), X, y, classes, train, test, train_sizes_abs,
    #         scorer, verbose) for train, test in cv_iter)
    else:
        train_test_proportions = []
        for train, test in cv_iter:  # 在每一折中train有一个逐渐增大的变化,test不变
            for n_train_samples in train_sizes_abs:
                train_test_proportions.append((train[:n_train_samples], test))

        out = parallel(delayed(_fit_and_score)(
            clone(estimator), X, y, scorer, train, test,
            verbose, parameters=None, fit_params=None, return_train_score=True)
            for train, test in train_test_proportions)
        out = np.array(out)
        n_cv_folds = out.shape[0] // n_unique_ticks
        out = out.reshape(n_cv_folds, n_unique_ticks, 2)

    out = np.asarray(out).transpose((2, 1, 0))

函数的返回值:

  • train_sizes_abs :array, shape=(n_unique_ticks),曲线上每个点对应的训练数据集的size
  • train_scores:array, shape=(n_ticks, n_cv_folds),所有的在训练集上的分数。
  • test_scores: array, shape=(n_ticks, n_cv_folds),所有的在测试集上的分数。

注释掉了不重要的代码便于分析。该方法就是计算交叉验证中对于不同训练数据集大小的训练分数和测试分数。算法的中文描述如下:

  1. 将数据做 k(默认为3)折划分。
  2. 在每一折的验证中,有一个参数train_sizes (默认为np.linspace(0.1, 1.0, 5) = array([0.1 , 0.325, 0.55 , 0.775, 1. ])表示训练集依次取这一折中train_set的0.1比例的数据,0.325比例的数据,0.55比例的数据,0.775比例的数据,1.0比例的数据,然后分别和这一折中 test_set 组成新的训练集—测试集对,分别计算每一对上的训练分数和测试分数。

如果指定折数k,train_sizes的长度为m,那么训练estimator并验证其性能的过程要重复 k*m次。简单的就是在每一折上看训练集逐渐变大时,estimator的性能的变化情况。

这个函数计算的结果如何可视化的代码可以参考 这里

6. validation_curve()

计算在不同参数取值下的训练集分数和测试集分数。

需要设置的参数:

validation_curve(estimator, X, y, param_name, param_range)

param_name:string,参数名字

param_range: array-like,参数范围

返回的结果:

train_scores : array, shape (n_ticks, n_cv_folds),Scores on training sets.
test_scores : array, shape (n_ticks, n_cv_folds),Scores on test set.

可视化的代码可以参考 这里

7. permutation_test_score

不是很重要,几乎没见有用到过

原文地址:https://www.cnblogs.com/ZeroTensor/p/10278177.html