我正在尝试在sklearn中构建GridSearchCV管道以使用KNeighborsClassifier和SVM。到目前为止,已经尝试了以下代码:
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=3)
from sklearn import svm
from sklearn.svm import SVC
clf = SVC(kernel='linear')
pipeline = Pipeline([ ('knn',neigh), ('sVM', clf)]) # Code breaks here
weight_options = ['uniform','distance']
param_knn = {'weights':weight_options}
param_svc = {'kernel':('linear', 'rbf'), 'C':[1,5,10]}
grid = GridSearchCV(pipeline, param_knn, param_svc, cv=5, scoring='accuracy')
但出现以下错误:
TypeError: All intermediate steps should be transformers and implement fit and transform. 'KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
metric_params=None, n_jobs=1, n_neighbors=3, p=2,
weights='uniform')' (type <class 'sklearn.neighbors.classification.KNeighborsClassifier'>) doesn't
谁能帮助我解决我的问题以及如何纠正它?我认为最后一行也有问题,请重新声明。
最佳答案
该错误清楚地表明KNeighborsClassifier没有转换方法KNN仅具有fit方法,而SVM具有fit_transform()方法。对于管道,我们可以向其中传递n个参数。但所有参数都应包含转换器方法。请参考以下链接
http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html
关于python - 使用KNeighborsClassifier的SKlearn管道,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42733254/