You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LightGBM训练API如何在保留内置指标时仅用自定义指标早停

LightGBM原生训练API实现自定义指标早停+跟踪内置指标的解决方案

LightGBM 3.x 原生训练API确实不支持在params的metric配置中混传自定义可调用对象和内置指标名,但你要的需求可以通过early_stopping_metric参数轻松实现,无需更换API,也无需自行实现内置指标。

核心实现逻辑

  1. 在params的metric参数中配置所有你需要跟踪的内置评估指标
  2. 通过feval参数传入自定义评估指标,注意自定义指标需要返回(指标名称, 指标值, 是否越大越好)格式的三元组
  3. 在lgb.train()中添加early_stopping_metric参数,值设为你的自定义指标返回的指标名称,早停就只会基于该指标触发,其他所有内置指标仍会正常输出和记录

完整示例代码

import lightgbm as lgb
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

# 自定义评估指标示例
def my_eval_metric(y_pred, y_true):
    y_pred_label = np.where(y_pred > 0.5, 1, 0)
    acc = np.mean(y_pred_label == y_true.get_label())
    # 返回格式要求:(指标名, 指标计算结果, 该指标是否越大越好)
    return "my_custom_acc", acc, True

# 构造测试数据集
X, y = make_classification(n_samples=10000, n_features=20, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
d_train = lgb.Dataset(X_train, y_train)
d_val = lgb.Dataset(X_val, y_val, reference=d_train)

# 训练参数配置
params = {
    "objective": "binary",
    "boosting_type": "gbdt",
    # 配置需要跟踪的所有内置指标
    "metric": ["binary_logloss", "auc"],
    "learning_rate": 0.01,
    "seed": 42
}

evals_result = {}
model = lgb.train(
    params,
    d_train,
    num_boost_round=1000,
    valid_sets=[d_val],
    # 传入自定义评估指标
    feval=my_eval_metric,
    early_stopping_rounds=20,
    # 关键配置:指定早停仅参考自定义指标
    early_stopping_metric="my_custom_acc",
    evals_result=evals_result,
    verbose_eval=10
)

效果验证

  • 训练日志会同时输出binary_logloss、auc、my_custom_acc三个指标的实时值
  • 早停仅会判断my_custom_acc是否连续20轮没有提升,不受其他指标波动影响
  • 所有指标的训练历史都会完整保存在evals_result中,可后续提取分析

版本兼容性说明

early_stopping_metric参数在LightGBM 2.3.0及以上版本均支持,你使用的3.2.1版本可以直接使用。

内容的提问来源于stack exchange,提问作者Kyle Parsons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:24:02