python - “DBSCAN”对象没有使用 GridSearchCV 和管道的属性“预测”
问题描述
我正在使用scikit-learn库并从中构建管道。
这是我构建的管道的最后(也是主要)部分:
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”而不是“predict”。我不想改变我的布局(比如从 GridSearchCV 找到最佳管道),因为我有更多的参数和算法要比较。
解决方案
我遇到了同样的问题AgglomerativeClustering
并解决了这个问题,我像这样使用 Wrapper:
class AgglomerativeClusteringWrapper(AgglomerativeClustering):
def predict(self,X):
return self.labels_.astype(int)
因此,您可以更改为 DBSCAN,一切都会正常工作。
推荐阅读
- asp.net-mvc-5 - ScriptBundle 说对象引用未设置为对象的实例
- python - 用文本文件中的相应行替换列表列表中的数字
- selenium - 错误:UnsupportedOperationError:在桥接模式下不支持相对于视口的指针移动
- spring - 如何使用 Apche Camel 向 WebSphere MQ 发送消息并从 MQ 队列接收消息
- javascript - 如何将 AJAX 中的 JSON 文件与 Django 链接?
- c# - 区分可选参数和强制参数
- android - 遥控设备的 HID 描述符
- javascript - 访问控制允许来源失败(在某些情况下)
- airflow - 触发 DAG 后如何调度 DAG 任务?
- visual-studio-code - 如何删除我的控制台 VS 代码上的颜色?