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

Beginner

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

简介

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

虚拟机使用提示

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

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

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

数据生成

我们将使用 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 个所选特征存在等效分数的平稳期。