1

我在尝试使用特征选择数据集进行预测时遇到的一个问题是,一旦您选择了某些特征,如果您要在测试数据集上进行预测,测试数据集的特征将不会对齐,因为训练数据集会由于特征选择而具有较少的特征。您如何正确实施特征选择,以使测试数据集具有与训练数据集相同的特征?

例子:

 from sklearn.datasets import load_iris
 from sklearn.feature_selection import SelectKBest
 from sklearn.feature_selection import chi2
 iris = load_iris()
 X, y = iris.data, iris.target
 X.shape
(150, 4)
 X_new = SelectKBest(chi2, k=2).fit_transform(X, y)
 X_new.shape
(150, 2)
4

2 回答 2

2

你也必须使用transform你的测试集......并且不要使用fit_transform,而只是transform。这需要你保存你的SelectKBest对象,所以效果如下:

selector = SelectKBest(chi2, k=2)
X_train_clean = selector.fit_transform(X_train, y_train)
X_test_clean = selector.transform(X_test)
于 2017-04-18T18:16:35.473 回答
0

我相信你想通过SelectKBest先拟合然后transform你的测试数据来创建一个 feature_selector 对象。像这样:

feature_selector = SelectKBest(chi2, k=2).fit(X_train, y)
X_train_pruned = feature_selector.transform(X_train)
X_test_pruned = feature_selector.transform(X_test)
于 2017-04-18T18:15:48.140 回答