机器学习-KMeans聚类(肘系数Elbow和轮廓系数Silhouette)

本文介绍了KMeans聚类算法的基本原理,包括如何选择初始中心点和迭代过程。针对聚类数量的选择,通过Elbow方法和Silhouette分析来评估模型性能。Elbow方法寻找变形度下降最陡的点,而Silhouette系数衡量样本在群组内的紧密程度和与其他群组的分离程度。结果表明,当设置聚类数量为3时,聚类效果最佳,平均轮廓系数接近0.72,与Elbow方法的结果一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Section I: Brief Introduction on KMeans Cluster

The K-Means algorithm belongs to the category of prototype-based clustering. Prototype-based clustering means that each cluster is represented by a prototype, which can either be the centorid (average) of similar points with continuous features, or the medoid (the most frequently occurring point) in the case of categorical features. While K-Means is very good at identifying clusters with a spherical shape, one of the drawbacks of this clutering algorithm is that the number of clusters need to be specified. An inapproriate choice for cluter number can result in poor clustering performance, so two indexes for model performance, i.e., elbow and silhouette, are useful techniques to evaluate the quality of clutering to determine the optimal number of cluters.
The flowchart of K-Means algorithm can be summarized by the following four steps:

  • Step 1: Randomly pick k centroids from the sample points as initial cluter centers
  • Step 2: Assign each sample to the nearest centroid according to distance difference, and then move the centroids to the center of the samples that were assigned to it
  • Step 3: Repeat steps 2 until the cluster assignments do not change or user-defined tolerance or maximum number of iterations is reached; otherwise, update centroids.

FROM
Sebastian Raschka, Vahid Mirjalili. Python机器学习第二版. 南京:东南大学出版社,2018.

第一部分:基本KMeans聚类算法
代码

from sklearn import datasets

import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")

plt.rcParams['figure.dpi']=200
plt.rcParams['savefig.dpi']=200
font = {
   'weight': 'light'}
plt.rc("font", **font)

#Section 1: Load Blobs from datasets and visualize it
X,y=datasets.make_blobs(n_samples=150,
                        n_features=2,
                        centers=3,
                        cluster_std=0.5,
                        shuffle=True,
                        random_state=0)
plt.scatter(X[:,0],X[:,1],c='white',marker='o',edgecolors='black',s=50)
plt.grid()
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.savefig('./fig1.png')
plt.show()

#Section 2: Use KMeans algorithm to visualize data points and centroids
from sklearn.cluster import KMeans

#Set n_init=10 to run k-means clustering algorithm 10 times independently
#with different centroids to choose the final model with the lowest SSE
km=KMeans(n_clusters=3,
          init='random',
          n_init=10,
          max_iter=300,
          tol=1e-4,
          random_state=0)

y_km=km.fit_predict(X)
plt.scatter(X[y_km==0,0],
            X[y_km==0,1],
            s=50,
            c='lightgreen',
            marker='s',
            edgecolor='black',
            label='Cluster 1')
plt.scatter(X[y_km==1,0],
            X[y_km==1,1],
            s=50,
            c='orange',
            marker='o',
            edgecolor='black',
            label='Cluster 2')
plt.scatter(X[y_km==2,0],
            X[y_km==2,1],
            s=50,
            c='lightblue',
            marker='v',
            edgecolor='black',
            label='Cluster 3')
plt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],
            s=250,
            marker='*',
            c='red',
            edgecolor='black',
            label='Centroids')
plt.xlabel(
<think>好的,用户现在问的是如何根据轮廓系数调整K-Means聚类。我需要先回顾一下轮廓系数的基本概念,然后思考如何用它来优化K值的选择。 首先,轮廓系数是用来评估聚类效果的一个指标,范围在-1到1之间。数值越高表示聚类效果越好。用户可能已经知道K-Means,但可能不清楚如何具体应用轮廓系数来调整聚类数目K。 接下来,我应该分步骤解释:计算不同K值的轮廓系数,选择最佳K值,以及可能的注意事项。需要确保用户能够理解每一步的操作,并且能够实际操作。比如,可能需要给出代码示例,但用户之前的问题中提到了LaTeX格式,所以可能希望有结构化的中文解释,而不是代码。 另外,用户之前的问题是关于字体缺失的警告,现在转向机器学习,可能是在做数据可视化时遇到问题,进而需要优化聚类结果。所以可能需要强调可视化轮廓系数的方法,比如绘制轮廓系数随K值变化的折线图,帮助直观选择最佳K值。 还要考虑用户可能的误区,比如K值的选择不仅仅依赖于轮廓系数,还需要结合业务需求数据分布。此外,轮廓系数在高维数据中可能不太可靠,可能需要提及降维或其他评估指标的结合使用。 需要确保回答结构清晰,步骤明确,可能包括以下几个部分:轮廓系数简介、计算步骤、如何选择K值、实际例子、注意事项等。可能还需要比较不同K值的结果,说明如何分析轮廓系数轮廓图。 最后,检查是否有遗漏的重要点,比如轮廓系数的计算公式,或者如何解释轮廓系数的平均值分布情况。确保用户能够根据指导实际应用该方法调整K-Means聚类。</think>--- ### **根据轮廓系数Silhouette Score)调整 K-Means 聚类的步骤** 轮廓系数是一种评估聚类质量的指标,通过分析样本与其所属簇的紧密度分离度,帮助选择最佳的聚类数($k$)。以下是具体操作方法分析流程: --- #### **1. 轮廓系数简介** - **定义** 对每个样本计算轮廓系数: $$ s(i) = \frac{b(i) - a(i)}{\max\{a(i), b(i)\}} $$ - $a(i)$: 样本 $i$ 到同簇其他样本的平均距离(**簇内紧密度**)。 - $b(i)$: 样本 $i$ 到最近其他簇所有样本的平均距离(**簇间分离度**)。 - $s(i) \in [-1, 1]$,越接近 $1$ 表示聚类效果越好。 - **整体评估** 取所有样本 $s(i)$ 的平均值作为模型的轮廓系数,值越高说明聚类越合理。 --- #### **2. 调整 K-Means 聚类的步骤** ##### **步骤 1:遍历不同 $k$ 值** 尝试不同的聚类数(如 $k=2$ 到 $k=10$),对每个 $k$ 执行以下操作: 1. 用 K-Means 对数据聚类。 2. 计算所有样本的轮廓系数并求均值。 ```python from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score scores = [] for k in range(2, 11): kmeans = KMeans(n_clusters=k, random_state=42) labels = kmeans.fit_predict(X) score = silhouette_score(X, labels) scores.append(score) ``` ##### **步骤 2:选择最佳 $k$** 绘制轮廓系数随 $k$ 变化的曲线,选择使轮廓系数最大或接近最大的 $k$ 值(需结合业务背景)。 ```python import matplotlib.pyplot as plt plt.plot(range(2, 11), scores, marker='o') plt.xlabel('Number of clusters (k)') plt.ylabel('Silhouette Score') plt.title('Silhouette Score vs. k') plt.show() ``` - **示例结果分析** 若曲线在 $k=4$ 时达到峰值,则选择 $k=4$ 作为最佳聚类数。 --- #### **3. 深入分析轮廓图(Silhouette Plot)** 对特定 $k$ 值生成轮廓图,观察每个簇的样本分布离群点: - 每个簇对应一个“刀形”区域,宽度表示簇内样本数量,高度表示簇内样本的轮廓系数- 理想情况:所有簇的轮廓系数均较高,且宽度相近。 ```python from sklearn.metrics import silhouette_samples import matplotlib.cm as cm k = 4 # 假设选择 k=4 kmeans = KMeans(n_clusters=k, random_state=42) labels = kmeans.fit_predict(X) # 绘制轮廓图 fig, ax = plt.subplots(figsize=(8, 6)) y_lower = 10 for i in range(k): cluster_silhouette = silhouette_scores[labels == i] cluster_silhouette.sort() y_upper = y_lower + cluster_silhouette.shape[0] color = cm.nipy_spectral(float(i) / k) ax.fill_betweenx(np.arange(y_lower, y_upper), 0, cluster_silhouette, facecolor=color, edgecolor=color, alpha=0.7) ax.text(-0.05, y_lower + 0.5 * cluster_silhouette.shape[0], str(i)) y_lower = y_upper + 10 ax.set_xlabel("Silhouette Coefficient") ax.set_ylabel("Cluster") plt.show() ``` --- #### **4. 注意事项** 1. **结合其他指标** 轮廓系数可能在高维数据或复杂分布中失效,需结合手法(Elbow Method)或 Calinski-Harabasz 指数综合判断。 2. **数据预处理** 确保数据已标准化(如使用 `StandardScaler`),避免量纲差异影响距离计算。 3. **业务需求优先** 若 $k$ 对应的轮廓系数差异较小(如 $k=3$ $k=4$ 的分数接近),需结合业务解释性选择。 --- #### **5. 示例场景** 假设对客户消费行为聚类- 若 $k=5$ 的轮廓系数最高,但业务上更关注“高/中/低”三个消费层级,可优先选择 $k=3$。 - 若某簇的轮廓系数显著低于其他簇,需检查该簇样本是否属于噪声或需进一步细分。 --- 通过轮廓系数调整 K-Means,能更客观地平衡簇内紧密性簇间分离性,从而优化聚类结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值