H2O-3 早停参数 stopping_tolerance 深度解析:相对改进容差与收敛判定原理
H2O-3 早停参数 stopping_tolerance 深度解析:相对改进容差与收敛判定原理
导读
stopping_tolerance 是 H2O-3 机器学习平台中控制早停(early stopping)收敛灵敏度的核心参数:它定义了模型在停止训练之前必须达到的"相对改进"下限。本指南以官方参数文档(h2o-docs/src/product/data-science/algo-params/stopping_tolerance.rst)为主线,结合 H2O-3 源码中早停判定引擎、参数校验逻辑与 AutoML 自适应默认值实现,帮助你彻底理解该参数的判定公式、各算法默认值差异,并掌握在 R 与 Python 客户端中的实战配置方法。
参数概览:适用算法与定位
stopping_tolerance 是一个训练早停控制参数,可在以下算法中使用:
- GBM(梯度提升机)
- DRF(分布式随机森林)
- Deep Learning(深度学习)
- GLM(广义线性模型)
- GAM(广义加性模型)
- AutoML(自动机器学习)
- XGBoost
- Isolation Forest(孤立森林)
该参数同时也是一个超参数(Hyperparameter: yes),可以纳入网格搜索。不过需要注意:由于它控制的是早停行为而非模型结构,官方文档明确建议在网格搜索中通常保持固定值,而不是作为网格维度进行遍历——改变模型结构类参数(如树深度、学习率)对效果的影响远比调整容差有意义。关于早停类参数的网格搜索规范,可参考官方文档中 stopping_rounds 参数 与 stopping_metric 参数 的说明。
工作原理:移动平均与相对改进判定
该参数的含义是:模型在训练停止之前必须达到的改进容差(tolerance)。当模型在连续若干次评分(scoring event)中,相对改进不再超过该容差时,训练提前结束。
官方文档给出了一个典型组合示例:
stopping_rounds=3stopping_metric=misclassificationstopping_tolerance=1e-3
在此配置下,系统会计算最近 4 个 stopping rounds 的简单移动平均(simple moving average)——其中第一个移动平均值作为参考值(reference value),其余 3 个移动平均值与它进行比较。模型将在满足以下条件时停止训练:
- 对于越小越好的指标(如 misclassification):最佳移动平均与参考移动平均的比值 ≥ 1-1e-3 时停止;
- 对于越大越好的指标(如 AUC):最佳移动平均与参考移动平均的比值 ≤ 1+1e-3 时停止。
这些早停选项的核心价值在于提升性能:通过限制实际构建的模型数量,显著降低训练开销。
源码级的判定实现
H2O-3 的早停判定核心位于 h2o-core/src/main/java/hex/ScoreKeeper.java 的 stopEarly() 方法(第 319-395 行)。从源码可以看出完整的算法流程:
- 最少评分次数约束:当
k = stopping_rounds时,需要至少2k次评分事件(len < 2*k时直接返回false不触发早停)——前k次用于建立参考窗口,后k次用于检验改进。代码注释中给出了具体示例:20 次评分、k=3 时,movingAvg[0]基于索引 14-16 的事件(参考值),movingAvg[1..3]分别基于 15-17、16-18、17-19 的事件。 - 窗口移动平均计算:对最近
k+1次评分事件,每次取长度为k的滑动窗口计算算术平均。 - 方向感知的比较逻辑:
ConvergenceStrategy枚举(MORE_IS_BETTER/LESS_IS_BETTER/NON_DIRECTIONAL,第 402-443 行)分别对应不同指标的收敛判定:
| 指标方向 | 判定公式(源码第 410-428 行) |
|---|---|
| 越大越好(如 AUC、AUCPR) | ratio = maxInLastK / lastBeforeK,当 ratio <= 1 + rel_improvement 时停止 |
| 越小越好(如 misclassification、logloss、MSE) | ratio = minInLastK / lastBeforeK,当 ratio >= 1 - rel_improvement 时停止 |
其中 rel_improvement 就是用户传入的 stopping_tolerance。同时源码还有两个保护性检查:若移动平均中出现 NaN 或窗口内发生**零值穿越(zero-crossing,符号不一致)**则暂不判定早停,避免出现除以零或畸形的相对改进计算。
ScoreKeeper.StoppingMetric 枚举(第 147-168 行)为每个指标绑定收敛策略:AUC/AUCPR/lift_top_group 等绑定 MORE_IS_BETTER;deviance/logloss/MSE/RMSE/MAE/RMSLE/misclassification/mean_per_class_error 等绑定 LESS_IS_BETTER;anomaly_score 绑定 NON_DIRECTIONAL(适用于 Isolation Forest)。
以 XGBoost 为例,训练过程中正是通过 h2o-extensions/xgboost/src/main/java/hex/tree/xgboost/XGBoost.java 调用 ScoreKeeper.stopEarly(..., _parms._stopping_tolerance, ...) 来周期性检查收敛并决定是否提前终止迭代。
默认值与各算法的差异
通用默认值:0.001
对于除 AutoML 和 Isolation Forest 之外的所有支持算法,stopping_tolerance 默认值为 0.001。该默认值定义于 h2o-core/src/main/java/hex/Model.java:
protected double defaultStoppingTolerance() { return 1e-3; }
参数声明(第 494 行)即 public double _stopping_tolerance = defaultStoppingTolerance();。
Isolation Forest:0.01
Isolation Forest 的默认容差为 0.01。从源码看,h2o-algos/src/main/java/hex/tree/isofor/IsolationForestModel.java 覆写了默认值:
@Override
protected double defaultStoppingTolerance() {
return 0.01; // (inherited value 0.001 would be too low for the default criterion anomaly_score)
}
注释表明原因:Isolation Forest 的默认早停指标是 anomaly_score(非方向性指标),0.001 对它的收敛判定过于严格。
AutoML:基于数据集的自适应默认值
AutoML 的行为比较特殊,其默认值取决于训练数据规模与质量:
- 若数据集至少 100 万行,默认值为 0.001;
- 否则,默认值由**数据集规模与非 NA 比率(non-NA-rate)**共同决定,取值会更大。
这个自适应逻辑在源码中有明确实现。h2o-core/src/main/java/hex/grid/HyperSpaceSearchCriteria.java 中提供了 default_stopping_tolerance_for_frame():
public static double default_stopping_tolerance_for_frame(Frame frame) {
return Math.min(0.05, Math.max(0.001, 1/Math.sqrt((1 - frame.naFraction()) * frame.numRows())));
}
即默认容差被限定在 [0.001, 0.05] 区间内,取 1 / sqrt(行数 × 非NA比率)。这与 Python/R 客户端文档中描述的 "computed as 1/sqrt(nrows * non-NA-rate)" 完全一致。其设计意图在源码注释中说明:尤其对于小样本(small N),需要给出一个更宽松(更大)的容差,否则早停会过于严苛、难以触发。
在 h2o-automl/src/main/java/ai/h2o/automl/AutoML.java 中,AutoML 构建流程会判断用户是否使用 AUTO_STOPPING_TOLERANCE 哨兵值:若使用则调用 set_default_stopping_tolerance_for_frame(refFrame) 基于训练帧自动计算并记录事件日志;若用户显式设置的值小于 0.7 × defaultTolerance,还会给出警告提示。
Deep Learning 的例外(源码细节)
从源码看,Deep Learning 对默认容差的处理有所不同:h2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java 中 defaultStoppingTolerance() 返回 0,同时其 _stopping_rounds 默认值为 5。这意味着在未显式设置 stopping_tolerance 时,Deep Learning 的早停要求"严格改进"(容差为 0)。这与官方参数文档中"通用默认 0.001"的描述存在实现层面的差异,实际使用 Deep Learning 时建议显式指定该参数以获得可预期的行为。
参数校验与使用前提
stopping_tolerance 不是独立生效的,它必须与 stopping_rounds 配合使用。H2O-3 在 h2o-core/src/main/java/hex/ModelBuilder.java 的参数校验阶段有明确约束:
if (_parms._stopping_tolerance < 0) {
error("_stopping_tolerance", "Stopping tolerance must be >= 0.");
}
if (_parms._stopping_tolerance >= 1) {
error("_stopping_tolerance", "Stopping tolerance must be < 1.");
}
if (_parms._stopping_rounds == 0) {
if (_parms._stopping_metric != ScoreKeeper.StoppingMetric.AUTO)
warn("_stopping_metric", "Stopping metric is ignored for _stopping_rounds=0.");
if (_parms._stopping_tolerance != _parms.defaultStoppingTolerance())
warn("_stopping_tolerance", "Stopping tolerance is ignored for _stopping_rounds=0.");
} else if (_parms._stopping_rounds < 0) {
error("_stopping_rounds", "Stopping rounds must be >= 0.");
}
归纳为以下三条使用前提:
- 取值范围:
stopping_tolerance必须满足0 <= value < 1,否则直接报错。 - 必须启用
stopping_rounds:只有stopping_rounds > 0时,stopping_metric和stopping_tolerance才会生效;若stopping_rounds = 0,这两个参数都会被忽略(并产生警告)。 - 指标与问题类型匹配:分类问题不能使用
deviance(GLM 除外),回归问题不能使用仅限分类的指标(如misclassification、mean_per_class_error);若使用自定义指标custom/custom_increasing进行早停,还必须同时定义custom_metric_func(见 h2o-core/src/main/java/hex/ModelBuilder.java)。
此外,h2o-core/src/main/java/water/api/schemas3/ModelParametersSchemaV3.java 中该参数的 REST API 定义也沿用了同一套语义:"长度 k 的简单移动平均在 k=stopping_rounds 次评分事件内未按 stopping_tolerance 改进则停止"。
与相关参数的关系
早停三件套中,stopping_tolerance 与另外两个参数协同工作:
| 参数 | 作用 | 关联文档 |
|---|---|---|
stopping_metric |
决定用哪个指标评估收敛(如 AUC、logloss、misclassification、deviance 等),其"越大越好/越小越好"方向决定了容差比较公式 | stopping_metric 参数文档 |
stopping_rounds |
决定观察多少个评分事件内的移动平均;容差只有在 stopping_rounds > 0 时才生效 |
stopping_rounds 参数文档 |
stopping_tolerance |
决定"相对改进要达到多少才算有进步",数值越小要求越严格、训练越久 | 本文档 |
三者共同定义了一个收敛判定:在连续 stopping_rounds 个评分窗口内,stopping_metric 的相对改进未超过 stopping_tolerance 即停止。在 AutoML 中,该参数同时作用于单个模型的训练与整个 AutoML 搜索流程的提前终止(见 h2o-py/h2o/automl/_estimator.py 的参数说明),R 端则映射到 build_control$stopping_criteria$stopping_tolerance(见 h2o-r/h2o-package/R/automl.R)。
完整实战示例(R 与 Python)
以下示例继承自官方参数文档,使用经典航空公司航班延误数据集(allyears2k_headers.zip)训练 GBM 分类模型,演示 stopping_tolerance 与 stopping_metric、stopping_rounds 的配合使用。目标是根据航班特征预测 IsDepDelayed(航班是否延误)。
R 版本
library(h2o)
h2o.init()
# import the airlines dataset:
# This dataset is used to classify whether a flight will be delayed 'YES' or not "NO"
# original data can be found at http://www.transtats.bts.gov/
airlines <- h2o.importFile("http://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
# convert columns to factors
airlines["Year"] <- as.factor(airlines["Year"])
airlines["Month"] <- as.factor(airlines["Month"])
airlines["DayOfWeek"] <- as.factor(airlines["DayOfWeek"])
airlines["Cancelled"] <- as.factor(airlines["Cancelled"])
airlines['FlightNum'] <- as.factor(airlines['FlightNum'])
# set the predictor names and the response column name
predictors <- c("Origin", "Dest", "Year", "UniqueCarrier", "DayOfWeek", "Month", "Distance", "FlightNum")
response <- "IsDepDelayed"
# split into train and validation
airlines_splits <- h2o.splitFrame(data = airlines, ratios = 0.8, seed = 1234)
train <- airlines_splits[[1]]
valid <- airlines_splits[[2]]
# try using the `stopping_tolerance` metric:
# train your model, where you specify the stopping_metric, stopping_rounds,
# and stopping_tolerance
airlines_gbm <- h2o.gbm(x = predictors, y = response, training_frame = train, validation_frame = valid,
stopping_metric = "AUC", stopping_rounds = 3,
stopping_tolerance = 1e-2, seed = 1234)
# print the auc for the validation data
print(h2o.auc(airlines_gbm, valid = TRUE))
Python 版本
import h2o
from h2o.estimators.gbm import H2OGradientBoostingEstimator
h2o.init()
h2o.cluster().show_status()
# import the airlines dataset:
# This dataset is used to classify whether a flight will be delayed 'YES' or not "NO"
# original data can be found at http://www.transtats.bts.gov/
airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
# convert columns to factors
airlines["Year"]= airlines["Year"].asfactor()
airlines["Month"]= airlines["Month"].asfactor()
airlines["DayOfWeek"] = airlines["DayOfWeek"].asfactor()
airlines["Cancelled"] = airlines["Cancelled"].asfactor()
airlines['FlightNum'] = airlines['FlightNum'].asfactor()
# set the predictor names and the response column name
predictors = ["Origin", "Dest", "Year", "UniqueCarrier", "DayOfWeek", "Month", "Distance", "FlightNum"]
response = "IsDepDelayed"
# split into train and validation sets
train, valid= airlines.split_frame(ratios = [.8], seed = 1234)
# try using the `stopping_tolerance` metric:
# train your model, where you specify the stopping_metric, stopping_rounds,
# and stopping_tolerance
# initialize the estimator then train the model
airlines_gbm = H2OGradientBoostingEstimator(stopping_metric = "auc", stopping_rounds = 3,
stopping_tolerance = 1e-2,
seed =1234)
airlines_gbm.train(x = predictors, y = response, training_frame = train, validation_frame = valid)
# print the auc for the validation data
airlines_gbm.auc(valid=True)
示例中 stopping_tolerance = 1e-2 表示:当验证集 AUC 的相对改进在连续 3 轮评分窗口内未超过 1% 时,GBM 停止生长新树。Python 端该参数在各类估算器上均有标准属性接口,例如 h2o-py/h2o/estimators/gbm.py 中的 stopping_tolerance getter/setter;R 端对应的 h2o.gbm() 参数定义见 h2o-r/h2o-package/R/gbm.R。
参数选择实操建议
基于上述源码机制,配置 stopping_tolerance 时可参考以下原则:
- 默认 0.001 适用于大多数中大规模数据集:该值既能有效抑制过拟合(模型不会在收敛平台期无限迭代),又不至于过早终止训练。
- 小数据集建议放宽容差:可以参考 AutoML 的公式
1/sqrt(行数 × 非NA比率)(钳制在[0.001, 0.05]),为小样本手动设置更大的容差,否则早停几乎不可能触发,等于白付额外训练时间。 - 与
stopping_rounds联动调整:stopping_rounds决定观察窗口长度,容差决定"改进多少算数"。窗口越长、容差越严,训练越充分但耗时越长;反之训练更快但可能过早收敛。 - 网格搜索中保持固定:由于该参数控制的是早停而非模型结构,官方文档建议在网格搜索中将其固定,把搜索预算留给树结构、正则化等真正影响模型容量的超参数。
- Isolation Forest 无需手动调小:其默认 0.01 已针对
anomaly_score指标校准,过小的容差会让默认收敛判定形同虚设。