使用DBSCAN进行聚类:如果事先不设定聚类数量,如何训练模型?

我正在使用sklearn内置的数据集iris进行聚类。在使用KMeans时,我会提前设定聚类数量,但在DBSCAN中并非如此。如果事先不设定聚类数量,如何训练模型呢?

我尝试了以下方法:

import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns#%matplotib inlinefrom sklearn.cluster import DBSCAN,MeanShiftfrom sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_split,KFold,cross_val_scorefrom sklearn.metrics import accuracy_score,confusion_matrixiris = load_iris()X = iris.datay = iris.targetdbscan = DBSCAN(eps=0.3,min_samples=10)dbscan.fit(X,y)

我在这上面卡住了!


回答:

DBSCAN是一种聚类算法,因此它不使用标签y。确实,你可以使用它的fit方法,如.fit(X, y),但根据文档所述:

y: 被忽略

未使用,此处仅为API一致性而保留。

DBSCAN的另一个特点是,与KMeans等算法不同,它不以聚类数量作为输入;相反,它会自行估计聚类数量。

明白了这一点后,让我们使用iris数据集来调整文档示例

结果如下:

Estimated number of clusters: 2Estimated number of noise points: 17Homogeneity: 0.560Completeness: 0.657V-measure: 0.604Adjusted Rand Index: 0.521Adjusted Mutual Information: 0.599Silhouette Coefficient: 0.486

让我们绘制一下结果:

# Plot resultimport matplotlib.pyplot as plt# Black removed and is used for noise instead.unique_labels = set(labels)colors = [plt.cm.Spectral(each)          for each in np.linspace(0, 1, len(unique_labels))]for k, col in zip(unique_labels, colors):    if k == -1:        # Black used for noise.        col = [0, 0, 0, 1]    class_member_mask = (labels == k)    xy = X[class_member_mask & core_samples_mask]    plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),             markeredgecolor='k', markersize=14)    xy = X[class_member_mask & ~core_samples_mask]    plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),             markeredgecolor='k', markersize=6)plt.title('Estimated number of clusters: %d' % n_clusters_)plt.show()

enter image description here

就这样了。

与所有聚类算法一样,这里的监督学习常规概念,如训练/测试分割、预测未见数据、交叉验证等不适用。这种无监督方法可能在初步的探索性数据分析(EDA)中很有用,以帮助我们对数据有一个总体了解——但正如你可能已经注意到的那样,这样的分析结果不一定对监督问题有用:在这里,尽管我们的iris数据集中存在3个标签,算法仅发现了2个聚类。

…当然,这可能会根据模型参数的不同而改变。继续实验吧…

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注