k-means のシルエットプロット

産業は成長の連動性でクラスターに分かれるか?k-means のクラスターとシルエット幅。

k-means のシルエットプロット

シルエット幅は、各観測が自分のクラスターにどれだけ近いかを、最も近い他のクラスターへの近さと比べた指標です。1 に近ければ適切に配置され、0 に近ければ境界上にあり、負であれば誤って割り当てられている可能性が高いことを示します。クラスター数 k は、平均シルエットが最大となる値を選びます(2〜8 を試行)。左のパネルは第 1・第 2 主成分上のクラスター、右のパネルはクラスター内でシルエット幅を並べ替えたもので、破線は全体の平均です。

設定は Chaffa & Warin (2026)「Identifying industrial clusters through growth co-movement with unsupervised learning methods」(GeoJournal)です。90 の産業を、標準化した 5 つの連動性の特徴量 — 生産成長率と国内 GDP、米国の需要、一次産品価格、住宅着工との相関、および成長率のボラティリティ — で記述します。データは説明のために 3 つのプロファイル(国内景気型、輸出志向型、資源型)の周りに numpy(シード固定)でシミュレーションしたもので、論文のデータや結果ではありません。平均幅 0.5 前後は、Kaufman & Rousseeuw の目安では弱い構造と妥当な構造の境界にあたります。sklearn の KMeans、silhouette_score、silhouette_samples が計算を担い、PCA はクラスターの描画にのみ使います。

コードおよび図中のテキストは英語です。

silhouette-clusters.py · 63 行
ダウンロード GitHub
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}
}

多変量解析とクラスタリングのその他のグラフ