管道中 SelectKBest 方法的问题

Problem with SelectKBest method in pipeline

我正在尝试解决使用 KNN 算法进行分类的问题。在使用管道时,我决定添加 SelectKBest 但出现以下错误:

All intermediate steps should be transformers and implement fit and transform.

我不知道我是否可以将这种选择算法与 KNN 一起使用。但我也尝试使用 SVM 并得到了相同的结果。这是我的代码:

sel = SelectKBest('chi2',k = 3)
clf = kn()
s = ss()
step = [('scaler', s), ('kn', clf), ('sel',sel)]
pipeline = Pipeline(step)
parameter = {'kn__n_neighbors':range(1,40,1), 'kn__weights':['uniform','distance'], 'kn__p':[1,2] }
kfold = StratifiedKFold(n_splits=5, random_state=0)
grid = GridSearchCV(pipeline, param_grid = parameter, cv=kfold, scoring = 'accuracy', n_jobs = -1)
grid.fit(x_train, y_train)

所以,我认为管道的顺序并不重要,但后来我发现管道的最后一个成员必须能够 fit/transform。我通过将 clf 设置为最后一个来更改管道的顺序。问题已解决。

steps中确定的管道中的操作顺序很重要;来自 docs:

steps : list

List of (name, transform) tuples (implementing fit/transform) that are chained, in the order in which they are chained, with the last object an estimator.

错误是由于将 SelectKBest 添加为管道的 last 元素:

step = [('scaler', s), ('kn', clf), ('sel',sel)]

这不是估算器(它是转换器),以及您的中间步骤 kn 不是转换器。

我猜你真的不想执行特征选择在你拟合模型后...

改为:

step = [('scaler', s), ('sel', sel), ('kn', clf)]

你应该没事的。