sklearn pipeline_使用python+sklearn实现单变量特征选择

本文描述了一个单变量特征选择的示例。

本文我们将噪声(无信息)特征会添加到鸢尾花(iris)数据中,并应用单变量特征选择。对于每个特征,我们绘制单变量特征选择的p值以及SVM的相应权重。我们可以看到单变量特征选择会选择有信息的特征,并且这些特征具有较大的SVM权重。

在全部特征中,只有前四个是有意义的。我们可以看到它们在单变量特征选择时得分最高。SVM会为这些特征分配较大的权重,但会选择许多其它无信息的特征。在SVM之前应用单变量特征选择会增加重要特征的SVM权重,从而改善分类结果。

dbd5f5da80bc84863f932b33eaae692b.png

sphx_glr_plot_feature_selection_001

输出:

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

ff240c3661f05d5b4bced45b0a8404a5.png

下载Python源代码:plot_feature_selection.py

下载Jupyter notebook源代码:plot_feature_selection.ipynb

由Sphinx-Gallery生成的画廊

edf5a70d90759b432bc0a9623ab00698.png ☆☆☆为方便大家查阅,小编已将scikit-learn学习路线专栏文章统一整理到公众号底部菜单栏,同步更新中,关注公众号,点击左下方“系列文章”,如图:

640?wx_fmt=png

欢迎大家和我一起沿着scikit-learn文档这条路线,一起巩固机器学习算法基础。(添加微信:mthler,备注:sklearn学习,一起进【sklearn机器学习进步群】开启打怪升级的学习之旅。)

3818d89729ebe0c4ba447e8acdb74dc6.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值