k-means 轮廓图
各产业能否按增长联动性分成聚类?k-means 聚类及其轮廓宽度。

轮廓宽度比较每个观测与其所属簇的接近程度和与最近的其他簇的接近程度:接近 1 表示归属恰当,接近 0 表示处于边界,为负则可能被错分。簇数 k 取平均轮廓宽度最大的值(尝试 2 到 8)。左图在前两个主成分上展示各簇;右图将每个簇内的轮廓宽度排序,虚线为总体平均值。
背景为 Chaffa 和 Warin (2026),“Identifying industrial clusters through growth co-movement with unsupervised learning methods”(GeoJournal):90 个产业,每个由 5 项标准化的联动特征描述——其产出增长与全国 GDP、美国需求、大宗商品价格和住房开工的相关系数,以及其增长波动率。数据由 numpy(固定种子)围绕三种类型(国内周期型、出口导向型、资源型)模拟,仅作示例,并非该论文的数据或结果。按 Kaufman 和 Rousseeuw 的经验法则,平均宽度接近 0.5 处于“弱结构”与“合理结构”的分界。计算由 sklearn 的 KMeans、silhouette_score 和 silhouette_samples 完成;PCA 仅用于绘制聚类。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn.preprocessing import StandardScaler
# Simulated data, set in the context of Chaffa & Warin (2026) [chaffa2026]
# 90 industries x 5 growth co-movement features around three profiles
rng = np.random.default_rng(91)
centres = np.array([[0.7, 0.2, 0.0, 0.6, 0.04], # domestic cycle
[0.4, 0.7, 0.1, 0.1, 0.06], # export-oriented
[0.2, 0.3, 0.7, 0.0, 0.10]]) # resource-based
profile = rng.choice(3, 90, p=[0.45, 0.33, 0.22])
X = StandardScaler().fit_transform(centres[profile] + rng.normal(0, [0.15, 0.15, 0.15, 0.15, 0.02],
(90, 5)))
# Choose k by the average silhouette width
fits = {k: KMeans(k, n_init=20, random_state=1).fit(X) for k in range(2, 9)}
avg = {k: silhouette_score(X, m.labels_) for k, m in fits.items()}
k = max(avg, key=avg.get)
labels = fits[k].labels_
sil = silhouette_samples(X, labels)
colors = ["#007AFF", "#FF9500", "#34C759", "#FF3B30", "#AF52DE", "#5AC8FA", "#8E8E93", "#A2845E"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 5), width_ratios=[1, 1.15])
# Left: clusters projected on the first two principal components
pca = PCA(2).fit(X)
S, C = pca.transform(X), pca.transform(fits[k].cluster_centers_)
for j in range(k):
ax1.scatter(*S[labels == j].T, s=22, color=colors[j], alpha=0.6, lw=0)
ax1.scatter(*C[j], s=150, marker="X", color=colors[j], edgecolor="white", lw=1.5, zorder=3)
ax1.set_xlabel(f"PC1 ({100 * pca.explained_variance_ratio_[0]:.1f}%)")
ax1.set_ylabel(f"PC2 ({100 * pca.explained_variance_ratio_[1]:.1f}%)")
ax1.grid(axis="x")
# Right: silhouette widths, sorted within cluster
start = 0
for j in range(k):
s = np.sort(sil[labels == j])[::-1]
x = np.arange(start, start + len(s))
ax2.fill_between(x, 0, s, color=colors[j], step="mid", lw=0, alpha=0.85)
ax2.text(x.mean(), -0.05, f"Cluster {j + 1}\nn = {len(s)}\nmean {s.mean():.2f}",
ha="center", va="top", fontsize=9, color=colors[j], fontweight="semibold")
start += len(s) + 6
ax2.axhline(avg[k], color="#3A3A3C", ls="--", lw=1)
ax2.text(start - 6, avg[k] + 0.015, f"average {avg[k]:.2f}", ha="right", va="bottom",
fontsize=9, color="#3A3A3C")
ax2.axhline(0, color="#8E8E93", lw=0.8)
ax2.set_xticks([])
ax2.set_xlim(-3, start - 3)
ax2.set_ylim(-0.18, max(sil) + 0.08)
ax2.set_ylabel("Silhouette width")
ax2.spines["bottom"].set_visible(False)
ax1.set_title(f"Silhouette picks k = {k} co-movement clusters of industries",
pad=26)
ax1.text(0, 1.02, "Average silhouette for k = 2…8: " + ", ".join(f"{v:.2f}" for v in avg.values())
+ f" · {(sil < 0).sum()} industries with width < 0 · n = {len(X)} industries (simulated), "
f"{X.shape[1]} features", transform=ax1.transAxes, fontsize=9.5,
color="#6E6E73", in_layout=False)
plt.show()
图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。
数据来源
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - Chaffa & Warin (2026), industrial clusters from growth co-movement. Chaffa, L., & Warin, T. (2026). Identifying industrial clusters through growth co-movement with unsupervised learning methods. GeoJournal, 91(1), 16. https://doi.org/10.1007/s10708-025-11564-6
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.
这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。
如何引用
PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。
Warin, T. (2026). Silhouette plot for k-means. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/multivariate/silhouette-clusters/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}