备注
Go to the end 下载完整的示例代码。或者通过浏览器中的MysterLite或Binder运行此示例
DBSCAN集群算法演示#
DBSCAN(含噪应用程序基于密度的空间集群)在高密度区域中查找核心样本,并从中扩展集群。该算法适合包含相似密度集群的数据。
看到 在玩具数据集上比较不同的聚类算法 2D数据集上不同集群算法的演示示例。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
数据生成#
我们使用 make_blobs
创建3个合成集群。
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
centers = [[1, 1], [-1, -1], [1, -1]]
X, labels_true = make_blobs(
n_samples=750, centers=centers, cluster_std=0.4, random_state=0
)
X = StandardScaler().fit_transform(X)
我们可以将结果数据可视化:
import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1])
plt.show()

计算DBSCAN#
可以访问由指定的标签 DBSCAN
使用 labels_
属性有噪音的样品都有标签 \(-1\) .
import numpy as np
from sklearn import metrics
from sklearn.cluster import DBSCAN
db = DBSCAN(eps=0.3, min_samples=10).fit(X)
labels = db.labels_
# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
n_noise_ = list(labels).count(-1)
print("Estimated number of clusters: %d" % n_clusters_)
print("Estimated number of noise points: %d" % n_noise_)
Estimated number of clusters: 3
Estimated number of noise points: 18
聚类算法基本上是无监督的学习方法。但由于 make_blobs
由于可以访问合成聚类的真实标签,因此可以使用评估度量,该评估度量利用该“监督”地面真实信息来量化所得到的聚类的质量。这种度量的例子是同质性、完整性、V-度量、随机指数、调整后的随机指数和调整后的互信息(AMI)。
如果基础事实标签未知,则只能使用模型结果本身执行评估。在这种情况下,剪影系数就派上了用场。
更多详见 集群绩效评估中的机会调整 示例或第 集群绩效评估 module.
print(f"Homogeneity: {metrics.homogeneity_score(labels_true, labels):.3f}")
print(f"Completeness: {metrics.completeness_score(labels_true, labels):.3f}")
print(f"V-measure: {metrics.v_measure_score(labels_true, labels):.3f}")
print(f"Adjusted Rand Index: {metrics.adjusted_rand_score(labels_true, labels):.3f}")
print(
"Adjusted Mutual Information:"
f" {metrics.adjusted_mutual_info_score(labels_true, labels):.3f}"
)
print(f"Silhouette Coefficient: {metrics.silhouette_score(X, labels):.3f}")
Homogeneity: 0.953
Completeness: 0.883
V-measure: 0.917
Adjusted Rand Index: 0.952
Adjusted Mutual Information: 0.916
Silhouette Coefficient: 0.626
图结果#
核心样本(大点)和非核心样本(小点)根据指定的聚类进行颜色编码。标记为噪声的样本以黑色表示。
unique_labels = set(labels)
core_samples_mask = np.zeros_like(labels, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
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(f"Estimated number of clusters: {n_clusters_}")
plt.show()

Total running time of the script: (0分0.144秒)
相关实例
Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>
_