单变量特征选择#

本笔记本展示了如何使用单变量特征选择来提高含噪数据集的分类准确率。

在此示例中,我们向鸢尾花(iris)数据集中添加了一些噪声(无信息)特征。我们使用支持向量机(SVM)分别在应用单变量特征选择前后对数据集进行分类。对于每个特征,我们绘制了单变量特征选择的 p 值以及对应的 SVM 权重。通过这种方式,我们将比较模型准确率,并考察单变量特征选择对模型权重的影响。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

生成样本数据#

import numpy as np

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# The iris dataset
X, y = load_iris(return_X_y=True)

# Some noisy data not correlated
E = np.random.RandomState(42).uniform(0, 0.1, size=(X.shape[0], 20))

# Add the noisy data to the informative features
X = np.hstack((X, E))

# Split dataset to select feature and evaluate the classifier
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)

单变量特征选择#

使用 F 检验进行特征评分的单变量特征选择。我们使用默认的选择函数来选择四个最显著的特征。

from sklearn.feature_selection import SelectKBest, f_classif

selector = SelectKBest(f_classif, k=4)
selector.fit(X_train, y_train)
scores = -np.log10(selector.pvalues_)
scores /= scores.max()
import matplotlib.pyplot as plt

X_indices = np.arange(X.shape[-1])
plt.figure(1)
plt.clf()
plt.bar(X_indices - 0.05, scores, width=0.2)
plt.title("Feature univariate score")
plt.xlabel("Feature number")
plt.ylabel(r"Univariate score ($-Log(p_{value})$)")
plt.show()
Feature univariate score

在所有特征集合中,只有原始的 4 个特征是显著的。我们可以看到,它们在单变量特征选择中获得了最高的分数。

与 SVM 的对比#

未应用单变量特征选择

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import LinearSVC

clf = make_pipeline(MinMaxScaler(), LinearSVC())
clf.fit(X_train, y_train)
print(
    "Classification accuracy without selecting features: {:.3f}".format(
        clf.score(X_test, y_test)
    )
)

svm_weights = np.abs(clf[-1].coef_).sum(axis=0)
svm_weights /= svm_weights.sum()
Classification accuracy without selecting features: 0.789

应用单变量特征选择后

clf_selected = make_pipeline(SelectKBest(f_classif, k=4), MinMaxScaler(), LinearSVC())
clf_selected.fit(X_train, y_train)
print(
    "Classification accuracy after univariate feature selection: {:.3f}".format(
        clf_selected.score(X_test, y_test)
    )
)

svm_weights_selected = np.abs(clf_selected[-1].coef_).sum(axis=0)
svm_weights_selected /= svm_weights_selected.sum()
Classification accuracy after univariate feature selection: 0.868
plt.bar(
    X_indices - 0.45, scores, width=0.2, label=r"Univariate score ($-Log(p_{value})$)"
)

plt.bar(X_indices - 0.25, svm_weights, width=0.2, label="SVM weight")

plt.bar(
    X_indices[selector.get_support()] - 0.05,
    svm_weights_selected,
    width=0.2,
    label="SVM weights after selection",
)

plt.title("Comparing feature selection")
plt.xlabel("Feature number")
plt.yticks(())
plt.axis("tight")
plt.legend(loc="upper right")
plt.show()
Comparing feature selection

如果不使用单变量特征选择,SVM 会为前 4 个原始显著特征分配较大的权重,但同时也会选择许多无信息的特征。在 SVM 之前应用单变量特征选择可以增加 SVM 对显著特征的权重分配,从而提高分类效果。

脚本运行总时长:(0 分 0.185 秒)

相关示例

连接多个特征提取方法

连接多个特征提取方法

SVM-Anova:带单变量特征选择的 SVM

SVM-Anova:带单变量特征选择的 SVM

特征聚合 vs. 单变量选择

特征聚合 vs. 单变量选择

管道 ANOVA SVM

管道 ANOVA SVM

由 Sphinx-Gallery 生成的图库