八、特征选择

作者:Chris Albon

译者:飞龙

协议:CC BY-NC-SA 4.0

用于特征选取的 ANOVA F 值

如果特征是类别的,计算每个特征与目标向量之间的卡方(八、特征选择 - 图1)统计量。 但是,如果特征是定量的,则计算每个特征与目标向量之间的 ANOVA F 值。

F 值得分检查当我们按照目标向量对数字特征进行分组时,每个组的均值是否显着不同。

  1. # 加载库
  2. from sklearn.datasets import load_iris
  3. from sklearn.feature_selection import SelectKBest
  4. from sklearn.feature_selection import f_classif
  5. # 加载鸢尾花数据
  6. iris = load_iris()
  7. # 创建特征和标签
  8. X = iris.data
  9. y = iris.target
  10. # 创建 SelectKBest 对象来选择两个带有最佳 ANOVA F 值的特征
  11. fvalue_selector = SelectKBest(f_classif, k=2)
  12. # 对 SelectKBest 对象应用特征和标签
  13. X_kbest = fvalue_selector.fit_transform(X, y)
  14. # 展示结果
  15. print('Original number of features:', X.shape[1])
  16. print('Reduced number of features:', X_kbest.shape[1])
  17. '''
  18. Original number of features: 4
  19. Reduced number of features: 2
  20. '''

用于特征选择的卡方

八、特征选择 - 图2

  1. # 加载库
  2. from sklearn.datasets import load_iris
  3. from sklearn.feature_selection import SelectKBest
  4. from sklearn.feature_selection import chi2
  5. # 加载鸢尾花数据
  6. iris = load_iris()
  7. # 创建特征和目标
  8. X = iris.data
  9. y = iris.target
  10. # 通过将数据转换为整数,转换为类别数据
  11. X = X.astype(int)
  12. # 选择两个卡方统计量最高的特征
  13. chi2_selector = SelectKBest(chi2, k=2)
  14. X_kbest = chi2_selector.fit_transform(X, y)
  15. # 展示结果
  16. print('Original number of features:', X.shape[1])
  17. print('Reduced number of features:', X_kbest.shape[1])
  18. '''
  19. Original number of features: 4
  20. Reduced number of features: 2
  21. '''

丢弃高度相关的特征

  1. # 加载库
  2. import pandas as pd
  3. import numpy as np
  4. # 创建特征矩阵,具有两个高度相关特征
  5. X = np.array([[1, 1, 1],
  6. [2, 2, 0],
  7. [3, 3, 1],
  8. [4, 4, 0],
  9. [5, 5, 1],
  10. [6, 6, 0],
  11. [7, 7, 1],
  12. [8, 7, 0],
  13. [9, 7, 1]])
  14. # 将特征矩阵转换为 DataFrame
  15. df = pd.DataFrame(X)
  16. # 查看数据帧
  17. df
012
0111
1220
2331
3440
4551
5660
6771
7870
8971
  1. # 创建相关度矩阵
  2. corr_matrix = df.corr().abs()
  3. # 选择相关度矩阵的上三角
  4. upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
  5. # 寻找相关度大于 0.95 的特征列的索引
  6. to_drop = [column for column in upper.columns if any(upper[column] > 0.95)]
  7. # 丢弃特征
  8. df.drop(df.columns[to_drop], axis=1)
02
011
120
231
340
451
560
671
780
891

递归特征消除

  1. # 加载库
  2. from sklearn.datasets import make_regression
  3. from sklearn.feature_selection import RFECV
  4. from sklearn import datasets, linear_model
  5. import warnings
  6. # 消除烦人但无害的警告
  7. warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd")
  8. # 生成特征矩阵,目标向量和真实相关度
  9. X, y = make_regression(n_samples = 10000,
  10. n_features = 100,
  11. n_informative = 2,
  12. random_state = 1)
  13. # 创建线性回归
  14. ols = linear_model.LinearRegression()
  15. # 创建递归特征消除器,按照 MSE 对特征评分
  16. rfecv = RFECV(estimator=ols, step=1, scoring='neg_mean_squared_error')
  17. # 拟合递归特征消除器
  18. rfecv.fit(X, y)
  19. # 递归特征消除
  20. rfecv.transform(X)
  21. '''
  22. array([[ 0.00850799, 0.7031277 , -1.2416911 , -0.25651883, -0.10738769],
  23. [-1.07500204, 2.56148527, 0.5540926 , -0.72602474, -0.91773159],
  24. [ 1.37940721, -1.77039484, -0.59609275, 0.51485979, -1.17442094],
  25. ...,
  26. [-0.80331656, -1.60648007, 0.37195763, 0.78006511, -0.20756972],
  27. [ 0.39508844, -1.34564911, -0.9639982 , 1.7983361 , -0.61308782],
  28. [-0.55383035, 0.82880112, 0.24597833, -1.71411248, 0.3816852 ]])
  29. '''
  30. # 最佳特征数量
  31. rfecv.n_features_
  32. # 5

方差阈值二元特征

  1. from sklearn.feature_selection import VarianceThreshold
  2. # 创建特征矩阵:
  3. # 特征 0:80% 的类 0
  4. # 特征 1:80% 的类 1
  5. # 特征 2:60% 的类 0,40% 的类 1
  6. X = [[0, 1, 0],
  7. [0, 1, 1],
  8. [0, 1, 0],
  9. [0, 1, 1],
  10. [1, 0, 0]]

在二元特征(即伯努利随机变量)中,方差计算如下:

](/uploads/projects/ds-ai-tech-notes/tex-46277250c0e8d4fadf188d0d22fa1343.gif)

其中 八、特征选择 - 图4 是类 1 观测的比例。 因此,通过设置 八、特征选择 - 图5,我们可以删除绝大多数观察是类 1 的特征。

  1. # Run threshold by variance
  2. thresholder = VarianceThreshold(threshold=(.75 * (1 - .75)))
  3. thresholder.fit_transform(X)
  4. '''
  5. array([[0],
  6. [1],
  7. [0],
  8. [1],
  9. [0]])
  10. '''

用于特征选择的方差阈值

八、特征选择 - 图6

  1. from sklearn import datasets
  2. from sklearn.feature_selection import VarianceThreshold
  3. # 加载鸢尾花数据
  4. iris = datasets.load_iris()
  5. # 创建特征和目标
  6. X = iris.data
  7. y = iris.target
  8. # 使用方差阈值 0.5 创建 VarianceThreshold 对象
  9. thresholder = VarianceThreshold(threshold=.5)
  10. # 应用方差阈值
  11. X_high_variance = thresholder.fit_transform(X)
  12. # 查看方差大于阈值的前五行
  13. X_high_variance[0:5]
  14. '''
  15. array([[ 5.1, 1.4, 0.2],
  16. [ 4.9, 1.4, 0.2],
  17. [ 4.7, 1.3, 0.2],
  18. [ 4.6, 1.5, 0.2],
  19. [ 5\. , 1.4, 0.2]])
  20. '''