本文描述了一個單變量特徵選擇的示例。
本文我們將噪聲(無信息)特徵會添加到鳶尾花(iris)數據中,並應用單變量特徵選擇。對於每個特徵,我們繪製單變量特徵選擇的p值以及SVM的相應權重。我們可以看到單變量特徵選擇會選擇有信息的特徵,並且這些特徵具有較大的SVM權重。
在全部特徵中,只有前四個是有意義的。我們可以看到它們在單變量特徵選擇時得分最高。SVM會為這些特徵分配較大的權重,但會選擇許多其它無信息的特徵。在SVM之前應用單變量特徵選擇會增加重要特徵的SVM權重,從而改善分類結果。
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
下載Python原始碼:plot_feature_selection.py
下載Jupyter notebook原始碼:plot_feature_selection.ipynb
由Sphinx-Gallery生成的畫廊
☆☆☆為方便大家查閱,小編已將scikit-learn學習路線專欄文章統一整理到公眾號底部菜單欄,同步更新中,關注公眾號,點擊左下方「系列文章」,如圖:歡迎大家和我一起沿著scikit-learn文檔這條路線,一起鞏固機器學習算法基礎。(添加微信:mthler,備註:sklearn學習,一起進【sklearn機器學習進步群】開啟打怪升級的學習之旅。)