【问题标题】:scikit-learn: Get selected features for prediction datascikit-learn:获取预测数据的选定特征
【发布时间】:2015-03-19 19:47:09
【问题描述】:

我有一组训练数据。用于创建模型的 python 脚本还将属性计算为一个 numpy 数组(它是一个位向量)。然后我想使用VarianceThreshold 来消除所有方差为 0 的特征(例如,全为 0 或 1)。然后我运行get_support(indices=True) 来获取选择列的索引。

我现在的问题是如何仅获取我想要预测的数据的选定特征。我首先计算所有特征,然后使用数组索引,但它不起作用:

x_predict_all = getAllFeatures(suppl_predict)
x_predict = x_predict_all[indices] #only selected features

indices 是一个 numpy 数组。

返回的数组 x_predict 具有正确的长度 len(x_predict) 但形状错误 x_predict.shape[1] 仍然是原始长度。然后我的分类器由于形状错误而引发错误

prediction = gbc.predict(x_predict)

  File "C:\Python27\lib\site-packages\sklearn\ensemble\gradient_boosting.py", li
ne 1032, in _init_decision_function
    self.n_features, X.shape[1]))
ValueError: X.shape[1] should be 1855, not 2090.

我该如何解决这个问题?

【问题讨论】:

    标签: scikit-learn feature-selection


    【解决方案1】:

    你可以这样做:

    测试数据

    from sklearn.feature_selection import VarianceThreshold
    
    X = np.array([[0, 2, 0, 3], 
                  [0, 1, 4, 3],  
                  [0, 1, 1, 3]])
    selector = VarianceThreshold()
    

    备选方案 1

    >>> selector.fit(X)
    >>> idxs = selector.get_support(indices=True)
    >>> X[:, idxs]
    array([[2, 0],
           [1, 4],
           [1, 1]])
    

    备选方案 2

    >>> selector.fit_transform(X)
    array([[2, 0],
           [1, 4],
           [1, 1]])
    

    【讨论】:

      猜你喜欢
      • 2015-01-12
      • 2018-09-07
      • 2018-02-24
      • 2013-03-07
      • 2022-07-19
      • 2018-01-01
      • 2018-06-01
      • 2014-05-22
      • 2016-02-25
      相关资源
      最近更新 更多