ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

MLflow XGBoost 自动日志(Autologging)实战:从原生 Booster 到 Scikit-learn 模型的完整示例

MLflow XGBoost 自动日志(Autologging)实战:从原生 Booster 到 Scikit-learn 模型的完整示例 MLflow XGBoost 自动日志Autologging实战从原生 Booster 到 Scikit-learn 模型的完整示例【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflow导读本文基于 MLflow 仓库中的 examples/xgboost/README.md 及其两个配套示例系统讲解如何用mlflow.xgboost.autolog()一键自动记录 XGBoost 模型的超参数、训练过程指标、特征重要性、模型签名与产物覆盖xgboost.train()原生 API 与XGBRegressor等 Scikit-learn API 两种训练范式。读完本文你将掌握自动日志的启用方式、两类示例的可运行命令命令行、MLflow Projects 两种运行形态、自动记录的具体内容清单以及autolog()全部关键配置参数的语义与源码级实现原理。示例总览一个autolog()覆盖所有 XGBoost 模型examples/xgboost/README.md 开宗明义地指出仓库在examples/xgboost下提供了两个并列的示例目录分别演示 XGBoost 自动日志功能在两类 API 下的使用方式examples/xgboost/xgboost_native记录由xgboost.train()训练出的原生 Booster 模型学习 API / 原生 APIexamples/xgboost/xgboost_sklearn演示自动日志如何作用于XGBClassifier、XGBRegressor等 XGBoost Scikit-learn 模型Scikit-learn API。原文档特别强调了一个关键结论对于所有 XGBoost 模型而言启用自动日志的方式没有任何差别——mlflow.xgboost.autolog()对原生 Booster 和 Scikit-learn 模型全部适用。这一设计在源码中得到了印证mlflow/xgboost/init.py 的autolog()文档字符串明确写着 Note that thescikit-learn APIis now supported.即该函数同时补丁patch了xgboost.train、xgboost.Booster.train以及xgboost.sklearn下的各估计器。因此你不需要根据模型类型切换不同的启用函数只需一行mlflow.xgboost.autolog()。两个示例均包含完整的项目骨架train.py、MLproject、python_env.yaml既可以按普通 Python 脚本运行也可以作为可复现的 MLflow Project 运行下文逐一展开。示例一原生 API —— 用xgboost.train()训练鸢尾花分类器数据集与训练目标examples/xgboost/xgboost_native/train.py 使用 scikit-learn 内置的 Iris鸢尾花数据集做三分类按 8:2 划分训练集与测试集test_size0.2, random_state42将数据包装为 XGBoost 的DMatrix对象然后调用xgboost.train()训练多分类 Booster。核心超参数包括参数取值说明objectivemulti:softprob多分类目标输出各类别概率num_class3类别数learning_rate默认0.3可通过--learning-rate覆盖每轮提升步长eval_metricmlogloss评估指标多分类对数损失colsample_bytree默认1.0每棵树构造时的列采样比例subsample默认1.0训练实例的子采样比例seed42随机种子保证可复现启用自动日志的关键代码train.py中的启用逻辑只有两步import mlflow import mlflow.xgboost # 开启 XGBoost 自动日志 mlflow.xgboost.autolog() with mlflow.start_run(): model xgb.train(params, dtrain, evals[(dtrain, train)]) # ... 评估与手工补充指标 mlflow.log_metrics({log_loss: loss, accuracy: acc})值得注意的点autolog()必须在训练调用之前执行它会以补丁monkey-patch方式拦截xgboost.train等入口示例将训练包在mlflow.start_run()上下文中训练结束后又手工mlflow.log_metrics补充了log_loss与accuracy两个自定义指标——这说明自动日志与手动记录可以共存于同一个 run训练时通过evals[(dtrain, train)]指定验证集autologging 会据此在每一轮迭代记录评估指标详见下文自动记录内容。三种运行方式该示例支持脚本运行、参数调优实验、Project 运行三种形态详见 examples/xgboost/xgboost_native/README.md。1. 直接以脚本运行默认参数python train.py2. 通过命令行参数调参实验——示例建议尝试不同参数组合python train.py --learning-rate 0.2 --colsample-bytree 0.8 --subsample 0.9 python train.py --learning-rate 0.4 --colsample-bytree 0.7 --subsample 0.8命令行参数由parse_args()解析三个开关--learning-rate、--colsample-bytree、--subsample分别映射到训练params字典中的learning_rate、colsample_bytree、subsample。3. 以 MLflow Project 方式运行——利用目录下的 MLproject 声明文件MLflow 会自动按 python_env.yaml 创建环境并注入参数mlflow run . -P learning_rate0.2 -P colsample_bytree0.8 -P subsample0.9MLproject中定义了三个带默认值的入口参数entry_points: main: parameters: learning_rate: {type: float, default: 0.3} colsample_bytree: {type: float, default: 1.0} subsample: {type: float, default: 1.0} command: | python train.py \ --learning-rate{learning_rate} \ --colsample-bytree{colsample_bytree} \ --subsample{subsample}底层依赖由 python_env.yaml 声明mlflow、scikit-learn、matplotlib、xgboost其中matplotlib用于生成特征重要性图脚本中对应mpl.use(Agg)的无界面后端设置。在 MLflow UI 中对比实验示例 README 建议用如下命令启动跟踪服务然后在浏览器中打开 MLflow UI 对比各次 run 的参数与指标mlflow server默认情况下 UI 位于http://localhost:5000你可以按learning_rate/colsample_bytree/subsample等参数对 run 进行分组对比直观观察不同超参数组合对mlogloss、accuracy的影响。示例二Scikit-learn API —— 用XGBRegressor做糖尿病回归数据集与训练目标examples/xgboost/xgboost_sklearn/train.py 使用糖尿病diabetes数据集训练回归模型构建xgb.XGBRegressor(n_estimators20, reg_lambda1, gamma0, max_depth3)并通过eval_set[(X_test, y_test)]传入验证集供训练过程评估import xgboost as xgb from sklearn.datasets import load_diabetes from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from utils import fetch_logged_data import mlflow import mlflow.xgboost def main(): X, y load_diabetes(return_X_yTrue, as_frameTrue) X_train, X_test, y_train, y_test train_test_split(X, y) # enable auto logging # this includes xgboost.sklearn estimators mlflow.xgboost.autolog() regressor xgb.XGBRegressor(n_estimators20, reg_lambda1, gamma0, max_depth3) regressor.fit(X_train, y_train, eval_set[(X_test, y_test)]) y_pred regressor.predict(X_test) mean_squared_error(y_test, y_pred) run_id mlflow.last_active_run().info.run_id print(fLogged data and model in run {run_id}) # show logged data for key, data in fetch_logged_data(run_id).items(): print(f\n---------- logged {key} ----------) pprint(data)代码注释this includes xgboost.sklearn estimators再次印证了原文档的结论mlflow.xgboost.autolog()同样覆盖 Scikit-learn 风格的估计器。训练完成后脚本用mlflow.last_active_run()拿到自动创建的 run ID并通过utils.fetch_logged_data()把该 run 下记录的参数、指标、标签tags与产物artifacts逐类打印出来方便在没有 UI 的环境下直接核对自动日志结果。查看自动记录的数据fetch_logged_data 的实现examples/xgboost/xgboost_sklearn/utils.py 实现了通用的 run 数据读取工具其要点from mlflow.tracking import MlflowClient def yield_artifacts(run_id, pathNone): client MlflowClient() for item in client.list_artifacts(run_id, path): if item.is_dir: yield from yield_artifacts(run_id, item.path) else: yield item.path def fetch_logged_data(run_id): client MlflowClient() data client.get_run(run_id).data # Exclude system tags: https://www.mlflow.org/docs/latest/tracking.html#system-tags tags {k: v for k, v in data.tags.items() if not k.startswith(mlflow.)} artifacts list(yield_artifacts(run_id)) return { params: data.params, metrics: data.metrics, tags: tags, artifacts: artifacts, }通过MlflowClient.get_run()获取 run 的params/metrics/tags其中系统标签以mlflow.前缀开头如mlflow.runName被过滤掉只保留用户可见标签yield_artifacts递归遍历list_artifacts的目录树收集该 run 下所有产物的相对路径如model/MLmodel、feature_importance_weight.png等。该示例同样可以python train.py直接运行其 MLproject 仅声明了python train.py一个入口依赖声明在 python_env.yamlmlflow、pandas、scikit-learn、xgboost。自动日志到底记录了什么autolog() 的行为契约从 mlflow/xgboost/init.py 中 autolog() 的文档字符串可以确认调用mlflow.xgboost.autolog()后会自动记录以下内容训练超参数xgboost.train()或 Scikit-learn 估计器的fit()接收的参数作为 run 的params记录逐迭代评估指标指定evals原生 API或eval_setScikit-learn API时每个训练迭代的指标都会被记录最优迭代指标指定early_stopping_rounds原生 API或early_stopping_rounds/callbacksScikit-learn API时记录最佳迭代处的指标特征重要性以 JSON 文件与图表plot两种形式落盘为产物默认记录weight类型见importance_types参数训练好的模型本身包括有效的输入示例input example推理出的模型输入输出签名model signature。源码同时展示了输入示例的采集机制autolog()会补丁DMatrix.__init__在构造时复制数据前若干行作为输入示例源码中对应INPUT_EXAMPLE_SAMPLE_ROWS并存储到DMatrix对象上供训练函数读取——因为训练完成后无法再从DMatrix反推原始数据。若数据来自文件字符串则会记录错误信息而不是直接失败。这些行为契约在 tests/xgboost/test_xgboost_autolog.py 中都有对应测试验证例如test_xgb_autolog_logs_default_params/test_xgb_autolog_logs_specified_params验证默认参数与显式指定参数均被记录test_xgb_autolog_logs_metrics_with_validation_data/test_xgb_autolog_logs_metrics_with_early_stopping验证带验证集、带早停时的指标记录test_xgb_autolog_logs_feature_importance/test_xgb_autolog_logs_specified_feature_importance验证特征重要性的记录与类型控制test_xgb_autolog_infers_model_signature_correctly验证模型签名推断正确性test_xgb_autolog_sklearn与test_xgb_autolog_sklearn_nested_in_pipeline验证 Scikit-learn 估计器含管道嵌套场景下的自动日志test_xgb_autolog_does_not_throw_if_importance_values_not_supported等异常路径测试验证在线性 Booster 或不支持重要性值时不抛异常。autolog() 完整配置参数速查下面依据 mlflow/xgboost/init.py 的 autolog 签名整理出全部可配置参数及其语义方便你在实际工程中按需开启参数默认值作用说明importance_typesNone实际回退为[weight]记录哪些类型的特征重要性支持weight、gain、cover、total_gain、total_cover等多类型用列表传入log_input_examplesFalse是否在模型产物中附带训练数据的输入示例仅当log_modelsTrue时生效log_model_signaturesTrue是否记录推理出的模型输入/输出签名仅当log_modelsTrue时生效log_modelsTrue是否把训练好的模型保存为 MLflow 模型产物为False时输入示例与签名也随之省略log_datasetsTrue是否记录训练/验证数据集信息dataset 标签与内容可用于下游数据集溯源disableFalse为True时关闭 XGBoost 自动日志集成exclusiveFalse为True时自动日志内容不会写入用户手动创建的 runfluent run而是仅写入自动创建的 rundisable_for_unsupported_versionsFalse为True时对未经当前 MLflow 客户端测试或不适配的 XGBoost 版本自动禁用 autologgingsilentFalse为True时抑制 MLflow 在自动日志期间的所有事件日志与警告registered_model_nameNone给定名字时每次训练结束自动把模型注册为指定 Registered Model 的新版本不存在则创建model_formatubj模型保存格式默认为ubjUBJSON官方推荐的高性能跨平台格式也支持json与xgbextra_tagsNone为自动日志创建的每个 managed run 附加的额外标签字典常用进阶用法举例结合上述参数工程实践中常见的组合写法包括import mlflow.xgboost mlflow.xgboost.autolog( importance_types[weight, gain], # 记录两类特征重要性 log_input_examplesTrue, # 附带输入示例 log_model_signaturesTrue, # 记录模型签名 registered_model_nameiris_xgb, # 训练后自动注册模型 model_formatubj, # 使用推荐的 UBJSON 格式 extra_tags{team: ml-platform}, # 附加自定义标签 )源码层面autolog()的补丁目标同时包含原生train与 Scikit-learn 估计器且对 1.3.0 及以上版本使用xgboost.callback.TrainingCallback子类AutologCallback收集逐迭代指标旧版本则回退到 picklable 回调包装见 源码 train_impl 的 callback 分支因此无需在业务代码里插入任何指标记录逻辑。从示例走向生产结合模型注册与加载示例本身聚焦训练 自动记录但既然autolog()已把模型以 MLflow 格式落盘你便可以无缝衔接 MLflow 的模型注册与加载能力通过registered_model_name让每次训练自动创建/更新注册模型版本对应测试 test_sklearn_api_autolog_registering_model 与test_xgb_api_autolog_registering_model之后用mlflow.xgboost.load_model()或mlflow.pyfunc.load_model()加载产物用于推理或部署需要对比多个 run 时启动mlflow server在 UI 中按参数分组、并排查看指标曲线与特征重要性图。若你的项目中同时存在原生 API 与 Scikit-learn API 两种写法也无需分别配置——正如原文档与源码反复强调的统一调用一次mlflow.xgboost.autolog()即可全部覆盖。参考与延伸阅读示例入口文档examples/xgboost/README.md原生 API 示例examples/xgboost/xgboost_native/train.py、MLproject、python_env.yamlScikit-learn API 示例examples/xgboost/xgboost_sklearn/train.py、utils.py、MLproject、python_env.yaml自动日志核心实现mlflow/xgboost/init.py 的 autolog()自动日志行为测试tests/xgboost/test_xgboost_autolog.py【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflow创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表