pipelin中SelectKBest方法的问题

2024-04-19 22:35:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解决一个问题,我用KNN算法进行分类。在使用pipeline时,我决定添加SelectKBest,但出现以下错误:

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

我不知道我是否可以用KNN的这个选择算法。但我也尝试了支持向量机,得到了相同的结果。这是我的密码:

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)

Tags: and算法pipelineparameterstep分类traingrid
2条回答

所以,我不认为管道的顺序很重要,但是后来,我发现管道的最后一个成员必须能够适应/转换。我改变了管道的顺序,使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作为管道的最后一个元素:

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

它不是一个估计器(它是一个转换器),以及你的中间步骤kn不是一个转换器。你知道吗

我猜在你安装了模型之后,你不会真的想进行特征选择。。。你知道吗

更改为:

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

你应该没事的。你知道吗

相关问题 更多 >