蓝色天空.知识 · 实践 · 创造
我的收藏
机器学习 教程目录 58章
机器学习 / LEARN BY DOING

常见问题排查

系统梳理模型上线效果衰减、工程部署故障与训练收敛异常三大类高频问题,实测训练-服务缩放偏移、Z-score 漂移告警、学习曲线诊断、20 层梯度稳定性与常驻加载性能。

学完这一章,你能够

  • 系统梳理模型上线效果衰减、工程部署故障与训练收敛异常三大类高频问题,实测训练-服务缩放偏移、Z-score 漂移告警、学习曲线诊断、20 层梯度稳定性与常驻加载性能。

模型性能问题:训练好、上线差的根源排查

离线笔记本准确率极高而线上效果一落千丈,首要嫌疑是数据分布不一致,常见三种根因:(1)特征工程不一致(训练-服务偏移),例如线上误对实时批次重新 fit StandardScaler 而未复用离线保存的 scaler.mean_ 与 scaler.scale_——本站实测针对高价值客群切片,复用离线标准化器保持 1.0000 准确率,误在线上重新 fit_transform 则骤降至 0.5333(暴跌 46.7 个百分点);(2)时间概念漂移与(3)样本选择偏差,需要持续监控输入特征统计量。本站核对来源滑动窗口样本 [0.1, 0.5, 1.2, 0.8, 1.5, 2.0, 2.5](均值 1.229 对比训练均值 0.5、标准差 0.3):按单点标准差算 Z=2.429(未超 3σ 阈值),但若按均值标准误 σ/√n 检验则 Z_SEM 高达 6.425;当线上整体再偏 +0.8 时 Z 升至 5.095,触发漂移告警。

第二大元凶是数据泄露:划分前全局标准化/插补、时序未来穿越或引入事后特征都会虚抬离线指标。本站再次对比实测:后 20% 测试区段偏移 +5.0 时,全局拟合使训练均值被污染至 1.0533(对比训练集真实均值 0.0617,偏差 0.9916),而将预处理与分类器装入 scikit-learn Pipeline 仅在训练集拟合则完全杜绝污染。

工程化与部署问题:环境依赖、延迟瓶颈与内存管理

将模型转化为高可用 API 服务常见三类工程故障:(1)环境依赖与版本冲突,需核对 Python 主版本、核心框架精确版本、底层 C++ 运行时与 pickle 跨版本兼容问题,通过 Docker 容器化、requirements.txt/environment.yml 锁版,以及 ONNX、PMML、SavedModel、TorchScript 等规范化格式保障一致性。

(2)线上推理性能低下:单次计算过重可通过剪枝、量化、蒸馏或轻量化重写优化;频繁数据库/远程 I/O 可引入特征缓存与预计算;按算子特性匹配 CPU/GPU 及 TensorRT/OpenVINO 加速;高并发场景用 TensorFlow Serving、TorchServe 或 Triton Inference Server 替代裸 Flask 单进程以支持动态批处理与热更新。

(3)资源与内存管理不当:严禁每次请求重复反序列化加载模型,应在服务启动时常驻内存共享,警惕全局 List/Dict 无界增长和大对象未释放,配合 gunicorn/uvicorn Worker 配置、进程守护定期轮转与 memory_profiler 排查泄漏。本站实测 40 次连续预测请求:每次重新 pickle.load 耗时 38.718 ms,而启动单次加载常驻内存复用仅耗 16.499 ms(提速超 2.3 倍且预测结果逐条一致),并同步校验 NaN/Inf 输入拦截与当前依赖版本锁定(Python 3.12.14 / NumPy 2.5.4 / scikit-learn 1.9.1)。

模型算法问题:欠拟合/过拟合与梯度消失/爆炸

判断欠拟合与过拟合的最佳诊断工具是学习曲线(learning_curve)。本站在 400 条含噪非线性分类数据上用 5 折 learning_curve 实测三类深度决策树:max_depth=1 呈典型欠拟合(训练 0.6756、验证 0.6175,双低);max_depth=None 呈明显过拟合(训练 1.0000、验证 0.7600,泛化鸿沟达 0.2400);max_depth=5 取得更优平衡(训练 0.8962、验证 0.7625,差距收窄至 0.1337)。详见下方排查表。

深层网络训练常遭遇梯度消失(早期损失停滞、权重几乎不更新)或梯度爆炸(权重暴涨乃至损失出现 NaN),对策涵盖按激活函数选用 He(ReLU)或 Xavier(Tanh/Sigmoid)初始化、设置范数阈值做梯度裁剪、加入 BatchNorm 以及引入 ResNet 残差连接。本站在 20 层宽 32 的纯 NumPy 前向信号尺度实验中量化复现:过小初始化(σ=0.05)20 层后输出标准差骤降至 2.419e-14(信号消失),过大初始化(σ=0.50)暴涨至 1.008×10^6(信号爆炸);而 He 初始化(ReLU 末层 std=0.7422)、BatchNorm(0.5811)与 Xavier 初始化(Tanh 末层 std=0.1422)均稳定在健康区间,同时梯度裁剪可将范数 50.0 的异常梯度精确压回 1.0000。

系统化线上故障排查七步流程

线上模型告警时,切忌盲目调参,应按七步有序收敛根因:(1)确认影响面——全量错误还是特定客群/场景,量化错误率;(2)审计输入样本——抽取异常请求检查字段完整、类型合法及有无 NaN/Inf/极端值;(3)本地精准复现——用同版模型与代码回放异常请求;(4)核对分布漂移——对比线上特征与训练集统计分布;(5)校验版本配置——核实代码、模型文件哈希与依赖配置一致;(6)查验系统日志与监控——排查超时、OOM 与上游接口报错;(7)基线隔离定位——用极简规则或小模型对照处理同一批异常输入,迅速区分问题出在数据链路还是模型自身。

欠拟合与过拟合现象、成因及解决方案对比

问题现象可能原因解决方案
欠拟合训练集与验证集表现均差(本站 d=1:训练 0.6756 / 验证 0.6175)模型容量过低、关键特征缺失、正则化过强或训练轮次不足增加模型复杂度、构造有效特征、减弱过强正则化或增加迭代轮次
过拟合训练集极高但验证集显著落后(本站无限制树:训练 1.0000 / 验证 0.7600)模型过度复杂、训练样本偏少或标签噪声较多扩充数据、引入 L1/L2/Dropout 正则化、限制树深/复杂度及早停

运行训练-服务偏移、学习曲线诊断与 20 层梯度稳定实验

含完整源码 · 245 行
展开查看收起
python
"""Independent scikit-learn + NumPy CPU lab for troubleshooting train-serve skew, leakage, learning curves, gradient instability, and serving checks."""
import json
import pickle
import platform
import tempfile
import time
from pathlib import Path

import numpy as np
import sklearn
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import learning_curve, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier


def run_cases():
    rng = np.random.default_rng(42)
    cases = []

    # 1. Train-serve skew (online refit bug vs saved scaler) + sliding-window Z-score drift
    X_s = rng.normal(loc=5.0, scale=2.0, size=(300, 3))
    y_s = (X_s[:, 0] - 5.0 + 0.6 * (X_s[:, 1] - 5.0) > 0).astype(int)
    X_tr, X_te, y_tr, y_te = train_test_split(X_s, y_s, test_size=0.3, random_state=42, stratify=y_s)
    scaler_off = StandardScaler().fit(X_tr)
    clf_off = LogisticRegression(random_state=42).fit(scaler_off.transform(X_tr), y_tr)

    # Take a skewed online slice (high-value positive customers: feature0 > 6.0)
    pos_mask = X_te[:, 0] > 6.0
    X_online = X_te[pos_mask]
    y_online = y_te[pos_mask]
    acc_saved_scaler = round(float(accuracy_score(y_online, clf_off.predict(scaler_off.transform(X_online)))), 4)
    # Bug: mistakenly calling fit_transform on the biased online slice centers it back to 0!
    acc_refit_bug = round(float(accuracy_score(y_online, clf_off.predict(StandardScaler().fit_transform(X_online)))), 4)

    # Exact sliding-window Z-score check from source example + shifted batch
    online_vals = np.array([0.1, 0.5, 1.2, 0.8, 1.5, 2.0, 2.5])
    tr_mean, tr_std = 0.5, 0.3
    z_source = round(float((np.mean(online_vals) - tr_mean) / tr_std), 3)
    # Standard error of the mean z-score: sqrt(n) * z_source (highlights batch size sensitivity)
    z_sem_source = round(float((np.mean(online_vals) - tr_mean) / (tr_std / np.sqrt(len(online_vals)))), 3)
    shifted_vals = online_vals + 0.8
    z_shifted = round(float((np.mean(shifted_vals) - tr_mean) / tr_std), 3)

    c1_ok = acc_saved_scaler >= 0.90 and acc_refit_bug < acc_saved_scaler - 0.25 and abs(z_source) <= 3.0 and abs(z_shifted) > 3.0
    cases.append(dict(
        name="train_serve_skew_and_zscore_drift",
        inputs=dict(online_slice_n=int(len(X_online)), tr_mean=tr_mean, tr_std=tr_std, z_threshold=3.0),
        prerequisites="对比复用离线 scaler.mean_/scale_ 与线上误重新 fit_transform;核对滑动窗口均值 Z-score",
        action="验证线上误重拟合导致准确率骤降 >25 个百分点,而复用离线参数保持 >=90%;并核对原例 Z=2.429(未超 3σ)与加剧偏移 Z=5.095(触发告警)。",
        expected=dict(saved_scaler_ge_90=True, refit_bug_drops_gt_25pct=True, source_z_le_3=True, shifted_z_gt_3=True),
        actual=dict(
            saved_scaler_ge_90=acc_saved_scaler >= 0.90,
            refit_bug_drops_gt_25pct=(acc_refit_bug < acc_saved_scaler - 0.25),
            source_z_le_3=(abs(z_source) <= 3.0),
            shifted_z_gt_3=(abs(z_shifted) > 3.0),
        ),
        measurements=dict(
            acc_saved_scaler=acc_saved_scaler, acc_refit_bug=acc_refit_bug,
            source_online_mean=round(float(np.mean(online_vals)), 3),
            z_source=z_source, z_sem_source=z_sem_source, z_shifted=z_shifted,
        ),
        passed=c1_ok,
    ))

    # 2. Global scaling leakage vs Pipeline isolation
    X_l = rng.normal(0.0, 1.0, size=(200, 4))
    X_l[160:, 0] += 5.0  # future test regime shift
    y_l = (X_l[:, 0] + X_l[:, 1] > 1.0).astype(int)
    Xl_tr, Xl_te, yl_tr, yl_te = X_l[:160], X_l[160:], y_l[:160], y_l[160:]
    sc_global = StandardScaler().fit(X_l)
    pipe_clean = Pipeline([("scaler", StandardScaler()), ("clf", LogisticRegression(random_state=42))]).fit(Xl_tr, yl_tr)
    sc_clean = pipe_clean.named_steps["scaler"]
    mean_contamination = round(float(abs(sc_global.mean_[0] - sc_clean.mean_[0])), 4)
    c2_ok = mean_contamination > 0.8 and abs(float(sc_clean.transform(Xl_tr)[:, 0].mean())) < 1e-6
    cases.append(dict(
        name="preprocessing_leakage_vs_pipeline_fix",
        inputs=dict(train_n=160, test_n=40, test_shift=5.0),
        prerequisites="对比全局 StandardScaler 拟合与 Pipeline 仅在训练集拟合",
        action="验证全局标准化被测试集偏移污染 (>0.8),而 Pipeline 严格隔离训练集统计量。",
        expected=dict(global_contaminated=True, pipeline_clean=True),
        actual=dict(global_contaminated=mean_contamination > 0.8, pipeline_clean=abs(float(sc_clean.transform(Xl_tr)[:, 0].mean())) < 1e-6),
        measurements=dict(global_mean0=round(float(sc_global.mean_[0]), 4), clean_mean0=round(float(sc_clean.mean_[0]), 4), contamination=mean_contamination),
        passed=c2_ok,
    ))

    # 3. Learning curve diagnosis: Underfitting vs Overfitting vs Balanced
    X_lc, y_lc = make_classification(
        n_samples=400, n_features=10, n_informative=5, n_redundant=2,
        flip_y=0.06, class_sep=1.0, random_state=42,
    )
    lc_summary = {}
    for label, depth in (("underfit_d1", 1), ("balanced_d5", 5), ("overfit_unbounded", None)):
        sizes, tr_sc, va_sc = learning_curve(
            DecisionTreeClassifier(max_depth=depth, random_state=42),
            X_lc, y_lc, cv=5, train_sizes=[0.25, 0.5, 0.75, 1.0], scoring="accuracy",
        )
        tr_end = round(float(tr_sc[-1].mean()), 4)
        va_end = round(float(va_sc[-1].mean()), 4)
        lc_summary[label] = dict(train_score=tr_end, val_score=va_end, gap=round(tr_end - va_end, 4))

    under_low = lc_summary["underfit_d1"]["train_score"] < 0.82 and lc_summary["underfit_d1"]["val_score"] < 0.82
    over_gap = lc_summary["overfit_unbounded"]["train_score"] == 1.0 and lc_summary["overfit_unbounded"]["gap"] > 0.12
    balanced_best_val = lc_summary["balanced_d5"]["val_score"] > lc_summary["underfit_d1"]["val_score"] and lc_summary["balanced_d5"]["gap"] < lc_summary["overfit_unbounded"]["gap"]
    c3_ok = under_low and over_gap and balanced_best_val
    cases.append(dict(
        name="learning_curve_underfit_vs_overfit",
        inputs=dict(n_samples=400, cv=5, depths=[1, 5, None]),
        prerequisites="使用 learning_curve 诊断 max_depth=1(欠拟合)、5(平衡)与 None(过拟合)的训练/验证曲线",
        action="验证深度 1 训练与验证均低 (<0.82)、无限制树训练 1.00 且泛化差距 >0.12,而深度 5 取得更高验证分且缩小差距。",
        expected=dict(underfit_both_low=True, overfit_train1_large_gap=True, balanced_improves=True),
        actual=dict(underfit_both_low=under_low, overfit_train1_large_gap=over_gap, balanced_improves=balanced_best_val),
        measurements=lc_summary,
        passed=c3_ok,
    ))

    # 4. Vanishing / exploding gradients, He vs Xavier initialization, BatchNorm & gradient clipping
    dim, depth = 32, 20
    x0 = rng.normal(0.0, 1.0, size=(64, dim))

    def propagate_relu_std(init_scale: float, use_bn: bool = False) -> float:
        h = x0.copy()
        for _ in range(depth):
            W = rng.normal(0.0, init_scale, size=(dim, dim))
            h = h @ W
            if use_bn:
                h = (h - h.mean(axis=0, keepdims=True)) / np.sqrt(h.var(axis=0, keepdims=True) + 1e-5)
            h = np.maximum(0.0, h)
        return float(np.std(h))

    def propagate_tanh_std(init_scale: float) -> float:
        h = x0.copy()
        for _ in range(depth):
            W = rng.normal(0.0, init_scale, size=(dim, dim))
            h = np.tanh(h @ W)
        return float(np.std(h))

    std_vanish = propagate_relu_std(0.05)                   # << 1e-6
    std_explode = propagate_relu_std(0.50)                  # >> 1e3
    std_he = round(propagate_relu_std(np.sqrt(2.0 / dim)), 4)
    std_bn = round(propagate_relu_std(0.50, use_bn=True), 4)
    std_xavier_tanh = round(propagate_tanh_std(np.sqrt(1.0 / dim)), 4)

    # Gradient norm clipping verification
    raw_grad = np.array([30.0, -40.0, 0.0])  # norm = 50.0
    max_norm = 1.0
    raw_norm = float(np.linalg.norm(raw_grad))
    clipped_grad = raw_grad * min(1.0, max_norm / (raw_norm + 1e-12))
    clipped_norm = round(float(np.linalg.norm(clipped_grad)), 6)

    c4_ok = (
        std_vanish < 1e-6
        and std_explode > 1e3
        and 0.1 < std_he < 5.0
        and 0.3 < std_bn < 1.5
        and 0.05 < std_xavier_tanh < 1.0
        and abs(clipped_norm - 1.0) < 1e-5
    )
    cases.append(dict(
        name="gradient_instability_init_bn_clip",
        inputs=dict(width=dim, depth=depth, max_norm=max_norm),
        prerequisites="20 层前向信号尺度实测:过小/过大初始化、He(ReLU)、Xavier(Tanh)、BatchNorm 与梯度范数裁剪",
        action="验证不当初始化在 20 层后导致信号消失 (<1e-6) 或爆炸 (>1e3),而 He/Xavier/BatchNorm 维持稳定尺度,梯度裁剪精确将范数 50 压至 1.0。",
        expected=dict(vanish_lt_1e6=True, explode_gt_1e3=True, he_and_bn_stable=True, xavier_stable=True, clipped_norm_is_1=True),
        actual=dict(
            vanish_lt_1e6=std_vanish < 1e-6,
            explode_gt_1e3=std_explode > 1e3,
            he_and_bn_stable=(0.1 < std_he < 5.0 and 0.3 < std_bn < 1.5),
            xavier_stable=(0.05 < std_xavier_tanh < 1.0),
            clipped_norm_is_1=(abs(clipped_norm - 1.0) < 1e-5),
        ),
        measurements=dict(
            vanish_std=float(f"{std_vanish:.3e}"),
            explode_std=float(f"{std_explode:.3e}"),
            he_relu_std=std_he,
            bn_relu_std=std_bn,
            xavier_tanh_std=std_xavier_tanh,
            raw_grad_norm=raw_norm,
            clipped_grad_norm=clipped_norm,
        ),
        passed=c4_ok,
    ))

    # 5. Serving diagnostics: NaN/Inf input filter, in-memory model reuse vs per-request reload, env audit
    with tempfile.TemporaryDirectory() as tmp:
        model_file = Path(tmp) / "clf.pkl"
        with model_file.open("wb") as fh:
            pickle.dump(pipe_clean, fh)

        def sanitize_input(arr: np.ndarray) -> tuple[bool, str]:
            if arr.ndim != 2 or arr.shape[1] != 4:
                return False, "bad_shape"
            if not np.all(np.isfinite(arr)):
                return False, "nan_or_inf"
            return True, "ok"

        ok_good, _ = sanitize_input(Xl_te[:1])
        ok_nan, code_nan = sanitize_input(np.array([[1.0, np.nan, 0.2, 0.3]]))
        ok_inf, code_inf = sanitize_input(np.array([[1.0, 0.2, np.inf, 0.3]]))

        # Compare 40 requests reloading pickle each time vs sharing one loaded instance in memory
        batch_reqs = [Xl_te[i : i + 1] for i in range(40)]
        t0 = time.perf_counter()
        preds_reload = []
        for row in batch_reqs:
            with model_file.open("rb") as fh:
                m = pickle.load(fh)
            preds_reload.append(int(m.predict(row)[0]))
        reload_ms = round((time.perf_counter() - t0) * 1000.0, 3)

        with model_file.open("rb") as fh:
            shared_model = pickle.load(fh)
        t1 = time.perf_counter()
        preds_cached = [int(shared_model.predict(row)[0]) for row in batch_reqs]
        cached_ms = round((time.perf_counter() - t1) * 1000.0, 3)

        env_pin = dict(python=platform.python_version(), numpy=np.__version__, sklearn=sklearn.__version__)
        preds_identical = preds_reload == preds_cached
        c5_ok = ok_good and (not ok_nan) and (not ok_inf) and preds_identical and cached_ms <= reload_ms

    cases.append(dict(
        name="serving_input_guard_and_model_reuse",
        inputs=dict(requests=40, feature_dim=4),
        prerequisites="核对 NaN/Inf 输入拦截、单次常驻加载 vs 每次请求重复反序列化及运行版本核对",
        action="验证 NaN/Inf 异常输入在预测前拦截,常驻内存复用与重复加载预测完全一致且不慢于每次重新加载。",
        expected=dict(nan_inf_blocked=True, predictions_identical=True, cached_not_slower=True),
        actual=dict(nan_inf_blocked=(ok_good and not ok_nan and not ok_inf), predictions_identical=preds_identical, cached_not_slower=(cached_ms <= reload_ms)),
        measurements=dict(reload_40_ms=reload_ms, cached_40_ms=cached_ms, env_pin=env_pin, codes=[code_nan, code_inf]),
        passed=c5_ok,
    ))

    payload = dict(
        version=platform.python_version(),
        system=platform.system(),
        cases=cases,
    )
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
核对线上误重拟合准确率骤降 46.7%、滑动窗口 Z-score 与均值标准误校验、三深度学习曲线、20 层 He/Xavier/BN 稳定尺度与梯度裁剪,以及常驻内存复用加速。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a449.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a483.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

小批次甚至单条样本的均值与标准差与训练总体截然不同(单条样本方差更是 0),重新拟合会把原本处于高分区的样本强行拉回 0 附近,造成严重的训练-服务偏移;线上必须只调用离线拟合好并持久化的 scaler.transform。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习