带交叉验证的递归特征消除

Machine LearningMachine LearningBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将逐步介绍如何使用scikit-learn实现带交叉验证的递归特征消除(RFECV)。RFECV用于特征选择,即选择相关特征的子集以用于模型构建的过程。我们将使用一个具有15个特征的分类任务,其中3个是信息性的,2个是冗余的,10个是非信息性的。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问Jupyter Notebook进行练习。

有时,你可能需要等待几秒钟让Jupyter Notebook完成加载。由于Jupyter Notebook的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,可以随时向Labby提问。课程结束后提供反馈,我们会及时为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) sklearn(("Sklearn")) -.-> sklearn/DataPreprocessingandFeatureEngineeringGroup(["Data Preprocessing and Feature Engineering"]) sklearn(("Sklearn")) -.-> sklearn/ModelSelectionandEvaluationGroup(["Model Selection and Evaluation"]) sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/linear_model("Linear Models") sklearn/DataPreprocessingandFeatureEngineeringGroup -.-> sklearn/feature_selection("Feature Selection") sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/model_selection("Model Selection") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/datasets("Datasets") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/linear_model -.-> lab-49268{{"带交叉验证的递归特征消除"}} sklearn/feature_selection -.-> lab-49268{{"带交叉验证的递归特征消除"}} sklearn/model_selection -.-> lab-49268{{"带交叉验证的递归特征消除"}} sklearn/datasets -.-> lab-49268{{"带交叉验证的递归特征消除"}} ml/sklearn -.-> lab-49268{{"带交叉验证的递归特征消除"}} end

数据生成

我们将使用scikit-learn的make_classification函数生成一个分类任务。我们将生成500个样本,每个样本有15个特征,其中3个是信息性的,2个是冗余的,10个是非信息性的。

from sklearn.datasets import make_classification

X, y = make_classification(
    n_samples=500,
    n_features=15,
    n_informative=3,
    n_redundant=2,
    n_repeated=0,
    n_classes=8,
    n_clusters_per_class=1,
    class_sep=0.8,
    random_state=0,
)

模型训练与选择

我们将创建RFECV对象并计算交叉验证分数。评分策略“accuracy”(准确率)用于优化正确分类样本的比例。我们将使用逻辑回归作为估计器,并采用5折分层k折交叉验证。

from sklearn.feature_selection import RFECV
from sklearn.model_selection import StratifiedKFold
from sklearn.linear_model import LogisticRegression

min_features_to_select = 1  ## 要考虑的最小特征数量
clf = LogisticRegression()
cv = StratifiedKFold(5)

rfecv = RFECV(
    estimator=clf,
    step=1,
    cv=cv,
    scoring="accuracy",
    min_features_to_select=min_features_to_select,
    n_jobs=2,
)
rfecv.fit(X, y)

print(f"Optimal number of features: {rfecv.n_features_}")

绘制特征数量与交叉验证分数的关系图

我们将绘制所选特征数量与交叉验证分数的关系图。我们将使用matplotlib来创建该图。

import matplotlib.pyplot as plt

n_scores = len(rfecv.cv_results_["mean_test_score"])
plt.figure()
plt.xlabel("Number of features selected")
plt.ylabel("Mean test accuracy")
plt.errorbar(
    range(min_features_to_select, n_scores + min_features_to_select),
    rfecv.cv_results_["mean_test_score"],
    yerr=rfecv.cv_results_["std_test_score"],
)
plt.title("Recursive Feature Elimination \nwith correlated features")
plt.show()

总结

在本实验中,我们经历了使用scikit-learn实现带交叉验证的递归特征消除(RFECV)的过程。我们生成了一个具有15个特征的分类任务,其中3个是信息性的,2个是冗余的,10个是非信息性的。我们使用逻辑回归作为估计器,并采用5折分层k折交叉验证。我们绘制了所选特征数量与交叉验证分数的关系图。我们发现最优特征数量为3,这与真实的生成模型相对应。由于引入了相关特征,我们还注意到对于3到5个所选特征存在等效分数的平稳期。