【特征工程】特征选择Feature Selection

正好在写这部分,就顺带练习一下吧。
一如既往地,来源:https://towardsdatascience.com/feature-selection-techniques-1bfab5fe0784
数据集:https://www.kaggle.com/uciml/mushroom-classification

减少特征数量的好处有:

  • 准确性提高。
  • 减少过度拟合。
  • 加快训练速度。
  • 改进数据可视化。
  • 增加模型的可解释性。

经统计证明,存在用于每个特定任务的最佳特征数量(图1)。如果添加的功能多于严格必要的功能,那么我们的模型性能将下降(由于添加的噪音)。 真正的挑战是找出要使用的最佳功能数量。
见:https://www.visiondummy.com/2014/04/curse-dimensionality-affect-classification/

【特征工程】特征选择Feature Selection_第1张图片

概念

有许多不同的方法可用于特征选择。 一些最重要的是:

  • 1.Filter Method
    做法:过滤数据集,只取其中的一个子集,包含所有相关的功能。
    **具体操作:**使用皮尔逊相关的相关矩阵
  • 2.Wrapper Method
    做法:使用Forward/Backward/Bidirectional/Recursive Feature Elimination作为评价标准。其结果可能比过滤更准确,但计算量更大。
    3.Embedded Method
    LASSO Regularization
    【特征工程】特征选择Feature Selection_第2张图片

具体操作

导入库

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import seaborn as sns
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier
from sklearn import svm

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8124 entries, 0 to 8123
Data columns (total 23 columns):
class                       8124 non-null object
cap-shape                   8124 non-null object
cap-surface                 8124 non-null object
cap-color                   8124 non-null object
bruises                     8124 non-null object
odor                        8124 non-null object
gill-attachment             8124 non-null object
gill-spacing                8124 non-null object
gill-size                   8124 non-null object
gill-color                  8124 non-null object
stalk-shape                 8124 non-null object
stalk-root                  8124 non-null object
stalk-surface-above-ring    8124 non-null object
stalk-surface-below-ring    8124 non-null object
stalk-color-above-ring      8124 non-null object
stalk-color-below-ring      8124 non-null object
veil-type                   8124 non-null object
veil-color                  8124 non-null object
ring-number                 8124 non-null object
ring-type                   8124 non-null object
spore-print-color           8124 non-null object
population                  8124 non-null object
habitat                     8124 non-null object
dtypes: object(23)
memory usage: 1.4+ MB
None

简单的数据处理

  • 1设置Target和predictor
  • 2.编码
  • 3.划分数据集
data = pd.read_csv("C:\\Users\\Nihil\\Documents\\pythonlearn\\data\\kaggle\\mushrooms.csv")
X = data.drop(['class'],axis=1)
y = data['class']

X = pd.get_dummies(X,prefix_sep='_')
y = LabelEncoder().fit_transform(y)
X2 = StandardScaler().fit_transform(X)

X_train,X_test,y_train,y_test = train_test_split(X2,y,test_size=0.3,random_state=101)

Feature Importance

用树模型实现对不同特征的重要度进行排序。

rft = RandomForestClassifier(n_estimators=700)
rft.fit(X_train,y_train)
pred = rft.predict(X_test)
print(confusion_matrix(y_test,pred))
print(classification_report(y_test,pred))

输出为

[[1274    0]
 [   0 1164]]
              precision    recall  f1-score   support

           0       1.00      1.00      1.00      1274
           1       1.00      1.00      1.00      1164

    accuracy                           1.00      2438
   macro avg       1.00      1.00      1.00      2438
weighted avg       1.00      1.00      1.00      2438

作出特征重要图

feat_importances = pd.Series(rft.feature_importances_, index= X.columns)
feat_importances.nlargest(7).plot(kind='barh')
plt.show()

【特征工程】特征选择Feature Selection_第3张图片

Recursive Feature Elimination (RFE)

RFE将机器学习模型的实例以及要使用的最终所需特征数量作为输入。 然后,它通过使用机器学习模型的准确性作为度量来对特征进行排名,从而递归地减少了要使用的特征数量。

你可能感兴趣的:(基础,特征处理,数据分析)