SHAP 依存プロット

前回保守からの日数が各ロットの予測廃棄率にどう寄与するか。最も強い交互作用の相手で色分けし、平滑化した傾向線を添えます。

SHAP 依存プロット

SHAP 依存プロットは 1 つの特徴量に焦点を当てます。各点が生産ロットで、横軸は特徴量の値、縦軸はその SHAP 値、すなわちそのロットの予測廃棄率への寄与です。傾向線(LOWESS 平滑化)は部分依存曲線に近いものですが、その周りの点の広がりにも情報があります。前回保守からの日数が同じでも、ほかの特徴量との 交互作用 によって寄与はロットごとに異なるのです。

色は、この縦方向の広がりを最もよく説明する特徴量を示します。ここでは、前回保守からの日数との SHAP 交互作用 値が平均して最も大きい特徴量を選んでいます(shap.TreeExplainer.shap_interaction_values)。例の舞台は、k-means クラスタリングとデータサイエンスを組み合わせて製造業の廃棄削減に取り組んだ Warin、d'Anglade、de Marcellis-Warin(2025 年、International Journal of Sustainable Engineering)の研究です。データは説明のために シミュレーション したもので、論文のデータや結果では ありません。モデル比較と同じ n = 600 の生産ロットで、作業場が湿っていると摩耗した機械ほど廃棄が増えるように作っています。モデルは勾配ブースティング回帰、平滑化は statsmodels.nonparametric.lowess によります。

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

shap-dependence.py · 60 行
ダウンロード GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import shap
from sklearn.ensemble import GradientBoostingRegressor
from statsmodels.nonparametric.smoothers_lowess import lowess
# Simulated data, set in the context of Warin, d'Anglade & de Marcellis-Warin (2025) [warin2025waste]

# Data: 600 production batches; outcome = waste rate (% of material scrapped)
rng = np.random.default_rng(2025)
n = 600
names = {"speed": "Machine speed (units/min)", "temperature": "Temperature (°C)",
         "humidity": "Humidity (%)", "experience": "Operator experience (years)",
         "maintenance": "Days since maintenance", "grade": "Material grade (1 = best)",
         "batch_size": "Batch size (kg)"}
X = pd.DataFrame({"speed": rng.uniform(80, 160, n), "temperature": rng.uniform(195, 225, n),
                  "humidity": rng.uniform(30, 75, n), "experience": rng.gamma(2, 4, n),
                  "maintenance": rng.uniform(0, 120, n), "grade": rng.integers(1, 4, n),
                  "batch_size": rng.uniform(200, 1000, n)})       # batch size has no effect
y = (2 + 0.002 * np.clip(X.speed - 110, 0, None) ** 2            # waste climbs above 110 units/min
     + 0.025 * (X.temperature - 210) ** 2                        # U-shape around the 210 °C set point
     + 3 * np.exp(-X.experience / 3)                             # novices waste more, gains fade
     + 4 * (X.humidity - 30) / 45 * X.maintenance / 120          # humidity hurts worn machines most
     + 0.6 * (X.grade - 1) + rng.normal(0, 0.7, n))
model = GradientBoostingRegressor(learning_rate=0.05, n_estimators=300, max_depth=2,
                                  subsample=0.8, random_state=0).fit(X, y)

explainer = shap.TreeExplainer(model)
sv = explainer.shap_values(X)
inter = explainer.shap_interaction_values(X)            # (batches, features, features)

f = list(X.columns).index("maintenance")
strength = np.abs(inter[:, f, :]).mean(axis=0)
strength[f] = 0
partner = int(np.argmax(strength))                       # strongest interaction partner

x, s = X.iloc[:, f].to_numpy(), sv[:, f]
col = X.iloc[:, partner].rank(pct=True).to_numpy()
trend = lowess(s, x, frac=0.35)

fig, ax = plt.subplots(figsize=(8, 5.2))
sc = ax.scatter(x, s, c=col, cmap="coolwarm", s=22, alpha=0.8, lw=0, vmin=0, vmax=1)
ax.plot(trend[:, 0], trend[:, 1], color="#1d1d1f", lw=2.2, label="LOWESS trend")
ax.axhline(0, color="#8E8E93", lw=0.8)
ax.set_xlabel(names["maintenance"])
ax.set_ylabel("SHAP value of days since maintenance\n(percentage points of waste)")
ax.grid(axis="x")
ax.legend(loc="upper left")
cb = fig.colorbar(sc, ax=ax, pad=0.02, aspect=40, ticks=[0, 1])
cb.ax.set_yticklabels(["low", "high"])
cb.set_label(f"{names[X.columns[partner]]} (percentile)", fontsize=9.5)
cb.outline.set_visible(False)

old = x > 90
wet, dry = s[old & (col > 2 / 3)].mean(), s[old & (col < 1 / 3)].mean()
ax.set_title(f"Beyond 90 days without maintenance: {wet:+.1f} points of waste when humid, "
             f"{dry:+.1f} when dry", pad=26)
ax.text(0, 1.02, f"Gradient boosting · n = {n} batches (simulated) · colour = strongest interaction "
        f"partner: {names[X.columns[partner]].split(' (')[0].lower()}", transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
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.
  • Warin, d'Anglade & de Marcellis-Warin (2025), data science for waste reduction in manufacturing. Warin, T., d'Anglade, P. M., & de Marcellis-Warin, N. (2025). Optimising industrial efficiency: Integrating K-means clustering and data science for sustainable manufacturing and waste reduction. International Journal of Sustainable Engineering, 18(1), 2527300. https://doi.org/10.1080/19397038.2025.2527300
    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). SHAP dependence plot. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/machine-learning/shap-dependence/

@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}
}

機械学習のその他のグラフ