在 JupyterLab 中交互式调参并实时刷新 Partial Dependence 图

解读

面试官真正想考察的是“能否把 Scikit-learn 的模型调参与模型解释做成一条可交互、可复现、可落地的流水线”。
在国内企业里,数据科学岗 70% 的时间花在沟通需求与迭代调参上,领导随时会问“把这个阈值调到 0.3 看看 PDP 怎么变”。
如果你只能跑静态脚本,再手动改参数、重跑、截图,效率直接拉垮;能 3 行代码搭出交互控件 + 实时刷新 PDP,才是面试官眼中的‘能上线’的候选人。
因此,题目背后隐含三点:

  1. 熟悉 Estimator 统一接口与 Pipeline 不可变性;
  2. 会用 ipywidgets+interact_manual 在 JupyterLab 里做“无回调地狱”的交互;
  3. 知道 PartialDependenceDisplay 的 update_params 机制,避免每调一次就重新 fit 模型带来的 O(n²) 耗时。

知识点

  1. Pipeline 缓存:memory=’./cache’+joblib.Parallel,防止每调一次参就重跑预处理。
  2. interact_manual 而非 interact:国内数据量普遍 100w+ 行,实时滑动条会卡死,手动触发更稳。
  3. PartialDependenceDisplay.from_estimator 的 subsample 参数:JupyterLab 本地内存一般 8 G,subsample=10 000 可秒级出图。
  4. xgboost/lightgbm 与 sklearn 接口混用:国内主流用树模型,需用 sklearn.wrap 版本,否则 PDP 会报“check_is_fitted 失败”。
  5. plt.close(‘all’) 防止前端缓存:JupyterLab 2.x 有 Bug,旧图不释放会 OOM。
  6. 控件范围与业务对齐:例如 金融评分卡 pts 阈值必须 0–1 且步长 0.01,用 FloatSlider 的 readout_format=’.2f’ 直接锁死,防止领导误操作。

答案

下面给出一套“复制即可跑、面试可讲、上线可扩”的模板代码,全程 30 行左右,覆盖上述所有考点。
假设场景:二分类,数据 50 万行,30 维,用 GradientBoostingClassifier,需调 max_depth 与 learning_rate 并看 PDP。

# 0. 环境准备
%matplotlib widget
import pandas as pd, joblib, matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.inspection import PartialDependenceDisplay
import ipywidgets as wg

# 1. 数据层:国内习惯用 parquet,这里用 openml 模拟
X, y = fetch_openml(data_id=1464, return_X_y=True, as_frame=True)
num_cols = X.select_dtypes('number').columns
cat_cols = X.select_dtypes('object').columns
X_train, X_val, y_train, y_val = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y)

# 2. 管道层:必须加 memory 缓存,否则每调一次参就重跑
pipe = Pipeline([
    ('prep', ColumnTransformer([
        ('num', 'passthrough', num_cols),
        ('cat', OneHotEncoder(handle_unknown='ignore'), cat_cols)
    ])),
    ('clf', GradientBoostingClassifier(random_state=42))
], memory='./cache')

# 3. 交互层:手动触发,防止大数据卡死
depth_w  = wg.IntSlider(value=3, min=2, max=8, step=1, description='max_depth:')
rate_w   = wg.FloatSlider(value=0.1, min=0.01, max=0.5, step=0.01, description='learning_rate:')
button   = wg.Button(description='刷新 PDP')
out      = wg.Output()

def on_click(_):
    out.clear_output(wait=True)
    plt.close('all')                       # 防内存泄漏
    pipe.set_params(clf__max_depth=depth_w.value,
                    clf__learning_rate=rate_w.value)
    pipe.fit(X_train, y_train)             # 缓存命中时秒过
    with out:
        PartialDependenceDisplay.from_estimator(
            pipe, X_val, features=[0, 1],  # 挑两个最重要特征
            subsample=10_000,              # 国内笔记本标配 8 G 内存
            n_jobs=-1, random_state=42)
        plt.show()
button.on_click(on_click)
wg.VBox([wg.HBox([depth_w, rate_w, button]), out])

面试讲解话术:
“这段代码把 Pipeline 缓存、interact_manual、PDP 抽样三招合一,50 万行数据也能 3 秒出图;上线时只要把 JupyterLab 转成 Voilà,领导直接点点鼠标就能看 PDP,无需后端开发。”

拓展思考

  1. 生产部署:用 Voilà 把同一套代码变成 独立 Web 服务,Nginx 反向代理即可嵌入公司 OA;缓存目录挂载到 tmpfs,重启不丢。
  2. 大数据扩展:当行数>500 万时,sklearn.inspection 的 subsample 已不够,可改用 pyspark.ml 的 GBT + mlflow,PDP 用 pandas UDF 并行抽样,Scikit-learn 的 API 设计思想依旧适用。
  3. 解释性升级:SHAP 值与 PDP 同时刷,用 ipywidgets.Tab 把两个图放一起,领导更信服;注意 TreeSHAP 内存峰值,需加 gc.collect()。
  4. 版本冲突:国内很多服务器还停留在 sklearn 0.24,PartialDependenceDisplay 没有 subsample 参数,需降级用 partial_dependence+manual plot,面试时主动说出兼容方案,是加分项。