简介
聚类是一种流行的无监督学习技术,它涉及根据数据点的特征将相似的数据点分组在一起。轮廓系数法是一种常用的技术,用于确定数据集中的最佳聚类数。在本实验中,我们将使用轮廓系数法,通过 KMeans 算法来确定最佳聚类数。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到笔记本标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟,让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
导入库
我们将首先导入执行分析所需的库。
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
生成数据
我们将使用 sklearn.datasets 库中的 make_blobs 函数来生成样本数据。此函数生成用于聚类的各向同性高斯数据点集。
X, y = make_blobs(
n_samples=500,
n_features=2,
centers=4,
cluster_std=1,
center_box=(-10.0, 10.0),
shuffle=True,
random_state=1,
) ## For reproducibility
确定最佳聚类数
我们将使用轮廓系数法来确定 KMeans 算法的最佳聚类数。我们将遍历 n_clusters 的一系列值,并绘制每个值的轮廓系数得分。
range_n_clusters = [2, 3, 4, 5, 6]
for n_clusters in range_n_clusters:
## 创建一个 1 行 2 列的子图
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.set_size_inches(18, 7)
## 第一个子图是轮廓图
ax1.set_xlim([-0.1, 1])
ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10])
## 用 n_clusters 值初始化聚类器,并设置随机生成器种子为 10 以确保可重复性。
clusterer = KMeans(n_clusters=n_clusters, n_init="auto", random_state=10)
cluster_labels = clusterer.fit_predict(X)
## silhouette_score 给出所有样本的平均值。
silhouette_avg = silhouette_score(X, cluster_labels)
## 计算每个样本的轮廓系数得分
sample_silhouette_values = silhouette_samples(X, cluster_labels)
y_lower = 10
for i in range(n_clusters):
## 聚合属于聚类 i 的样本的轮廓系数得分,并对其进行排序
ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = cm.nipy_spectral(float(i) / n_clusters)
ax1.fill_betweenx(
np.arange(y_lower, y_upper),
0,
ith_cluster_silhouette_values,
facecolor=color,
edgecolor=color,
alpha=0.7,
)
## 在轮廓图的中间用聚类编号标记
ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
## 计算下一个图的新 y_lower
y_lower = y_upper + 10 ## 10 用于 0 个样本
ax1.set_title("The silhouette plot for the various clusters.")
ax1.set_xlabel("The silhouette coefficient values")
ax1.set_ylabel("Cluster label")
## 所有值的平均轮廓系数得分的垂直线
ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
ax1.set_yticks([]) ## 清除 y 轴标签/刻度
ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
## 第二个图显示实际形成的聚类
colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)
ax2.scatter(
X[:, 0], X[:, 1], marker=".", s=30, lw=0, alpha=0.7, c=colors, edgecolor="k"
)
## 标记聚类
centers = clusterer.cluster_centers_
## 在聚类中心绘制白色圆圈
ax2.scatter(
centers[:, 0],
centers[:, 1],
marker="o",
c="white",
alpha=1,
s=200,
edgecolor="k",
)
for i, c in enumerate(centers):
ax2.scatter(c[0], c[1], marker="$%d$" % i, alpha=1, s=50, edgecolor="k")
ax2.set_title("The visualization of the clustered data.")
ax2.set_xlabel("Feature space for the 1st feature")
ax2.set_ylabel("Feature space for the 2nd feature")
plt.suptitle(
"Silhouette analysis for KMeans clustering on sample data with n_clusters = %d"
% n_clusters,
fontsize=14,
fontweight="bold",
)
plt.show()
解读结果
我们将解读轮廓系数法的结果。我们会查看每个 n_clusters 值对应的平均轮廓系数得分,并选择得分最高的那个值。
总结
在本实验中,我们使用轮廓系数法来确定 KMeans 算法的最佳聚类数。我们使用 make_blobs 函数生成样本数据,并绘制了一系列 n_clusters 值的轮廓系数得分。我们解读了结果并选择了 n_clusters 的最佳值。