Modeling / Pipeline¶
快速迭代模块
Modeling 建模和 Pipeline 编排仍在快速迭代中,接口约定、结果对象和调参参数后续可能发生较大变化。生产流程建议固定版本,并在升级前检查返回对象和字段名称。
能力索引¶
| 能力 | 主要入口 | 说明 |
|---|---|---|
| Pipeline 编排 | MarsModelingPipeline / MarsSelectionStep / MarsWOEBinningStep / MarsModelingStep |
串联多层筛选、可选 WOE 分箱和最终建模 |
| 样本切分 | MarsModelingSession.slice / MarsModelDataSplitter |
按时间严格切分 train/val/oot,或为长短 y 生成独立切片列 |
| 模型调参 | MarsModelingSession.tune / MarsModelTuner.tune |
支持 XGBoost、LightGBM、CatBoost、Logistic Regression |
| 指标体系 | optimize_metric / custom_metrics |
内置 auc、ks、f1,支持自定义 metric 和 maximize/minimize |
| 调参产物 | artifact_dir |
每次调参生成独立目录;artifact_dir=None 表示完全不落盘 |
| 模型保留 | keep_top_n_models |
调参过程中动态保留当前最优 N 个有效 trial 模型 |
| Replay | MarsModelReplayRunner.replay |
支持 Top-K replay,也支持 trial_nums=[...] 指定编号 replay |
| 特征重要性 | importance_methods |
默认 native importance,显式请求可计算 SHAP importance |
| 多口径评估 | benchmark_cols / aux_targets / target_group_cols |
多 benchmark、多辅助 target 和长短 y 独立评估 |
| PSI 口径 | psi_include_missing |
建模评估复用分箱评估器计算 Score/Feature PSI,只控制缺失箱是否纳入 |
Pipeline 编排¶
mars.pipeline.MarsModelingPipeline ¶
串联特征筛选、可选 WOE 分箱和 Modeling 建模的高层 Pipeline 编排器。
Pipeline 面向风控建模宽表场景,默认保持树模型链路简单:先筛选特征,再进入建模。
LR 或评分卡链路可以显式加入 MarsWOEBinningStep,把原始特征转换为 *_woe 后再筛选
或建模。该类不是 sklearn Pipeline 的严格子类,但保留熟悉的 fit、transform 和
predict 调用方式。
示例:
>>> from mars.feature import MarsStatsSelector
>>> pipeline = MarsModelingPipeline(
... target="target",
... features=["age"],
... steps=[MarsSelectionStep(name="stats", selector=MarsStatsSelector(skip_fine_scan=True))],
... )
>>> pipeline.features
['age']
__init__ ¶
初始化建模编排器并校验 step 拓扑。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
target
|
str
|
建模主目标列。 |
必需 |
features
|
Sequence[str]
|
初始候选特征列。 |
必需 |
steps
|
Sequence[MarsPipelineStep]
|
按顺序执行的 step 列表。 |
必需 |
fit ¶
按 step 顺序拟合 Pipeline 并返回结构化结果。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
FrameLike
|
包含特征、目标列以及可选切片列的建模样本。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
MarsPipelineResult
|
Pipeline 执行结果,包含最终特征、每步报告和建模调参结果。 |
transform ¶
使用已拟合的分箱和筛选步骤转换样本。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
FrameLike
|
待转换样本。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
DataFrame or DataFrame
|
保留原始上下文列,并追加已拟合 WOE 特征后的样本。返回类型尽量与输入一致。 |
predict ¶
对新样本执行 Pipeline 转换并追加模型预测分。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
FrameLike
|
待打分样本。 |
必需 |
pred_col
|
str
|
预测分列名。 |
'pred_score'
|
inplace
|
bool
|
当输入为 Pandas DataFrame 时,是否允许在输入对象上原地写入预测列。 |
False
|
返回:
| 类型 | 描述 |
|---|---|
DataFrame or DataFrame
|
追加预测分后的样本。 |
引发:
| 类型 | 描述 |
|---|---|
RuntimeError
|
Pipeline 尚未拟合或没有 modeling step 时抛出。 |
mars.pipeline.MarsPipelineStep ¶
Bases: ABC
Pipeline step 抽象基类。
子类负责管理自身的 fit_transform 和 transform 生命周期;Pipeline 主类只负责
调度、拓扑校验和最终结果组装。
fit_transform
abstractmethod
¶
fit_transform(df: DataFrame, *, target: str, active_features: Sequence[str], pipeline_state: MutableMapping[str, Any]) -> tuple[pl.DataFrame, list[str], MarsStepResult]
拟合当前 step,并返回转换后的数据、active features 和 step 结果。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame
|
当前 Pipeline 工作表。 |
必需 |
target
|
str
|
建模主目标列。 |
必需 |
active_features
|
Sequence[str]
|
当前 step 可消费的特征列。 |
必需 |
pipeline_state
|
MutableMapping[str, Any]
|
Pipeline 级可变状态,例如特征映射和是否已执行 WOE step。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple of polars.DataFrame, list of str, MarsStepResult
|
转换后的工作表、更新后的 active features 和 step 结果。 |
transform
abstractmethod
¶
transform(df: DataFrame, *, active_features: Sequence[str], pipeline_state: MutableMapping[str, Any]) -> tuple[pl.DataFrame, list[str]]
使用已拟合状态转换新样本。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame
|
当前 Pipeline 工作表。 |
必需 |
active_features
|
Sequence[str]
|
当前 step 可消费的特征列。 |
必需 |
pipeline_state
|
MutableMapping[str, Any]
|
Pipeline 级可变状态。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple of polars.DataFrame and list of str
|
转换后的工作表和更新后的 active features。 |
mars.pipeline.MarsSelectionStep ¶
Bases: MarsPipelineStep
Pipeline 中的特征筛选 step。
该 step 可以在同一个 Pipeline 中出现多次,每一步都只消费上一阶段输出的 active features。
__init__ ¶
__init__(name: str, selector: MarsBaseSelector, fit_params: Mapping[str, Any] | None = None) -> None
初始化筛选 step。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
name
|
str
|
step 唯一名称。 |
必需 |
selector
|
MarsBaseSelector
|
已配置好筛选策略的 MARS selector。 |
必需 |
fit_params
|
Mapping[str, Any] | None
|
传给 selector |
None
|
fit_transform ¶
fit_transform(df: DataFrame, *, target: str, active_features: Sequence[str], pipeline_state: MutableMapping[str, Any]) -> tuple[pl.DataFrame, list[str], MarsStepResult]
拟合 selector 并输出新的 active features。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame
|
当前 Pipeline 工作表。 |
必需 |
target
|
str
|
建模主目标列。 |
必需 |
active_features
|
Sequence[str]
|
当前候选特征列。 |
必需 |
pipeline_state
|
MutableMapping[str, Any]
|
Pipeline 级状态;筛选 step 当前只读该状态。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple of polars.DataFrame, list of str, MarsStepResult
|
原工作表、筛选后的 active features 和 step 结果。 |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
当前 step 筛空所有特征时抛出。 |
transform ¶
transform(df: DataFrame, *, active_features: Sequence[str], pipeline_state: MutableMapping[str, Any]) -> tuple[pl.DataFrame, list[str]]
转换阶段不裁剪工作表,只更新 active features。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame
|
当前 Pipeline 工作表。 |
必需 |
active_features
|
Sequence[str]
|
当前 active features。 |
必需 |
pipeline_state
|
MutableMapping[str, Any]
|
Pipeline 级状态;筛选 step 当前只读该状态。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple of polars.DataFrame and list of str
|
原工作表和拟合阶段保存的 selected features。 |
mars.pipeline.MarsWOEBinningStep ¶
Bases: MarsPipelineStep
Pipeline 中显式生成 WOE 特征的分箱 step。
该 step 主要服务 LR 和评分卡链路;树模型可以显式使用,但不作为默认推荐路径。
__init__ ¶
__init__(name: str, binner: MarsBinnerBase, cat_features: Sequence[str] | None = None, woe_batch_size: int = 200) -> None
初始化 WOE 分箱 step。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
name
|
str
|
step 唯一名称。 |
必需 |
binner
|
MarsBinnerBase
|
已配置好分箱策略的 MARS binner。 |
必需 |
cat_features
|
Sequence[str] | None
|
当前 active features 中需要按类别特征处理的列。 |
None
|
woe_batch_size
|
int
|
WOE 映射物化时的批大小。 |
200
|
fit_transform ¶
fit_transform(df: DataFrame, *, target: str, active_features: Sequence[str], pipeline_state: MutableMapping[str, Any]) -> tuple[pl.DataFrame, list[str], MarsStepResult]
拟合分箱器并追加 WOE 特征列。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame
|
当前 Pipeline 工作表。 |
必需 |
target
|
str
|
建模主目标列。 |
必需 |
active_features
|
Sequence[str]
|
当前需要分箱的特征列。 |
必需 |
pipeline_state
|
MutableMapping[str, Any]
|
Pipeline 级状态,会在本步骤更新 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple of polars.DataFrame, list of str, MarsStepResult
|
追加 WOE 列后的工作表、WOE 特征列和 step 结果。 |
transform ¶
transform(df: DataFrame, *, active_features: Sequence[str], pipeline_state: MutableMapping[str, Any]) -> tuple[pl.DataFrame, list[str]]
使用已拟合分箱器追加 WOE 特征列。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame
|
当前 Pipeline 工作表。 |
必需 |
active_features
|
Sequence[str]
|
当前需要转换的特征列。 |
必需 |
pipeline_state
|
MutableMapping[str, Any]
|
Pipeline 级状态,会在本步骤更新 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple of polars.DataFrame and list of str
|
追加 WOE 列后的工作表和 WOE 特征列。 |
mars.pipeline.MarsModelingStep ¶
Bases: MarsPipelineStep
Pipeline 中的最终建模 step。
该 step 最多出现一次,且必须位于 Pipeline 最后。
__init__ ¶
__init__(name: str, model_type: str, *, time_col: str | None = None, split_ratios: Mapping[str, float] | None = None, dataset_flag_col: str = 'dataset_flag', categorical_features: Sequence[str] | None = None, optimize_metric: str = 'ks', seed: int = 1206, tune_params: Mapping[str, Any] | None = None, slice_params: Mapping[str, Any] | None = None) -> None
初始化建模 step。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
name
|
str
|
step 唯一名称。 |
必需 |
model_type
|
str
|
建模后端类型,例如 |
必需 |
time_col
|
str | None
|
需要自动切分样本时使用的时间列。 |
None
|
split_ratios
|
Mapping[str, float] | None
|
训练、验证和 OOT 的切分比例;与 |
None
|
dataset_flag_col
|
str
|
建模样本切片列名。 |
'dataset_flag'
|
categorical_features
|
Sequence[str] | None
|
进入建模后端的类别特征列。若上游已生成 WOE 特征,通常应保持为空。 |
None
|
optimize_metric
|
str
|
调参优化指标。 |
'ks'
|
seed
|
int
|
随机种子。 |
1206
|
tune_params
|
Mapping[str, Any] | None
|
传给 |
None
|
slice_params
|
Mapping[str, Any] | None
|
传给 |
None
|
fit_transform ¶
fit_transform(df: DataFrame, *, target: str, active_features: Sequence[str], pipeline_state: MutableMapping[str, Any]) -> tuple[pl.DataFrame, list[str], MarsStepResult]
基于最终 active features 创建 session 并执行调参。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame
|
当前 Pipeline 工作表。 |
必需 |
target
|
str
|
建模主目标列。 |
必需 |
active_features
|
Sequence[str]
|
最终进入建模的特征列。 |
必需 |
pipeline_state
|
MutableMapping[str, Any]
|
Pipeline 级状态;如果已经执行 WOE step,LR 会按 numeric 模式消费外部 WOE 列;否则 LR 会启用后端自身的 WOE 转换。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple of polars.DataFrame, list of str, MarsStepResult
|
建模工作表、建模特征列和 step 结果。 |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
建模特征为空、切分参数不完整或缺少 dataset flag 时抛出。 |
transform ¶
transform(df: DataFrame, *, active_features: Sequence[str], pipeline_state: MutableMapping[str, Any]) -> tuple[pl.DataFrame, list[str]]
建模 step 在普通 transform 中不打分,只透传样本和 active features。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame
|
当前 Pipeline 工作表。 |
必需 |
active_features
|
Sequence[str]
|
最终建模特征列。 |
必需 |
pipeline_state
|
MutableMapping[str, Any]
|
Pipeline 级状态;当前只读该状态。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple of polars.DataFrame and list of str
|
原工作表和原 active features。 |
mars.pipeline.MarsPipelineResult
dataclass
¶
MarsModelingPipeline 的结构化运行结果。
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
active_features |
list of str
|
Pipeline 最终输出、并进入建模阶段的特征列。 |
selected_features |
list of str
|
最后一层筛选或 WOE 转换后的特征列。 |
feature_map |
dict of str to str
|
原始特征到派生特征的映射,例如 |
step_results |
list of MarsStepResult
|
每个 step 的输入、输出、剔除特征、报告和元数据。 |
modeling_result |
MarsModelTuningResult | None
|
建模 step 的调参结果;Pipeline 不包含建模 step 时为 |
metadata |
dict of str to Any
|
Pipeline 级元数据。 |
mars.pipeline.MarsStepResult
dataclass
¶
单个 Pipeline step 的结构化执行结果。
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
name |
str
|
step 名称。 |
step_type |
str
|
step 类型,当前包括 |
input_features |
list of str
|
step 执行前的 active features。 |
output_features |
list of str
|
step 执行后的 active features。 |
dropped_features |
list of str
|
本 step 从 active features 中剔除的特征。 |
report |
Any
|
step 产生的报告对象或明细表;无报告时为 |
metadata |
dict of str to Any
|
step 级元数据。 |
Session¶
mars.modeling.MarsModelingSession ¶
组织切分、调参、评估和 replay 的会话级门面。
last_feature_growth_run
property
¶
返回最近一次特征增长调参结果。
__init__ ¶
__init__(*, model_type: str, features: Sequence[str], target: str, dataset_flag_col: str = 'dataset_flag', categorical_features: Sequence[str] | None = None, optimize_metric: str = 'ks', seed: int = 1206, lr_feature_mode: str = 'numeric', lr_binning_type: str = 'native', lr_binner_kwargs: Mapping[str, Any] | None = None, lr_binner: Any | None = None) -> None
初始化建模会话。
slice ¶
slice(df: FrameLike, *, time_col: str, split_ratios: Mapping[str, float], target: str | None = None, mode: str = 'strict', train_key: str = 'train', val_key: str = 'val', random_seed: int = 42) -> FrameLike
生成带 dataset flag 的切分样本。
tune ¶
tune(df: FrameLike, *, param_space: Mapping[str, Any] | None = None, max_diff: float = 3.0, use_oot_penalty: bool = False, n_trials: int = 50, startup_trials: int = 20, warmup_steps: int = 100, num_boost_round: int = 500, early_stopping_rounds: int = 50, metric_params: Mapping[str, Any] | None = None, custom_metrics: Mapping[str, MetricCallable] | None = None, metric_directions: Mapping[str, MetricDirection] | None = None, training_metric: str | None = None, backend_metric: Any | None = None, keep_top_n_models: int = 5, artifact_dir: str | Path | None = 'modeling_artifacts', importance_methods: Sequence[Literal['native', 'shap']] = ('native',), shap_sample_size: int = 5000, shap_background_size: int = 1000, overwrite: bool = False) -> MarsModelTuningResult
执行单次调参。
tune_incrementally ¶
tune_incrementally(df: FrameLike, *, steps: Sequence[int] | None = None, feature_order: Sequence[str] | None = None, importance_table: DataFrame | None = None, min_features: int = 10, max_features: int | None = None, step_size: int | None = None, mode: str = 'prefix', selection_metric: str | None = None, **tune_kwargs: Any) -> MarsFeatureGrowthResult
按特征数量递增执行多轮调参。
evaluate ¶
evaluate(df: FrameLike, *, pred_col: str, benchmark_col: str | None = None, benchmark_cols: Sequence[str] | None = None, time_col: str | None = None, val_target: str | None = None, aux_targets: Sequence[str] | None = None, target_group_cols: Mapping[str, str] | None = None, feature_cols: Sequence[str] | None = None, importance_table: DataFrame | None = None, psi_include_missing: bool = False) -> MarsModelingReport
基于预测分生成模型评估报告。
replay ¶
replay(tuning_result: MarsModelTuningResult, df: FrameLike, *, top_k: int = 5, sort_metric: str = 'ks', include_val: bool = True, trial_nums: Sequence[int] | None = None, retrain: bool = True, num_boost_round: int = 500, early_stopping_rounds: int = 50, optimize_metric: str | None = None, metric_params: Mapping[str, Any] | None = None, custom_metrics: Mapping[str, MetricCallable] | None = None, metric_directions: Mapping[str, MetricDirection] | None = None, training_metric: str | None = None, backend_metric: Any | None = None, benchmark_col: str | None = None, benchmark_cols: Sequence[str] | None = None, time_col: str | None = None, val_target: str | None = None, aux_targets: Sequence[str] | None = None, target_group_cols: Mapping[str, str] | None = None, psi_include_missing: bool = False) -> MarsModelReplayResult
基于调参结果执行 replay、重训和重评估。
Data Splitter¶
mars.modeling.MarsModelDataSplitter ¶
Bases: PandasSplitterMixin, PolarsSplitterMixin
无状态的建模样本切分入口。
split_by_time_strictly ¶
split_by_time_strictly(df: FrameLike, *, time_col: str, target: str, split_ratios: dict[str, float], dataset_flag_col: str = 'dataset_flag') -> FrameLike
按时间顺序严格切分 train/val/oot。
split_hybrid_random_val ¶
split_hybrid_random_val(df: FrameLike, *, time_col: str, target: str, split_ratios: dict[str, float], dataset_flag_col: str = 'dataset_flag', train_key: str = 'train', val_key: str = 'val', random_seed: int = 42) -> FrameLike
在建模窗口内随机切 train/val,其余切片仍按时间顺序。
split_by_target_observation ¶
split_by_target_observation(df: FrameLike, *, time_col: str, target: str, split_ratios: dict[str, float], aux_targets: Sequence[str] | None = None, dataset_flag_col: str = 'dataset_flag', aux_dataset_flag_suffix: str = '__dataset_flag') -> FrameLike
为主目标和辅助目标生成各自独立的切片列。
Tuning¶
mars.modeling.MarsModelTuner ¶
二分类风险模型调参工具。
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
spec |
ModelingSpec
|
当前调参任务的建模规格。 |
last_run |
MarsModelTuningResult or None
|
最近一次调参结果。 |
示例:
>>> tuner = MarsModelTuner(model_type="xgb", features=["age"], target="y")
>>> tuner.spec.optimize_metric
'ks'
best_model
property
¶
best_score
property
¶
best_params
property
¶
history_table
property
¶
__init__ ¶
__init__(*, model_type: str, features: Sequence[str], target: str, dataset_flag_col: str = 'dataset_flag', categorical_features: Sequence[str] | None = None, optimize_metric: str = 'ks', seed: int = 1206, lr_feature_mode: str = 'numeric', lr_binning_type: str = 'native', lr_binner_kwargs: Mapping[str, Any] | None = None, lr_binner: Any | None = None) -> None
初始化 Modeling Pipeline 调参器。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model_type
|
str
|
模型后端类型。 |
必需 |
features
|
Sequence[str]
|
建模特征列。 |
必需 |
target
|
str
|
目标列名。 |
必需 |
dataset_flag_col
|
str
|
样本切片标记列名。 |
'dataset_flag'
|
categorical_features
|
Sequence[str] | None
|
类别特征列。 |
None
|
optimize_metric
|
str
|
调参优化指标。 |
'ks'
|
seed
|
int
|
随机种子。 |
1206
|
lr_feature_mode
|
str
|
LR 特征模式。 |
'numeric'
|
lr_binning_type
|
str
|
LR WOE 模式使用的分箱器类型,支持 |
'native'
|
lr_binner_kwargs
|
Mapping[str, Any] | None
|
构造 LR 分箱器时使用的参数。 |
None
|
lr_binner
|
Any | None
|
显式复用的 LR 分箱器实例。 |
None
|
tune ¶
tune(df: FrameLike, *, param_space: Mapping[str, Any] | None = None, max_diff: float = 3.0, use_oot_penalty: bool = False, n_trials: int = 50, startup_trials: int = 20, warmup_steps: int = 100, num_boost_round: int = 500, early_stopping_rounds: int = 50, metric_params: Mapping[str, Any] | None = None, custom_metrics: Mapping[str, MetricCallable] | None = None, metric_directions: Mapping[str, MetricDirection] | None = None, training_metric: str | None = None, backend_metric: Any | None = None, keep_top_n_models: int = 5, artifact_dir: str | Path | None = 'modeling_artifacts', importance_methods: Sequence[Literal['native', 'shap']] = ('native',), shap_sample_size: int = 5000, shap_background_size: int = 1000, overwrite: bool = False) -> MarsModelTuningResult
调优一个模型后端并返回可复用的建模调优结果。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
FrameLike
|
已经带有 train、validation、OOT 切片标记的建模样本。 |
必需 |
param_space
|
Mapping[str, Any] | None
|
对后端搜索空间的覆盖或扩展。 |
None
|
max_diff
|
float
|
泛化衰减阈值,单位是百分点。 |
3.0
|
use_oot_penalty
|
bool
|
是否将 OOT 衰减纳入 trial 有效性判断。 |
False
|
n_trials
|
int
|
Optuna 试验次数。 |
50
|
startup_trials
|
int
|
剪枝器开始工作前的预热试验次数。 |
20
|
warmup_steps
|
int
|
剪枝器预热步数。 |
100
|
num_boost_round
|
int
|
最大 boosting 轮数。 |
500
|
early_stopping_rounds
|
int
|
early stopping 轮数。 |
50
|
metric_params
|
Mapping[str, Any] | None
|
指标参数,例如 |
None
|
custom_metrics
|
Mapping[str, MetricCallable] | None
|
用户自定义指标函数字典。 |
None
|
metric_directions
|
Mapping[str, MetricDirection] | None
|
指标排序方向。 |
None
|
training_metric
|
str | None
|
模型后端训练期监控指标。 |
None
|
backend_metric
|
Any | None
|
透传给模型后端原生训练接口的自定义 metric。 |
None
|
keep_top_n_models
|
int
|
调参过程中动态保留的最优模型数量。 |
5
|
artifact_dir
|
str | Path | None
|
调参产物根目录; |
'modeling_artifacts'
|
importance_methods
|
Sequence[Literal['native', 'shap']]
|
特征重要性计算方式。 |
('native',)
|
shap_sample_size
|
int
|
计算 SHAP values 的最大样本量。 |
5000
|
shap_background_size
|
int
|
SHAP 背景样本量。 |
1000
|
overwrite
|
bool
|
保留参数;当前每次调参都会创建独立运行目录。 |
False
|
返回:
| 类型 | 描述 |
|---|---|
MarsModelTuningResult
|
包含最佳模型、调参历史、训练配置和元数据的建模调优结果。 |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
当指标、重要性方法或输入配置不合法时抛出。 |
ImportError
|
当当前功能依赖的可选组件不可用时抛出。 |
RuntimeError
|
当底层训练、评估或导出流程失败时抛出。 |
Exception
|
第三方依赖在调参期间抛出的未包装异常会继续向上抛出。 |
mars.modeling.MarsModelReplayRunner ¶
基于 MarsModelTuningResult 回放调参结果。
MarsModelReplayRunner 不在构造函数中绑定模型类型、特征列或目标列,而是从
:meth:replay 传入的调优结果中读取建模规格。回放候选既可以按 Top-K 自动选择,
也可以由调用者传入 trial 编号。benchmark 分数、时间列和辅助验证目标属于本次
replay 评估上下文,因此保留在方法入参中。
示例:
replay ¶
replay(tuning_result: MarsModelTuningResult, df: FrameLike, *, top_k: int = 5, sort_metric: str = 'ks', include_val: bool = True, trial_nums: Sequence[int] | None = None, retrain: bool = True, num_boost_round: int = 500, early_stopping_rounds: int = 50, optimize_metric: str | None = None, metric_params: Mapping[str, Any] | None = None, custom_metrics: Mapping[str, MetricCallable] | None = None, metric_directions: Mapping[str, MetricDirection] | None = None, training_metric: str | None = None, backend_metric: Any | None = None, benchmark_col: str | None = None, benchmark_cols: Sequence[str] | None = None, time_col: str | None = None, val_target: str | None = None, aux_targets: Sequence[str] | None = None, target_group_cols: Mapping[str, str] | None = None, psi_include_missing: bool = False) -> MarsModelReplayResult
回放 Top-K 或指定 trial,并生成模型、打分数据和评估报告。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
tuning_result
|
MarsModelTuningResult
|
提供模型类型、特征列、目标列和样本切片配置的调优结果。 |
必需 |
df
|
FrameLike
|
用于重新训练和打分的样本表。 |
必需 |
top_k
|
int
|
要回放的 trial 数量。 |
5
|
sort_metric
|
str
|
replay 排行表排序指标。 |
'ks'
|
include_val
|
bool
|
是否将 validation 切片指标纳入平均排序。 |
True
|
trial_nums
|
Sequence[int] | None
|
指定要 replay 的 trial 编号;传入后按给定顺序回放, |
None
|
retrain
|
bool
|
是否使用 trial 参数重新训练; |
True
|
num_boost_round
|
int
|
当调优结果中没有保存该配置时使用的最大 boosting 轮数。 |
500
|
early_stopping_rounds
|
int
|
当调优结果中没有保存该配置时使用的 early stopping 轮数。 |
50
|
optimize_metric
|
str | None
|
覆盖 replay 后端使用的优化指标。 |
None
|
metric_params
|
Mapping[str, Any] | None
|
指标参数,例如 |
None
|
custom_metrics
|
Mapping[str, MetricCallable] | None
|
replay 重训时使用的自定义指标函数字典。 |
None
|
metric_directions
|
Mapping[str, MetricDirection] | None
|
指标排序方向;会影响 Top-K trial 选择和自定义指标 replay。 |
None
|
training_metric
|
str | None
|
模型后端训练期监控指标。 |
None
|
backend_metric
|
Any | None
|
透传给模型后端原生训练接口的自定义 metric。 |
None
|
benchmark_col
|
str | None
|
benchmark 或 champion 模型分数列名。 |
None
|
benchmark_cols
|
Sequence[str] | None
|
多个 benchmark 或 champion 模型分数列名。 |
None
|
time_col
|
str | None
|
原始时间列名,用于补充报告中的时间边界。 |
None
|
val_target
|
str | None
|
替代验证目标列名。 |
None
|
aux_targets
|
Sequence[str] | None
|
辅助验证目标列名;不参与训练,只进入 replay 评估报告。 |
None
|
target_group_cols
|
Mapping[str, str] | None
|
每个目标对应的独立样本切片列名,用于长短 y 表现期不一致的评估。 |
None
|
psi_include_missing
|
bool
|
replay 评估报告计算 |
False
|
返回:
| 类型 | 描述 |
|---|---|
MarsModelReplayResult
|
包含 replay 排行表、模型、打分数据和评估报告的结果对象。 |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
当输入参数、列配置或数据状态不满足当前方法要求时抛出。 |
Evaluation 与 Prediction¶
mars.modeling.MarsModelEvaluator ¶
构建二分类模型分组评估报告。
evaluate ¶
evaluate(df: FrameLike, *, pred_col: str, group_col: str, target: str, benchmark_col: str | None = None, benchmark_cols: Sequence[str] | None = None, time_col: str | None = None, val_target: str | None = None, aux_targets: Sequence[str] | None = None, target_group_cols: Mapping[str, str] | None = None, feature_cols: Sequence[str] | None = None, importance_table: DataFrame | None = None, psi_include_missing: bool = False) -> MarsModelingReport
对已打分样本构建模型评估报告。
mars.modeling.ModelPredictor ¶
复用统一后端注册表与适配器的预测器。
__init__ ¶
__init__(model: Any, feature_list: Sequence[str], *, categorical_features: Sequence[str] | None = None, model_type: str, category_levels: Dict[str, Sequence[Any]] | None = None) -> None
保存训练后模型、特征契约与显式后端标识。
predict ¶
追加预测分数,并保持调用方偏好的数据框类型。
evaluate ¶
evaluate(df: FrameLike, group_col: str, target: str, *, time_col: str | None = None, val_target: str | None = None, benchmark_col: str | None = None, benchmark_cols: Sequence[str] | None = None, aux_targets: Sequence[str] | None = None, target_group_cols: Mapping[str, str] | None = None, pred_col: str = 'pred_score', psi_include_missing: bool = False) -> MarsModelingReport
对输入样本打分,并立即生成建模评估报告。
Result Objects¶
mars.modeling.MarsModelTuningResult
dataclass
¶
单次调参流程的结构化结果对象。
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
best_model |
Any
|
验证集最优模型。 |
history_table |
DataFrame
|
trial 级训练历史。 |
importance_table |
DataFrame
|
特征重要性表。 |
retained_models |
dict
|
调参过程中动态保留的 trial 模型。 |
retained_model_table |
DataFrame
|
已保留模型的 trial 编号、分数和排名。 |
artifact_path |
str or None
|
本次调参产物目录;不落盘时为 |
run_id |
str or None
|
本次调参运行编号。 |
metric_names |
list of str
|
本次调参计算的内置和自定义指标名。 |
metric_directions |
dict
|
各指标的排序方向。 |
importance_tables |
dict of str to pandas.DataFrame
|
native、SHAP 等多来源重要性表。 |
metadata |
dict
|
调参过程元信息和 artifact 元数据。 |
training_config |
dict
|
可复现训练配置。 |
backend_data_mode |
str
|
实际后端数据通道。 |
category_levels |
dict
|
类别特征稳定字典。 |
示例:
>>> run = MarsModelTuningResult(
... model_type="xgb",
... optimize_metric="ks",
... features=["age"],
... target="y",
... dataset_flag_col="dataset_flag",
... categorical_features=[],
... best_params={},
... best_iteration=None,
... best_model=None,
... best_score=0.0,
... history_table=pd.DataFrame(),
... history_path="history.csv",
... study=None,
... replay_candidates=[],
... importance_table=pd.DataFrame(),
... )
>>> run.features
['age']
export_artifact ¶
将调参结果写入本地 artifact 目录。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
str
|
输出目录。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Path
|
artifact 目录路径。 |
示例:
>>> from tempfile import TemporaryDirectory
>>> run = MarsModelTuningResult(
... model_type="xgb",
... optimize_metric="ks",
... features=["age"],
... target="y",
... dataset_flag_col="dataset_flag",
... categorical_features=[],
... best_params={},
... best_iteration=None,
... best_model=None,
... best_score=0.0,
... history_table=pd.DataFrame(),
... history_path="history.csv",
... study=None,
... replay_candidates=[],
... importance_table=pd.DataFrame(),
... )
>>> with TemporaryDirectory() as tmp:
... artifact_dir = run.export_artifact(tmp)
... (artifact_dir / "metadata.json").exists()
True
from_artifact
classmethod
¶
从本地 artifact 目录恢复调参结果。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
str
|
由 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
MarsModelTuningResult
|
恢复后的单次调参结果。 |
引发:
| 类型 | 描述 |
|---|---|
FileNotFoundError
|
当指定路径不存在时抛出。 |
ValueError
|
当输入参数、列配置或数据状态不满足当前方法要求时抛出。 |
示例:
>>> from tempfile import TemporaryDirectory
>>> run = MarsModelTuningResult(
... model_type="xgb",
... optimize_metric="ks",
... features=["age"],
... target="y",
... dataset_flag_col="dataset_flag",
... categorical_features=[],
... best_params={},
... best_iteration=None,
... best_model=None,
... best_score=0.0,
... history_table=pd.DataFrame(),
... history_path="history.csv",
... study=None,
... replay_candidates=[],
... importance_table=pd.DataFrame(),
... )
>>> with TemporaryDirectory() as tmp:
... _ = run.export_artifact(tmp)
... MarsModelTuningResult.from_artifact(tmp).features
['age']
mars.modeling.MarsModelReplayResult
dataclass
¶
调参 replay 流程的结构化结果对象。
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
ranking_table |
DataFrame
|
用于选取 Top-K 或指定 trial 的排名表。 |
leaderboard_table |
DataFrame
|
replay 后的模型排行榜。 |
models |
dict
|
replay 训练得到的模型对象。 |
scored_df |
(DataFrame or DataFrame, optional)
|
追加预测列后的数据。 |
reports |
dict
|
每个 replay 模型对应的评估报告。 |
示例:
>>> replay = MarsModelReplayResult(
... model_type="xgb",
... ranking_table=pd.DataFrame(),
... leaderboard_table=pd.DataFrame(),
... models={},
... scored_df=None,
... reports={},
... importance_tables={},
... )
>>> replay.models
{}
export_artifact ¶
将 replay 结果写入本地 artifact 目录。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
str
|
输出目录。 |
必需 |
include_scored_df
|
bool
|
是否保存评分后的数据框。 |
False
|
返回:
| 类型 | 描述 |
|---|---|
Path
|
artifact 目录路径。 |
示例:
>>> from tempfile import TemporaryDirectory
>>> replay = MarsModelReplayResult(
... model_type="xgb",
... ranking_table=pd.DataFrame(),
... leaderboard_table=pd.DataFrame(),
... models={},
... scored_df=None,
... reports={},
... importance_tables={},
... )
>>> with TemporaryDirectory() as tmp:
... artifact_dir = replay.export_artifact(tmp)
... (artifact_dir / "metadata.json").exists()
True
from_artifact
classmethod
¶
从本地 artifact 目录恢复 replay 结果。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
str
|
由 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
MarsModelReplayResult
|
恢复后的 replay 结果。 |
引发:
| 类型 | 描述 |
|---|---|
FileNotFoundError
|
当指定路径不存在时抛出。 |
ValueError
|
当输入参数、列配置或数据状态不满足当前方法要求时抛出。 |
示例:
>>> from tempfile import TemporaryDirectory
>>> replay = MarsModelReplayResult(
... model_type="xgb",
... ranking_table=pd.DataFrame(),
... leaderboard_table=pd.DataFrame(),
... models={},
... scored_df=None,
... reports={},
... importance_tables={},
... )
>>> with TemporaryDirectory() as tmp:
... _ = replay.export_artifact(tmp)
... MarsModelReplayResult.from_artifact(tmp).model_type
'xgb'
mars.modeling.MarsFeatureGrowthResult
dataclass
¶
逐步增加特征调参的结构化结果。
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
summary_table |
DataFrame
|
step 级汇总审计表。 |
runs |
dict of int to MarsModelTuningResult
|
每个成功 step 对应的调参结果。 |
best_step |
int or None
|
推荐模型对应的特征数量;若无成功 step 则为 |
best_run |
MarsModelTuningResult or None
|
推荐 step 对应的调参结果。 |
示例:
>>> run = MarsFeatureGrowthResult(
... model_type="xgb",
... optimize_metric="ks",
... feature_order=["age"],
... steps=[1],
... selection_metric="ks",
... summary_table=pd.DataFrame(),
... runs={},
... )
>>> run.best_features
[]
best_model
property
¶
best_score
property
¶
best_features
property
¶
export_artifact ¶
将特征增长实验结果写入本地 artifact 目录。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
str
|
输出目录。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Path
|
artifact 目录路径。 |
示例:
from_artifact
classmethod
¶
从本地 artifact 目录恢复特征增长实验结果。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
str
|
artifact 目录。 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
MarsFeatureGrowthResult
|
恢复后的实验结果。 |
引发:
| 类型 | 描述 |
|---|---|
FileNotFoundError
|
当指定路径不存在时抛出。 |
ValueError
|
当输入参数、列配置或数据状态不满足当前方法要求时抛出。 |
示例:
mars.modeling.MarsModelingReport ¶
建模评估报告的数据容器。
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
summary_table |
DataFrame
|
分数据集的核心指标汇总表。 |
caption |
str
|
Notebook 样式展示标题。 |
detail_tables |
dict of str to pandas.DataFrame
|
ROC、KS、PSI、风险水位图等轻量明细表。 |
metadata |
dict
|
训练配置、版本、特征重要性等报告元数据。 |
示例:
>>> import pandas as pd
>>> report = MarsModelingReport(pd.DataFrame({"metric": [1.0]}))
>>> report.caption
'MARS Model Evaluation'
styled_summary
property
¶
__init__ ¶
__init__(summary_table: DataFrame, caption: str = 'MARS Model Evaluation', detail_tables: Dict[str, DataFrame] | None = None, metadata: Dict[str, Any] | None = None) -> None
初始化建模评估报告对象。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
summary_table
|
DataFrame
|
建模评估汇总表。 |
必需 |
caption
|
str
|
报告标题。 |
'MARS Model Evaluation'
|
detail_tables
|
Dict[str, DataFrame] | None
|
多粒度明细表集合。 |
None
|
metadata
|
Dict[str, Any] | None
|
报告元数据。 |
None
|
show_summary ¶
to_pandas ¶
write_excel ¶
将汇总表和明细表写入 Excel 工作簿。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
str
|
输出文件路径。 |
'mars_model_evaluation.xlsx'
|
engine
|
str | None
|
Pandas ExcelWriter 引擎。 |
None
|
返回:
| 类型 | 描述 |
|---|---|
None
|
函数仅产生 Excel 文件写入副作用。 |
示例:
to_html ¶
to_html(path: str = 'mars_model_report.html', *, title: str | None = None, run: Any | None = None, scorecard: Any | None = None, importance_table: DataFrame | None = None, history_table: DataFrame | None = None, top_features: int = 20, dpi: int = 150) -> Path
生成单文件 HTML 模型报告。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
str
|
输出路径。 |
'mars_model_report.html'
|
title
|
str | None
|
HTML 报告标题。 |
None
|
run
|
Any | None
|
调参结果对象,用于补充审计元数据。 |
None
|
scorecard
|
Any | None
|
评分卡对象,用于展示评分刻度。 |
None
|
importance_table
|
DataFrame | None
|
特征重要性表。 |
None
|
history_table
|
DataFrame | None
|
调参历史表。 |
None
|
top_features
|
int
|
HTML 中展示的重要特征数量。 |
20
|
dpi
|
int
|
Matplotlib 图片分辨率。 |
150
|
返回:
| 类型 | 描述 |
|---|---|
Path
|
写出的 HTML 文件路径。 |
示例: