比较 BIRCH 和 MiniBatchKMeans

Beginner

This tutorial is from open-source community. Access the source code

简介

本实验在一个合成数据集上比较了两种聚类算法 BIRCH 和 MiniBatchKMeans 的运行时间。这两种算法都具有可扩展性,能够高效地对大型数据集进行聚类。该合成数据集有 25,000 个样本以及使用 make_blobs 生成的两个特征。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到笔记本标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。

导入库

第一步是导入所需的库。我们将导入以下库:

  • numpy
  • matplotlib
  • sklearn
from joblib import cpu_count
from itertools import cycle
from time import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors

from sklearn.cluster import Birch, MiniBatchKMeans
from sklearn.datasets import make_blobs

生成数据集

下一步是生成数据集,以便对 MiniBatchKMeans 和 BIRCH 进行比较。我们将使用 matplotlib 默认提供的所有颜色。

## 为数据集生成中心点,使其形成一个 10X10 的网格。
xx = np.linspace(-22, 22, 10)
yy = np.linspace(-22, 22, 10)
xx, yy = np.meshgrid(xx, yy)
n_centers = np.hstack((np.ravel(xx)[:, np.newaxis], np.ravel(yy)[:, np.newaxis]))

## 生成数据集,以便对 MiniBatchKMeans 和 BIRCH 进行比较。
X, y = make_blobs(n_samples=25000, centers=n_centers, random_state=0)

## 使用 matplotlib 默认提供的所有颜色。
colors_ = cycle(colors.cnames.keys())

Birch 模型

第三步是使用 BIRCH 在有无最终聚类步骤的情况下进行聚类计算并绘图。我们将创建两个 Birch 模型,一个不进行全局聚类步骤,另一个进行全局聚类步骤。

## 使用 BIRCH 在有无最终聚类步骤的情况下进行聚类计算并绘图。
birch_models = [
    Birch(threshold=1.7, n_clusters=None),
    Birch(threshold=1.7, n_clusters=100),
]
final_step = ["不进行全局聚类", "进行全局聚类"]

for ind, (birch_model, info) in enumerate(zip(birch_models, final_step)):
    t = time()
    birch_model.fit(X)
    print("BIRCH %s 作为最终步骤耗时 %0.2f 秒" % (info, (time() - t)))

    ## 绘制结果
    labels = birch_model.labels_
    centroids = birch_model.subcluster_centers_
    n_clusters = np.unique(labels).size
    print("聚类数量 : %d" % n_clusters)

    ax = fig.add_subplot(1, 3, ind + 1)
    for this_centroid, k, col in zip(centroids, range(n_clusters), colors_):
        mask = labels == k
        ax.scatter(X[mask, 0], X[mask, 1], c="w", edgecolor=col, marker=".", alpha=0.5)
        if birch_model.n_clusters is None:
            ax.scatter(this_centroid[0], this_centroid[1], marker="+", c="k", s=25)
    ax.set_ylim([-25, 25])
    ax.set_xlim([-25, 25])
    ax.set_autoscaley_on(False)
    ax.set_title("BIRCH %s" % info)

MiniBatchKMeans 模型

第四步是使用 MiniBatchKMeans 进行聚类计算。我们将把模型拟合到我们的数据集上,并打印运行 MiniBatchKMeans 所花费的时间。

## 使用 MiniBatchKMeans 进行聚类计算。
mbk = MiniBatchKMeans(
    init="k-means++",
    n_clusters=100,
    batch_size=256 * cpu_count(),
    n_init=10,
    max_no_improvement=10,
    verbose=0,
    random_state=0,
)
t0 = time()
mbk.fit(X)
t_mini_batch = time() - t0
print("运行 MiniBatchKMeans 花费的时间 %0.2f 秒" % t_mini_batch)
mbk_means_labels_unique = np.unique(mbk.labels_)

ax = fig.add_subplot(1, 3, 3)
for this_centroid, k, col in zip(mbk.cluster_centers_, range(n_clusters), colors_):
    mask = mbk.labels_ == k
    ax.scatter(X[mask, 0], X[mask, 1], marker=".", c="w", edgecolor=col, alpha=0.5)
    ax.scatter(this_centroid[0], this_centroid[1], marker="+", c="k", s=25)
ax.set_xlim([-25, 25])
ax.set_ylim([-25, 25])
ax.set_title("MiniBatchKMeans")
ax.set_autoscaley_on(False)
plt.show()

总结

本实验在一个合成数据集上比较了两种聚类算法(BIRCH 和 MiniBatchKMeans)的运行时间。BIRCH 是一种层次聚类算法,能够高效地对大型数据集进行聚类。MiniBatchKMeans 是 KMeans 算法的一种变体,同样能够高效地对大型数据集进行聚类。两种算法都能在合理的时间内对数据集进行聚类。