均值漂移聚类算法的演示#

参考

Dorin Comaniciu 和 Peter Meer,“均值漂移:一种面向特征空间分析的鲁棒方法”。IEEE 模式分析与机器智能汇刊。2002 年。第 603-619 页。

import numpy as np

from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets import make_blobs

生成样本数据#

centers = [[1, 1], [-1, -1], [1, -1]]
X, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)

使用均值漂移计算聚类#

# The following bandwidth can be automatically detected using
bandwidth = estimate_bandwidth(X, quantile=0.2, n_samples=500)

ms = MeanShift(bandwidth=bandwidth, bin_seeding=True)
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_

labels_unique = np.unique(labels)
n_clusters_ = len(labels_unique)

print("number of estimated clusters : %d" % n_clusters_)
number of estimated clusters : 3

绘制结果#

import matplotlib.pyplot as plt

plt.figure(1)
plt.clf()

colors = ["#dede00", "#377eb8", "#f781bf"]
markers = ["x", "o", "^"]

for k, col in zip(range(n_clusters_), colors):
    my_members = labels == k
    cluster_center = cluster_centers[k]
    plt.plot(X[my_members, 0], X[my_members, 1], markers[k], color=col)
    plt.plot(
        cluster_center[0],
        cluster_center[1],
        markers[k],
        markerfacecolor=col,
        markeredgecolor="k",
        markersize=14,
    )
plt.title("Estimated number of clusters: %d" % n_clusters_)
plt.show()
Estimated number of clusters: 3

脚本的总运行时间:(0 分钟 0.474 秒)

相关示例

亲和传播聚类算法的演示

亲和传播聚类算法的演示

K-Means 和 MiniBatchKMeans 聚类算法的比较

K-Means 和 MiniBatchKMeans 聚类算法的比较

DBSCAN 聚类算法的演示

DBSCAN 聚类算法的演示

K-Means++ 初始化的示例

K-Means++ 初始化的示例

由 Sphinx-Gallery 生成的图库