我有一组训练数据。用于创建模型的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.
我该如何解决这个问题?
答案 0 :(得分:3)
你可以这样做:
测试数据
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]])