【问题标题】:While doing feature selection using selectKbest, can we use the same code for the training and testing set? Will it give the same features?在使用 selectKbest 进行特征选择时,我们可以对训练集和测试集使用相同的代码吗?它会提供相同的功能吗?
【发布时间】:2021-12-07 19:44:30
【问题描述】:
x_tr = SelectKBest(chi2, k=25).fit_transform(x_tr,y_tr)
x_ts = SelectKBest(chi2, k=25).fit_transform(x_ts, y_ts)
这是我的代码。我担心它会为训练和测试数据选择不同的特征。我应该更改代码还是提供相同的功能?
【问题讨论】:
标签:
python
machine-learning
testing
scikit-learn
feature-selection
【解决方案1】:
简答:你会获得不同的功能(除非你很幸运)。
为什么?基本上,因为您从不同的数据中获取信息:
x_tr = SelectKBest(chi2, k=25).fit_transform(x_tr,y_tr)
x_ts = SelectKBest(chi2, k=25).fit_transform(x_ts, y_ts)
在第一行中,您从x_tr 和y_tr 获得特征;在第二行中,您从x_ts 和y_ts 获得特征。因此,您获得的输出不同是有道理的。综上所述,如果输入不同,输出也很有可能不同。
您获得相同特征的唯一情况是训练和测试数据超级同质并且它们隐藏完全相同的信息。在您的情况下,您需要 25 个特征,而在每个代码中获得完全相同的 25 个特征将非常困难。
如果您想应用转换,请使用以下代码:
select = SelectKBest(score_func=chi2, k=25) #We define the model by using SelectKBest class
x_tr_selected = select.fit_transform(x_tr ,y_tr) #We fit the class using x_tr and y_tr. And we transform x_tr
x_ts_selected = select.transform(x_ts) #We only transform the data x_ts with the information we obtain in the previous fit
【解决方案2】:
要获得相同的特征,您必须适应训练数据,然后转换训练和测试数据。
select = SelectKBest(chi2, k=25).fit(x_tr, y_tr)
X_train_new = select.transform(x_tr)
X_test_new = select.transform(x_ts)