sklearn特征选择类库使用小结

在建立机器模型时,并不是所有属性对模型有同等贡献的,也不是属性越多,模型也好,因此要从众多属性中选择对模型输出及预测结果贡献最大的特征变量,这个过程就叫特征选择,特征选择的作用:消除无关变量,较少训练数据,节省了训练时间,同时提供了模型准确率,也可以缓解过拟合问题。

sklearn.feature_selection模块实现了特征选择算法,目前主要包括:单变量特征选择和递归特征消除。该模块的类主要用于特征选择或样本集上降维,提高算法的准确率或者提升在高位数据集上表现

①sklearn.feature_selection.VarianceThreshold(threshold=0.0):通过特征的方差来提取特征,默认方差为0的特征会自动删除

  • 默认删除方差为0的特征
[python]  view plain  copy
  1. In [1]: from sklearn.feature_selection import VarianceThreshold  
  2.    ...: X = [[0203], [0143], [0113]]  
  3.    ...: selector = VarianceThreshold()#默认threshold=0.0  
  4.    ...: selector.fit_transform(X)  
  5.    ...:  
  6. Out[1]:  
  7. array([[20],  
  8.        [14],  
  9.        [11]])  
  • 指定方差阈值(threshold)参数:表示只提取特征方差大于阈值的特征
[python]  view plain  copy
  1. In [6]: from sklearn.feature_selection import VarianceThreshold  
  2.    ...: X = [[0203], [0143], [0116]]  
  3.    ...: selector = VarianceThreshold(threshold=2)  
  4.    ...: selector.fit_transform(X)  
  5.    ...:  
  6. Out[6]:  
  7. array([[0],  
  8.        [4],  
  9.        [1]])  
  10.   
  11. In [7]: selector.variances_  
  12. Out[7]: array([ 0.        ,  0.22222222,  2.88888889,  2.        ])  
  • 通过variances_属性查看样本各个特征的方差
[python]  view plain  copy
  1. In [2]: selector.variances_  
  2. Out[2]: array([ 0.        ,  0.22222222,  2.88888889,  0.        ])  
  • fit(X, y=None):从特征向量X中学习方差,返回sklearn.feature_selection.variance_threshold.VarianceThreshold对象,y参数只是为了兼容sklearn.pipeline.Pipeline
[python]  view plain  copy
  1. In [8]: from sklearn.feature_selection import VarianceThreshold  
  2.    ...: X = [[0203], [0143], [0116]]  
  3.    ...: st = VarianceThreshold(threshold=2)  
  4.    ...: st.fit(X)  
  5.    ...: print(type(st.fit(X)))  
  6.    ...: st.variances_  
  7.    ...:  
  8. <class 'sklearn.feature_selection.variance_threshold.VarianceThreshold'>  
  9. Out[8]: array([ 0.        ,  0.22222222,  2.88888889,  2.        ])  
  • fit_transform(X, y=None, **fit_params):返回提取特征转换后的数组
[python]  view plain  copy
  1. In [9]: selector.fit_transform(X)  
  2. Out[9]:  
  3. array([[0],  
  4.        [4],  
  5.        [1]])  
  • get_params(deep=True):获取估计器参数,以字典形式返回
[python]  view plain  copy
  1. In [10]: selector.get_params(deep=True)  
  2. Out[10]: {'threshold'2}  
  • get_support(indices=False):若indices参数为False,返回所有特征的布尔数组,满足条件的特征列为True,不满足的特征列为False;若indices为True,则满足条件的特征列对应的整数组成的数组
[python]  view plain  copy
  1. In [11]: selector.get_support(False)  
  2. Out[11]: array([FalseFalse,  TrueFalse], dtype=bool)  
  3.   
  4. In [12]: selector.get_support(True)  
  5. Out[12]: array([2], dtype=int64)  
  • inverse_transform(X):返回X剔除的特征列值用0替换的数组
[python]  view plain  copy
  1. In [13]: selector.inverse_transform(selector.fit_transform(X))  
  2. Out[13]:  
  3. array([[0000],  
  4.        [0040],  
  5.        [0010]])  
  • set_params(**params):设置估计器参数
[python]  view plain  copy
  1. In [14]: selector.set_params(threshold=1)  
  2. Out[14]: VarianceThreshold(threshold=1)  
  • transform(X):数据转换
[python]  view plain  copy
  1. In [15]: X2= [[0203], [0143], [0113]]  
  2.     ...: selector.transform(X2)  
  3.     ...:  
  4. Out[15]:  
  5. array([[03],  
  6.        [43],  
  7.        [13]])  

②sklearn.feature_selection.GenericUnivariateSelect(score_func=<function f_classif>, mode=’percentile’,param=1e-05):可以设置不同的策略来进行单变量特征选择,也可以同时超参数调优选择最佳单变量选择策略

参数说明:

score_func:回调函数,函数接受X和y两个数组,返回(scores, pvalues)元组数组

mode:特征选择模式,可选项:‘percentile’, ‘k_best’, ‘fpr’, ‘fdr’, ‘fwe’

[python]  view plain  copy
  1. In [1]: from sklearn.datasets import load_iris  
  2.    ...: from sklearn.feature_selection import chi2  
  3.    ...: from sklearn.feature_selection import GenericUnivariateSelect  
  4.    ...: iris = load_iris()  
  5.    ...: X,y = iris.data , iris.target  
  6.    ...: s = GenericUnivariateSelect(score_func =chi2, mode='k_best',param=2)  
  7.    ...: s.fit_transform(X,y)  
  8.    ...:  
  9. Out[1]:  
  10. array([[ 1.4,  0.2],  
  11.        [ 1.4,  0.2],  
  12.        [ 1.3,  0.2],  
  13.        [ 1.5,  0.2],  
  14.        [ 1.4,  0.2],  
  15.        [ 1.7,  0.4],  
  16.         .....         
  17.        [ 5.4,  2.3],  
  18.        [ 5.1,  1.8]])  
scores_属性:查看各个特征的score
[python]  view plain  copy
  1. In [2]: s.scores_  
  2. Out[2]: array([  10.81782088,    3.59449902,  116.16984746,   67.24482759])  
pvalues_属性:查看各特征P值
[python]  view plain  copy
  1. In [3]: s.pvalues_  
  2. Out[3]:  
  3. array([  4.47651499e-03,   1.65754167e-01,   5.94344354e-26,  
  4.          2.50017968e-15])  

③sklearn.feature_selection.SelectKBest(score_func=<function f_classif>, k=10):scores按升序排序,选择排前k名所对应的特征

参数说明:k取整数或all

属性值:

[python]  view plain  copy
  1. In [1]: from sklearn.datasets import load_iris  
  2.    ...: from sklearn.feature_selection import SelectKBest,chi2  
  3.    ...: iris = load_iris()  
  4.    ...: X,y  = iris.data,iris.target  
  5.    ...: s = SelectKBest(chi2, k='all').fit(X,y)  
  6.    ...:  
  7.   
  8. In [2]: s.scores_  
  9. Out[2]: array([  10.81782088,    3.59449902,  116.16984746,   67.24482759])  
  10.   
  11. In [3]: s.pvalues_  
  12. Out[3]:  
  13. array([  4.47651499e-03,   1.65754167e-01,   5.94344354e-26,  
  14.          2.50017968e-15])  
  15.   
  16. In [4]: sk =SelectKBest(chi2, k=2).fit(X,y)  
  17.   
  18. In [5]: sk.scores_  
  19. Out[5]: array([  10.81782088,    3.59449902,  116.16984746,   67.24482759])  
  20.   
  21. In [6]: sk.pvalues_  
  22. Out[6]:  
  23. array([  4.47651499e-03,   1.65754167e-01,   5.94344354e-26,  
  24.          2.50017968e-15])  

方法:
  • fit_transform(X, y=None, **fit_params):训练和转换数据
[python]  view plain  copy
  1. In [7]: sk.fit_transform(X,y)  
  2. Out[7]:  
  3. array([[ 1.4,  0.2],  
  4.        [ 1.4,  0.2],  
  5.        [ 1.3,  0.2],  
  6.       ...  
  7.        [ 5.2,  2. ],  
  8.        [ 5.4,  2.3],  
  9.        [ 5.1,  1.8]])  
  • get_support(indices=False):indices=False返回布尔数组,选择的特征列为True,未选择的特征列为False;indices=True返回选择特征列的整数索引
[python]  view plain  copy
  1. In [8]: sk.get_support(indices=False)  
  2. Out[8]: array([FalseFalse,  True,  True], dtype=bool)  
  3.   
  4. In [9]: sk.get_support(indices=True)  
  5. Out[9]: array([23], dtype=int64)  
  • inverse_transform(X):返回和原X大小相同的数组,未选择的特征用0替换
[python]  view plain  copy
  1. In [11]: sk.inverse_transform(sk.fit_transform(X,y))  
  2. Out[11]:  
  3. array([[ 0. ,  0. ,  1.4,  0.2],  
  4.        [ 0. ,  0. ,  1.4,  0.2],  
  5.        [ 0. ,  0. ,  1.3,  0.2],  
  6.        [ 0. ,  0. ,  1.5,  0.2],  
  7.        ....  
  8.        [ 0. ,  0. ,  5.4,  2.3],  
  9.        [ 0. ,  0. ,  5.1,  1.8]])  
  • transform(X):返回X降维到所选的特征上数组

[python]  view plain  copy
  1. In [3]: sk.transform(X)  
  2. Out[3]:  
  3. array([[ 1.4,  0.2],  
  4.        [ 1.4,  0.2],  
  5.        [ 1.3,  0.2],  
  6.        [ 1.5,  0.2],  
  7.       ...  
  8.        [ 5.4,  2.3],  
  9.        [ 5.1,  1.8]])  
④sklearn.feature_selection.SelectPercentile(score_func=<function f_classif>, percentile=10):scores按升序排序,选择排前百分percentile所对应的特征

[python]  view plain  copy
  1. In [1]: from sklearn.datasets import load_iris  
  2.    ...: from sklearn.feature_selection import SelectPercentile,chi2  
  3.    ...: iris = load_iris()  
  4.    ...: X, y = iris.data, iris.target  
  5.    ...: sp=SelectPercentile(chi2, percentile=33).fit(X,y)  
  6.    ...: print(sp.scores_)  
  7.    ...: X_new = sp.fit_transform(X,y)  
  8.    ...: X_new[:10]  
  9.    ...:  
  10. [  10.81782088    3.59449902  116.16984746   67.24482759]  
  11. Out[1]:  
  12. array([[ 1.4],  
  13.        [ 1.4],  
  14.        [ 1.3],  
  15.        [ 1.5],  
  16.        [ 1.4],  
  17.        [ 1.7],  
  18.        [ 1.4],  
  19.        [ 1.5],  
  20.        [ 1.4],  
  21.        [ 1.5]])  
  22.   
  23. In [2]: from sklearn.datasets import load_iris  
  24.    ...: from sklearn.feature_selection import SelectPercentile,chi2  
  25.    ...: iris = load_iris()  
  26.    ...: X, y = iris.data, iris.target  
  27.    ...: sp=SelectPercentile(chi2, percentile=34).fit(X,y)  
  28.    ...: print(sp.scores_)  
  29.    ...: X_new = sp.fit_transform(X,y)  
  30.    ...: X_new[:10]  
  31.    ...:  
  32. [  10.81782088    3.59449902  116.16984746   67.24482759]  
  33. Out[2]:  
  34. array([[ 1.4,  0.2],  
  35.        [ 1.4,  0.2],  
  36.        [ 1.3,  0.2],  
  37.        [ 1.5,  0.2],  
  38.        [ 1.4,  0.2],  
  39.        [ 1.7,  0.4],  
  40.        [ 1.4,  0.3],  
  41.        [ 1.5,  0.2],  
  42.        [ 1.4,  0.2],  
  43.        [ 1.5,  0.1]])  
没明白上述percentile=33时,只选择一个特征,而percentile=34时,选择了两个特征,该比例值时如何计算的? -----遗留问题

⑤sklearn.feature_selection.SelectFpr(score_func=<function f_classif>, alpha=0.05):alpha默认值为0.05,过滤掉特征的pvalues_高于指定alpha的特征

[python]  view plain  copy
  1. In [3]: from sklearn.datasets import load_iris  
  2.    ...: from sklearn.feature_selection import SelectFpr,chi2  
  3.    ...: iris = load_iris()  
  4.    ...: X, y = iris.data, iris.target  
  5.    ...: sp=SelectFpr(chi2, alpha=0.05).fit(X,y)  
  6.    ...:  
  7.   
  8. In [4]: sp.pvalues_  
  9. Out[4]:  
  10. array([  4.47651499e-03,   1.65754167e-01,   5.94344354e-26,  
  11.          2.50017968e-15])  
  12.   
  13. In [5]: sp.get_support(indices=True)  
  14. Out[5]: array([023], dtype=int64)  
⑥sklearn.feature_selection.SelectFdr(score_func=<function f_classif>, alpha=0.05),同SelectFpr类似

[python]  view plain  copy
  1. In [6]: from sklearn.datasets import load_iris  
  2.    ...: from sklearn.feature_selection import SelectFdr,chi2  
  3.    ...: iris = load_iris()  
  4.    ...: X, y = iris.data, iris.target  
  5.    ...: sp=SelectFdr(chi2, alpha=0.004).fit(X,y)  
  6.    ...:  
  7.   
  8. In [7]: sp.pvalues_  
  9. Out[7]:  
  10. array([  4.47651499e-03,   1.65754167e-01,   5.94344354e-26,  
  11.          2.50017968e-15])  
  12.   
  13. In [8]: sp.get_support(indices=True)  
  14. Out[8]: array([23], dtype=int64)  

猜你喜欢

转载自blog.csdn.net/weixin_41988628/article/details/80396361