Skip to main content
 首页 » 编程设计

python-2.7之使用 scikit-learn 去除低方差特征

2024年12月31日9myhome

scikit-learn 提供了各种移除描述符的方法,下面给出的教程提供了用于此目的的基本方法,

http://scikit-learn.org/stable/modules/feature_selection.html

但是本教程没有提供任何方法或方法可以告诉您保留已删除或保留的功能列表的方式。

下面的代码取自教程。

    from sklearn.feature_selection import VarianceThreshold 
    X = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]] 
    sel = VarianceThreshold(threshold=(.8 * (1 - .8))) 
    sel.fit_transform(X) 
array([[0, 1], 
       [1, 0], 
       [0, 0], 
       [1, 1], 
       [1, 0], 
       [1, 1]]) 

上面给定的示例代码仅描述了两个描述符“shape(6, 2)”,但在我的情况下,我有一个形状为(第 51 行,第 9000 列)的巨大数据框。找到合适的模型后,我想跟踪有用和无用的特征,因为我可以通过只计算有用的特征来节省计算测试数据集特征的计算时间。

例如,当您使用 WEKA 6.0 执行机器学习建模时,它提供了显着的特征选择灵活性,在删除无用特征后,您可以获得丢弃特征和有用特征的列表。

谢谢

请您参考如下方法:

然后,如果我没猜错的话,您可以做的是:

VarianceThreshold 的情况下,您可以调用方法 fit 而不是 fit_transform 。这将拟合数据,结果方差将存储在 vt.variances_ 中(假设 vt 是您的对象)。

有了阈值,您可以像 fit_transform 那样提取转换的特征:

X[:, vt.variances_ > threshold] 

或获取索引为:
idx = np.where(vt.variances_ > threshold)[0] 

或者作为面具
mask = vt.variances_ > threshold 

PS:默认阈值为0

编辑:

更直接的做法是使用 get_support 类的方法 VarianceThreshold 。从文档:
get_support([indices])  Get a mask, or integer index, of the features selected 

您应该在 fitfit_transform 之后调用此方法。