【问题标题】:sklearn GridSearchCV, SelectKBest, and SVMsklearn GridSearchCV、SelectKBest 和 SVM
【发布时间】:2016-05-11 23:12:10
【问题描述】:

我正在尝试通过我编写的 golub 函数创建一个使用特征选择的分类器,它根据 SelectKBest 的要求返回两个 np 数组。我想将其链接到具有线性和的 SVM 分类器,并优化 k 和 C 的可能组合。但是,到目前为止我所尝试的都没有成功,我不知道为什么。代码如下:

 import numpy as np
 from sklearn import cross_validation
 from sklearn import svm
 from sklearn.feature_selection import SelectKBest
 from sklearn.pipeline import make_pipeline, Pipeline
 from sklearn.grid_search import GridSearchCV
 from golub_mod import golub

 class SVM_golub_linear:
    def __init__(self,X,y):
       self.X=X
       self.y=y


   def Golub_SVM(self):
       X=self.X
       y=self.y
       kbest=SelectKBest(golub,k=1)
       k_vals=np.linspace(100,1000,10,dtype=int)
       k_vals=k_vals.tolist()
       c_vals=[0.00001,0.0001,0.001,0.01,.1,1,10,100,1000]

       clf=svm.LinearSVC(penalty='l2')
       steps=[('feature_selection',kbest),('svm_linear',clf)]
       pipeline=make_pipeline(steps)
       params=dict(feature_selection__k=k_vals,
       svm_linear__C=c_vals)
       best_model=GridSearchCV(pipeline,param_grid=params)
       self.model=best_model.fit(X,y)
       print(best_mod.best_params_)

   def svmpredict(self,X_n):
       y_vals=self.model.predict(X_n)
       return y_vals

当我尝试运行它时:

   model=SVM_golub_linear(X,y)
   model.Golub_SVM()

我收到以下错误:

 TypeError: Last step of chain should implement fit    '[('feature_selection',
  SelectKBest(k=1, score_func=<function golub at 0x105f2c398>)), ('svm_linear', LinearSVC(C=1.0, class_weight=None, dual=False, fit_intercept=True,
 intercept_scaling=1, loss='squared_hinge', max_iter=1000,
 multi_class='ovr', penalty='l2', random_state=None, tol=0.0001,
 verbose=0))]' (type <type 'list'>) doesn't)

我不明白这一点,因为 LinearSVC 确实有一个 fit 方法。谢谢

【问题讨论】:

    标签: scikit-learn svm


    【解决方案1】:

    如果你在上面的代码中替换

        pipeline=make_pipeline(steps)
    

        pipeline=Pipeline(steps)
    

    代码按原样工作。

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 2017-04-21
      • 2015-07-04
      • 2018-08-11
      • 2018-04-16
      • 2014-01-29
      • 2020-05-14
      • 2015-04-25
      相关资源
      最近更新 更多