递归特征消除#

此示例演示了如何使用递归特征消除 (RFE) 来确定单个像素在手写数字分类中的重要性。RFE 递归地移除最不重要的特征,并根据其重要性分配排名,其中 ranking_ 值越高表示重要性越低。排名通过蓝色深浅和像素注释进行可视化,以提高清晰度。正如预期,位于图像中心的像素比靠近边缘的像素更具预测性。

Ranking of pixels with RFE (Logistic Regression)
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

import matplotlib.pyplot as plt

from sklearn.datasets import load_digits
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler

# Load the digits dataset
digits = load_digits()
X = digits.images.reshape((len(digits.images), -1))
y = digits.target

pipe = Pipeline(
    [
        ("scaler", MinMaxScaler()),
        ("rfe", RFE(estimator=LogisticRegression(), n_features_to_select=1, step=1)),
    ]
)

pipe.fit(X, y)
ranking = pipe.named_steps["rfe"].ranking_.reshape(digits.images[0].shape)

# Plot pixel ranking
plt.matshow(ranking, cmap=plt.cm.Blues)

# Add annotations for pixel numbers
for i in range(ranking.shape[0]):
    for j in range(ranking.shape[1]):
        plt.text(j, i, str(ranking[i, j]), ha="center", va="center", color="black")

plt.colorbar()
plt.title("Ranking of pixels with RFE\n(Logistic Regression)")
plt.show()

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

相关示例

手写数字识别

手写数字识别

核密度估计

核密度估计

特征凝聚

特征凝聚

标签传播数字:性能演示

标签传播数字:性能演示

由 Sphinx-Gallery 生成的画廊