自动化特征选择

⭐在添加新特征或处理一般的的高维数据集,最好将特征的数量减少到只包含最有用的那些特征,并删除其余特征
然而,如何判断每个特征的作用呢?
三种基本的策略:
1、单变量统计
2、基于模型的选择
3、迭代选择

这些都是监督方法,需要划分测试集和训练集,并旨在训练集上拟合特征选择

1、单变量统计

⭐我们计算每个特征和目标值之间的关系是否存在统计显著性,并选择最高置信度的特征。

  • 只单独考虑每个特征
  • 若一个特征需与其他特征结合才具有信息量,则该特征会被舍弃
  • 速度很快

sklearn中使用单变量特征选择:
1、选择一项测试:f_classif/f_regresion
2、确定p值,选择一种舍弃特征的方法(舍弃p值过大的特征)

  • SelectBest选择固定数量的k个特征 SelectPercentile选择固定百分比的特征

    #cancer数据集,并添加没有信息量的噪声特征
    
    from sklearn.datasets import load_breast_cancer
    from sklearn.model_selection import train_test_split
    from sklearn.feature_selection import SelectKBest
    from sklearn.feature_selection import SelectPercentile
    
    import numpy as np
    
    cancer = load_breast_cancer()
    #获得确定的随机数
    rng = np.random.RandomState(42)
    noise = rng.normal(size=(len(cancer.data),50))
    
    #向数据中添加特征
    #前30个来自数据集,后50个是噪声
    X_w_noise = np.hstack([cancer.data,noise])
    
    X_train, X_test, y_train, y_test = train_test_split(X_w_noise,cancer.target,random_state=0,test_size=.5)
    
    #使用f_classif和SelectPercentile(percentile=50)
    select = SelectPercentile(percentile=50)
    select.fit(X_train,y_train)
    
    #对训练集进行变换
    X_train_selected = select.transform(X_train)
    
    print("X_train.shape:{}".format(X_train.shape))
    print("X_train_selected.shape:{}".format(X_train_selected.shape))
    
    
    '''
    ```
    X_train.shape:(284, 80)
    X_train_selected.shape:(284, 40)
    ```
    '''
    
    
    from matplotlib import pyplot as plt
    
    #用get_support方法查看哪些特征被选中
    mask = select.get_support()
    print(mask)
    
    #将mask可视化:黑色为ture,白色为False
    plt.matshow(mask.reshape(1,-1),cmap='gray_r')
    plt.xlabel("sample index")
    
    '''
    ```
    [ True  True  True  True  True  True  True  True  True False  True False
      True  True  True  True  True  True False False  True  True  True  True
      True  True  True  True  True  True False False False  True False  True
     False False  True False False False False  True False False  True False
     False  True False  True False False False False False False  True False
      True False False False False  True False  True False False False False
      True  True False  True False False False False]
    
    
    ```
    '''
    

📣
大多数原始特征被选择(前30个),少部分噪音被选择(后50)

  #使用LogisticRegression比较所有特征上的性能,与仅使用所选特征的性能

  from sklearn.linear_model import LogisticRegression

  #对测试数据进行变换
  X_test_selected = select.transform(X_test)

  lr = LogisticRegression().fit(X_train,y_train)
  print("Score with all features:{:.3}".format(lr.score(X_test,y_test)))

  lr = LogisticRegression().fit(X_train_selected,y_train)
  print("Score with selected features:{:.3}".format(lr.score(X_test_selected,y_test)))


  '''
  ```
  Score with all features:0.919
  Score with selected features:0.909
  ```
  '''

2、基于模型的特征选择

⭐使用一个监督机器学习模型来判断每个特征的重要性,并且保留最重要的特征

  • 特征选择模型为每个特征提供某种重要性度量,用这个度量可以对特征进行排序
  • 考虑所有特征
  • 使用SelecteFromModel

比如:基于决策树的模型提供了feature_importances_属性
线性模型学到的是稀疏系数

  from sklearn.feature_selection import SelectFromModel
  from sklearn.ensemble import RandomForestClassifier 

  select = SelectFromModel(RandomForestClassifier(n_estimators=100,random_state=42),threshold='median')

  #SelectFromModel类选出重要性度量(由监督模型提供)大于给定阈值的所有特征

  #拟合模型
  select.fit(X_train,y_train)

  X_train_l1 = select.transform(X_train)
  print("X_train.shape:{}".format(X_train.shape))
  print("X_train_l1.shape:{}".format(X_train_l1.shape))

  '''
  ```
  X_train.shape:(284, 80)
  X_train_l1.shape:(284, 40)
  ```
  '''

  #查看选中的特征

  mask = select.get_support()
  plt.matshow(mask.reshape(1,-1),cmap='gray_r')
  plt.xlabel("Sample index")

3、 迭代特征选择

⭐将会构建一系列模型,每个模型使用不同数量的特征

⭐有两种基本方法:

  • 开始时没有特征,然后逐个添加特征,直到满足某个终止条件
  • 或者从所有特征开始,然后逐个删除特征,直到满足某个终止条件

计算成本高

  #递归特征消除
  from sklearn.feature_selection import RFE
  select = RFE(RandomForestClassifier(n_estimators=100,random_state=42),n_features_to_select=40)
  select.fit(X_train,y_train)
  #将选中的特征可视化
  mask = select.get_support()
  plt.matshow(mask.reshape(1,-1),cmap='gray_r')
  plt.xlabel("Sample index")

  #使用RFE做特征选择时Logistic回归模型的精度

  X_train_rfe = select.transform(X_train)
  X_test_rfe = select.transform(X_test)

  score = LogisticRegression().fit(X_train_rfe,y_train).score(X_test_rfe,y_test)
  print("Test socre:{:.2f}".format(score))

  '''
  `Test socre:0.93`
  '''

📣
如果不确定何时选用哪些特征作为机器学习算法的输入,那么自动化特征选择可能特别有用

4、参考文献

《python机器学习基础教程》

posted @ 2022-05-21 17:53  朝南烟  阅读(154)  评论(0编辑  收藏  举报
body { color: #000; background-color: #e6e6e6; font-family: "Helvetica Neue",Helvetica,Verdana,Arial,sans-serif; font-size: 12px; min-height: 101%; background: url(https://images.cnblogs.com/cnblogs_com/caolanying/1841633/o_2009041…ly1geq8oc9owbj21hc0u0th5.jpg) fixed; } #home { margin: 0 auto; opacity: 0.8; width: 65%; min-width: 1080px; background-color: #fff; padding: 30px; margin-top: 50px; margin-bottom: 50px; box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3); }