带 ICE 曲线的部分依赖图
批次的预测废料率如何随机器速度和距上次维护的天数变化——每个批次一条曲线(ICE)之上的平均值(PDP)。

部分依赖图(PDP)显示:在其他特征保持观测值不变的情况下,当某一个特征变化时,模型的预测平均如何变化。平均值背后是 个体条件期望(ICE)曲线——每个观测一条。ICE 曲线相互平行,说明效应对每个人都相同;曲线发散或交叉,则揭示了被平均值掩盖的 交互作用。ICE 曲线在左端对齐(中心化),以便比较形状而非水平;底部的刻度标出数据实际所在之处,在其他地方模型是在外推。
本例以 Warin、d'Anglade 和 de Marcellis-Warin(2025,International Journal of Sustainable Engineering)的研究为背景,该研究结合 k-means 聚类与数据科学来减少制造业的废料。数据为说明用途而 模拟,并非 论文的数据或结果:使用与模型比较图相同的 n = 600 个生产批次。左图显示阈值效应:低速时废料平稳,高速时急剧上升,所有批次的曲线几乎平行。右图为距上次维护的天数,由于其效应被设定为依赖于湿度,ICE 曲线呈扇形散开。模型为梯度提升回归,曲线来自 sklearn.inspection.partial_dependence(kind="both")。PDP 描述的是模型而非世界:只有模型是因果的,它才是因果的。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.inspection import partial_dependence
# 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)
features = ["speed", "maintenance"]
change, spread = {}, {}
plt.rcParams["figure.constrained_layout.use"] = False # manual margins leave room for the subtitle
fig, axes = plt.subplots(1, 2, figsize=(10, 5), sharey=True)
fig.subplots_adjust(left=0.10, right=0.97, top=0.80, bottom=0.12, wspace=0.08)
for ax, f in zip(axes, features):
pd_res = partial_dependence(model, X, [f], kind="both", grid_resolution=40)
grid = pd_res["grid_values"][0]
ice = pd_res["individual"][0]
ice_c = ice - ice[:, [0]] # centred ICE
pdp_c = pd_res["average"][0] - pd_res["average"][0][0]
change[f] = pdp_c[-1] # average effect over the whole range
lo, hi = np.percentile(ice_c, [10, 90], axis=0)
spread[f] = (lo[-1], hi[-1])
ax.plot(grid, ice_c.T, color="#007AFF", alpha=0.07, lw=0.8)
ax.plot(grid, pdp_c, color="#FF9500", lw=3, label="Average (PDP)")
ax.plot(grid, lo, color="#007AFF", lw=1, ls="--")
ax.plot(grid, hi, color="#007AFF", lw=1, ls="--", label="10th / 90th percentile of ICE")
ax.plot(X[f], np.full(len(X), -1.3), "|", color="#3A3A3C", ms=8, alpha=0.4) # rug
ax.set_xlabel(names[f])
ax.set_title(f"Effect of {names[f].split(' (')[0].lower()}")
axes[0].set_ylim(-1.6, 6.5)
axes[0].set_ylabel("Change in predicted waste rate\n(points, relative to the lowest value)")
axes[0].legend(loc="upper left", fontsize=9)
m_lo, m_hi = spread["maintenance"]
fig.suptitle(f"Speed adds {change['speed']:.1f} points of waste for every batch; {grid[-1]:.0f} days without "
f"maintenance add {m_lo:.1f} to {m_hi:.1f}", x=0.02, y=0.97, ha="left")
fig.text(0.02, 0.885, f"Gradient boosting · n = {n} batches (simulated) · thin lines = one batch (centred ICE) · "
"ticks = observed values", 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). Partial dependence with ICE curves. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/machine-learning/partial-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}
}更多机器学习图表
带指标的混淆矩阵
分类器把推文归入环境、社会和治理主题的准确程度——样本外 3 × 3 混淆矩阵,并为各项指标给出自助法区间。
yardstick::conf_mat() + autoplot()精确率–召回率曲线
两个分类器预测哪些 Facebook 用户会分享 COVID-19 假新闻的样本外精确率–召回率曲线,附平均精确率与无技能基线。
yardstick::pr_curve() + autoplot()学习曲线
随着训练集增大,两个预测哪些 Facebook 用户会分享 COVID-19 假新闻的模型的训练准确率与交叉验证准确率。
caret::learning_curve_dat() + ggplot()