平衡模型复杂度和交叉验证得分#

此示例通过在最佳准确度得分的 1 个标准差范围内找到一个不错的准确度,同时最小化 PCA 成分的数量,来平衡模型复杂度和交叉验证得分 [1]。

该图显示了交叉验证得分与 PCA 成分数量之间的权衡。当 n_components=10 且 accuracy=0.88 时,平衡情况就出现了,这落入了最佳准确度得分的 1 个标准差范围之内。

[1] Hastie, T., Tibshirani, R., Friedman, J. (2001). 模型评估与选择。统计学习要素(第 219-260 页)。纽约,纽约,美国:施普林格纽约公司。

Balance model complexity and cross-validated score
The best_index_ is 2
The n_components selected is 10
The corresponding accuracy score is 0.88

# Author: Wenhao Zhang <[email protected]>

import matplotlib.pyplot as plt
import numpy as np

from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC


def lower_bound(cv_results):
    """
    Calculate the lower bound within 1 standard deviation
    of the best `mean_test_scores`.

    Parameters
    ----------
    cv_results : dict of numpy(masked) ndarrays
        See attribute cv_results_ of `GridSearchCV`

    Returns
    -------
    float
        Lower bound within 1 standard deviation of the
        best `mean_test_score`.
    """
    best_score_idx = np.argmax(cv_results["mean_test_score"])

    return (
        cv_results["mean_test_score"][best_score_idx]
        - cv_results["std_test_score"][best_score_idx]
    )


def best_low_complexity(cv_results):
    """
    Balance model complexity with cross-validated score.

    Parameters
    ----------
    cv_results : dict of numpy(masked) ndarrays
        See attribute cv_results_ of `GridSearchCV`.

    Return
    ------
    int
        Index of a model that has the fewest PCA components
        while has its test score within 1 standard deviation of the best
        `mean_test_score`.
    """
    threshold = lower_bound(cv_results)
    candidate_idx = np.flatnonzero(cv_results["mean_test_score"] >= threshold)
    best_idx = candidate_idx[
        cv_results["param_reduce_dim__n_components"][candidate_idx].argmin()
    ]
    return best_idx


pipe = Pipeline(
    [
        ("reduce_dim", PCA(random_state=42)),
        ("classify", LinearSVC(random_state=42, C=0.01)),
    ]
)

param_grid = {"reduce_dim__n_components": [6, 8, 10, 12, 14]}

grid = GridSearchCV(
    pipe,
    cv=10,
    n_jobs=1,
    param_grid=param_grid,
    scoring="accuracy",
    refit=best_low_complexity,
)
X, y = load_digits(return_X_y=True)
grid.fit(X, y)

n_components = grid.cv_results_["param_reduce_dim__n_components"]
test_scores = grid.cv_results_["mean_test_score"]

plt.figure()
plt.bar(n_components, test_scores, width=1.3, color="b")

lower = lower_bound(grid.cv_results_)
plt.axhline(np.max(test_scores), linestyle="--", color="y", label="Best score")
plt.axhline(lower, linestyle="--", color=".5", label="Best score - 1 std")

plt.title("Balance model complexity and cross-validated score")
plt.xlabel("Number of PCA components used")
plt.ylabel("Digit classification accuracy")
plt.xticks(n_components.tolist())
plt.ylim((0, 1.0))
plt.legend(loc="upper left")

best_index_ = grid.best_index_

print("The best_index_ is %d" % best_index_)
print("The n_components selected is %d" % n_components[best_index_])
print(
    "The corresponding accuracy score is %.2f"
    % grid.cv_results_["mean_test_score"][best_index_]
)
plt.show()

脚本总运行时间:(0 分钟 1.162 秒)

相关示例

使用交叉验证的递归特征消除

使用交叉验证的递归特征消除

使用交叉验证的网格搜索的自定义重拟合策略

使用交叉验证的网格搜索的自定义重拟合策略

比较随机森林和直方图梯度提升模型

比较随机森林和直方图梯度提升模型

文本特征提取和评估的示例管道

文本特征提取和评估的示例管道

由 Sphinx-Gallery 生成的图库