本文描述了一个单变量特征选择的示例。
本文我们将噪声(无信息)特征会添加到鸢尾花(iris)数据中,并应用单变量特征选择。对于每个特征,我们绘制单变量特征选择的p值以及SVM的相应权重。我们可以看到单变量特征选择会选择有信息的特征,并且这些特征具有较大的SVM权重。
在全部特征中,只有前四个是有意义的。我们可以看到它们在单变量特征选择时得分最高。SVM会为这些特征分配较大的权重,但会选择许多其它无信息的特征。在SVM之前应用单变量特征选择会增加重要特征的SVM权重,从而改善分类结果。
输出:
Classification accuracy without selecting features: 0.789
Classification accuracy after univariate feature selection: 0.868
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import LinearSVC
from sklearn.pipeline import make_pipeline
from sklearn.feature_selection import SelectKBest, f_classif
# #############################################################################
# 导入一些数据进行训练
# 鸢尾花植物数据集
X, y = load_iris(return_X_y=True)
# 一些不相关的噪声数据
E = np.random.RandomState(42).uniform(0, 0.1, size=(X.shape[0], 20))
# 将噪声数据添加到有信息的特征中
X = np.hstack((X, E))
# 分割数据集以选择特征并评估分类器
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
plt.figure(1)
plt.clf()
X_indices = np.arange(X.shape[-1])
# #############################################################################
# 通过F检验进行单变量特征选择以进行特征评分
# 我们使用默认选择函数来选择四个最重要的特征
selector = SelectKBest(f_classif, k=4)
selector.fit(X_train, y_train)
scores = -np.log10(selector.pvalues_)
scores /= scores.max()
plt.bar(X_indices - .45, scores, width=.2,
label=r'Univariate score ($-Log(p_{value})$)', color='darkorange',
edgecolor='black')
# #############################################################################
# 与SVM的权重进行比较
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()
plt.bar(X_indices - .25, svm_weights, width=.2, label='SVM weight',
color='navy', edgecolor='black')
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()
plt.bar(X_indices[selector.get_support()] - .05, svm_weights_selected,
width=.2, label='SVM weights after selection', color='c',
edgecolor='black')
plt.title("Comparing feature selection")
plt.xlabel('Feature number')
plt.yticks(())
plt.axis('tight')
plt.legend(loc='upper right')
plt.show()
脚本的总运行时间:(0分钟0.441秒)
估计的内存使用量: 8 MB
下载Python源代码:plot_feature_selection.py
下载Jupyter notebook源代码:plot_feature_selection.ipynb
由Sphinx-Gallery生成的画廊
☆☆☆为方便大家查阅,小编已将scikit-learn学习路线专栏文章统一整理到公众号底部菜单栏,同步更新中,关注公众号,点击左下方“系列文章”,如图:欢迎大家和我一起沿着scikit-learn文档这条路线,一起巩固机器学习算法基础。(添加微信:mthler,备注:sklearn学习,一起进【sklearn机器学习进步群】开启打怪升级的学习之旅。)