【问题标题】:'DBSCAN' object has no attribute 'predict' using GridSearchCV & Pipeline“DBSCAN”对象没有使用 GridSearchCV 和管道的属性“预测”
【发布时间】:2021-10-25 11:01:02
【问题描述】:

我正在使用scikit-learn 库并从中构建pipeline

这是我构建的管道的最后(也是主要)部分:

preprocessor_steps = [('data_transformer', data_transformer),
                      ('reduce_dim', TruncatedSVD())]
preprocessor = Pipeline(steps=preprocessor_steps)

clustering_steps = [('preprocessor', preprocessor),
                    ('cluster', DummyEstimator())]
clustering = Pipeline(steps=clustering_steps)

data_transformer 有 OneHotEncoder、KNNImputer 等步骤。

现在我有GridSearchCV:

param_grid = [{
      'cluster': [KMeans()],
      'cluster__n_clusters': range(1, 11),
      'cluster__init': ['k-means++', 'random']
    },  
    {
      'cluster': [DBSCAN()],
      'cluster__eps': [0.5, 0.7, 1],
    }]

grid_search = GridSearchCV(estimator=clustering, param_grid=param_grid, 
                           scoring='accuracy', verbose=2, n_jobs=1,
                           error_score='raise')
  
grid_search.fit(X_train, y_train)

它适用于KMeans 的所有超参数,但对于DBSCAN 则失败。它给出了一个错误:

AttributeError: 'DBSCAN' object has no attribute 'predict'

我认为这是因为 DBSCAN 有 'fit_predict' 而不是“预测”。我不想改变我的布局(比如从 GridSearchCV 中找到最佳管道),因为我有更多的参数和算法要比较。

【问题讨论】:

    标签: python scikit-learn pipeline dbscan gridsearchcv


    【解决方案1】:

    AgglomerativeClustering 我遇到了同样的问题 为了解决这个问题,我像这样使用 Wrapper:

    class AgglomerativeClusteringWrapper(AgglomerativeClustering):
        def predict(self,X):
          return self.labels_.astype(int)
    

    因此您可以更改为 DBSCAN,一切都会正常工作。

    【讨论】:

      猜你喜欢
      • 2020-01-31
      • 2020-07-02
      • 2016-03-15
      • 2020-07-02
      • 2017-05-22
      • 2020-10-27
      • 1970-01-01
      • 2019-10-05
      • 2021-04-15
      相关资源
      最近更新 更多