Analysis¶
状态:Stable。 使用方式见数据画像和 分箱与风险评估。
mars.analysis.MarsDataProfiler ¶
Bases: MarsBaseEstimator
数据质量、统计分布和稳定性画像器。
MarsDataProfiler 只保存稳定策略,不保存本次运行数据。每次调用
:meth:generate_profile 都会构造独立的运行上下文,因此同一个实例可以安全复用到
不同 DataFrame。
示例:
>>> import polars as pl
>>> df = pl.DataFrame({"age": [20, 30, None], "month": ["202601", "202601", "202602"]})
>>> profiler = MarsDataProfiler(missing_values=[-999])
>>> report = profiler.generate_profile(df, group_col="month")
>>> report.get_profile_data().overview.height > 0
True
__init__ ¶
__init__(
*,
missing_values: list[int | float | str] | None = None,
special_values: list[Any] | None = None,
psi_n_bins: int = 10,
psi_bin_method: ProfileBinMethod = "quantile",
psi_remove_empty_bins: bool = True,
psi_merge_small_bins: bool = True,
psi_min_bin_size: float = 0.02,
psi_cv_ignore_threshold: float = 0.05,
psi_batch_size: int = 50,
overview_batch_size: int = 500
) -> None
初始化画像策略。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
missing_values
|
list[int | float | str] | None
|
额外视为缺失的取值。 |
None
|
special_values
|
list[Any] | None
|
连续统计和 PSI 计算中需要识别的特殊值。 |
None
|
psi_n_bins
|
int
|
PSI 计算使用的最大分箱数。 |
10
|
psi_bin_method
|
ProfileBinMethod
|
PSI 数值特征分箱策略。 |
'quantile'
|
psi_remove_empty_bins
|
bool
|
数值特征 PSI 分箱时是否移除全局空箱。 |
True
|
psi_merge_small_bins
|
bool
|
数值特征 PSI 分箱时是否合并小样本箱。 |
True
|
psi_min_bin_size
|
float
|
数值特征 PSI 合并小样本箱时使用的最小样本占比。 |
0.02
|
psi_cv_ignore_threshold
|
float
|
分组 PSI 最大值低于该阈值时,变异系数强制置零。 |
0.05
|
psi_batch_size
|
int
|
PSI 趋势计算的特征批大小。 |
50
|
overview_batch_size
|
int
|
overview 计算的特征批大小。 |
500
|
generate_profile ¶
generate_profile(
df: DataFrame | DataFrame,
*,
metrics: list[str] | None = None,
features: list[str] | None = None,
benchmark_df: DataFrame | DataFrame | None = None,
categorical_features: list[str] | None = None,
exclude_features: list[str] | None = None,
include_dtypes: (
type | DataType | list[type | DataType] | None
) = None,
group_col: str | None = None,
time_col: str | None = None,
time_grain: str | None = None,
enable_sparkline: bool = True,
sparkline_bins: int = 8,
sparkline_sample_size: int = 200000,
psi_include_missing: bool = False,
psi_include_special: bool = False
) -> MarsProfileReport
生成一次数据画像报告。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame | DataFrame
|
待画像样本表。 |
必需 |
metrics
|
list[str] | None
|
本次计算的指标;不传时使用默认全量画像指标。 |
None
|
features
|
list[str] | None
|
本次画像的特征列;不传时使用过滤后的全部候选列。 |
None
|
benchmark_df
|
DataFrame | DataFrame | None
|
PSI 基准样本。传入后用其拟合分箱并构造 expected distribution;不会参与 overview、数据质量或其他统计指标。未提供分组时仍会计算当前全量相对基准的 PSI。 |
None
|
categorical_features
|
list[str] | None
|
显式声明的类别特征,用于整数编码类别的 unseen 和 PSI 分箱。 |
None
|
exclude_features
|
list[str] | None
|
本次画像需要排除的列名。 |
None
|
include_dtypes
|
type | DataType | list[type | DataType] | None
|
只保留指定数据类型的特征列。 |
None
|
group_col
|
str | None
|
已存在的分组列名。 |
None
|
time_col
|
str | None
|
原始日期列名;与 |
None
|
time_grain
|
str | None
|
时间聚合粒度,例如 |
None
|
enable_sparkline
|
bool
|
是否生成 overview 中的字符分布图。 |
True
|
sparkline_bins
|
int
|
字符分布图的直方图分箱数量。 |
8
|
sparkline_sample_size
|
int
|
字符分布图最多使用的采样行数。 |
200000
|
psi_include_missing
|
bool
|
计算 PSI 时是否纳入缺失值箱。 |
False
|
psi_include_special
|
bool
|
计算 PSI 时是否纳入特殊值箱。 |
False
|
返回:
| 类型 | 描述 |
|---|---|
MarsProfileReport
|
包含 overview、数据质量趋势表和统计趋势表的数据画像报告。 |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
指标、特征、benchmark 或对比配置无效时抛出。 |
示例:
mars.analysis.profile_stats ¶
profile_stats(
df: DataFrame | DataFrame,
*,
metrics: list[str],
features: list[str] | None = None,
benchmark_df: DataFrame | DataFrame | None = None,
categorical_features: list[str] | None = None,
group_col: str | None = None,
time_col: str | None = None,
time_grain: str | None = None,
missing_values: list[int | float | str] | None = None,
special_values: list[Any] | None = None,
exclude_features: list[str] | None = None,
include_dtypes: (
type | DataType | list[type | DataType] | None
) = None,
enable_sparkline: bool = False,
sparkline_bins: int = 8,
sparkline_sample_size: int = 200000,
psi_include_missing: bool = False,
psi_include_special: bool = False,
psi_remove_empty_bins: bool = True,
psi_merge_small_bins: bool = True,
psi_min_bin_size: float = 0.02
) -> MarsProfileReport
为指定指标生成轻量画像报告。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame | DataFrame
|
待画像样本表。 |
必需 |
metrics
|
list[str]
|
本次需要计算的数据质量或统计指标,必须显式传入。 |
必需 |
features
|
list[str] | None
|
本次画像的特征列。 |
None
|
benchmark_df
|
DataFrame | DataFrame | None
|
PSI 基准样本。传入后用其拟合分箱并构造 expected distribution;不会参与 overview、数据质量或其他统计指标。未提供分组时仍会计算当前全量相对基准的 PSI。 |
None
|
categorical_features
|
list[str] | None
|
显式声明的类别特征,用于整数编码类别的 unseen 和 PSI 分箱。 |
None
|
group_col
|
str | None
|
已存在的分组列名。 |
None
|
time_col
|
str | None
|
原始日期列名,用于生成趋势分组。 |
None
|
time_grain
|
str | None
|
时间聚合粒度,例如 |
None
|
missing_values
|
list[int | float | str] | None
|
额外视为缺失的取值。 |
None
|
special_values
|
list[Any] | None
|
连续统计和 PSI 计算中需要识别的特殊值。 |
None
|
exclude_features
|
list[str] | None
|
本次画像需要排除的列名。 |
None
|
include_dtypes
|
type | DataType | list[type | DataType] | None
|
本次画像允许保留的数据类型。 |
None
|
enable_sparkline
|
bool
|
是否生成 overview 中的字符分布图。 |
False
|
sparkline_bins
|
int
|
字符分布图的直方图分箱数量。 |
8
|
sparkline_sample_size
|
int
|
字符分布图最多使用的采样行数。 |
200000
|
psi_include_missing
|
bool
|
计算 PSI 时是否纳入缺失值箱。 |
False
|
psi_include_special
|
bool
|
计算 PSI 时是否纳入特殊值箱。 |
False
|
psi_remove_empty_bins
|
bool
|
数值特征 PSI 分箱时是否移除全局空箱。 |
True
|
psi_merge_small_bins
|
bool
|
数值特征 PSI 分箱时是否合并小样本箱。 |
True
|
psi_min_bin_size
|
float
|
数值特征 PSI 合并小样本箱时使用的最小样本占比。 |
0.02
|
返回:
| 类型 | 描述 |
|---|---|
MarsProfileReport
|
包含所请求指标表的画像报告。 |
示例:
>>> import polars as pl
>>> df = pl.DataFrame({"x": [1, 2, None], "month": ["202601", "202601", "202602"]})
>>> report = profile_stats(df, metrics=["missing", "mean"], group_col="month")
>>> "missing" in report.dq_tables
True
>>> benchmark = pl.DataFrame({"x": [1, 1, 2, 2]})
>>> current = pl.DataFrame({"x": [1, 2, 2, 2]})
>>> psi_report = profile_stats(current, metrics=["psi"], benchmark_df=benchmark)
>>> psi_report.stats_tables["psi"].columns
['feature', 'dtype', 'total']
mars.analysis.MarsBinEvaluator ¶
Bases: MarsBaseEstimator
分箱效果评估器。
该评估器用于对一组特征的分箱结果计算 IV、KS、AUC、PSI、Lift、单调性、
分组趋势和明细分布。构造函数只保存稳定评估策略和默认分箱器配置;数据、
目标列、特征范围、分组列和时间聚合粒度都由每次 evaluate 调用传入。
每次 evaluate 都会返回新的 MarsRiskProfile,其中包含报告对象和本次使用的
分箱器。评估器实例不会把上一次拟合出的分箱器作为下一次调用的隐式状态,
因此同一个实例可以安全地连续评估不同特征集合或不同数据集。
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
binning_type |
str
|
默认分箱器类型。 |
binner_params |
dict
|
默认分箱器参数副本。 |
示例:
>>> import polars as pl
>>> from mars.analysis import MarsBinEvaluator
>>> df = pl.DataFrame({"age": [20, 30, 40, 50], "y": [0, 0, 1, 1]})
>>> evaluator = MarsBinEvaluator(
... binning_type="native",
... binner_params={"method": "quantile", "n_bins": 2},
... )
>>> profile = evaluator.evaluate(df, target="y", features=["age"])
>>> "age" in profile.report.summary_table.get_column("feature").to_list()
True
__init__ ¶
__init__(
*,
binning_type: Literal[
"native", "optimal", "lite_opt"
] = "native",
binner_params: Dict[str, Any] | None = None,
feature_start_aware_reference: bool = False,
risk_corr_baseline: RiskCorrBaseline = "total",
ordered_metric_sort_by: OrderedMetricSortBy = "woe"
) -> None
初始化分箱评估器。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
binning_type
|
Literal['native', 'optimal', 'lite_opt']
|
未显式传入分箱器时使用的默认分箱策略。 |
'native'
|
binner_params
|
Dict[str, Any] | None
|
构造默认分箱器时使用的参数。 |
None
|
feature_start_aware_reference
|
bool
|
是否默认启用按特征上线时间重锚的稳定性参考,默认为 成功识别的特征使用上线首期分布作为 PSI 基准,并只在上线后计算 PSI/RC
趋势;其他特征沿用默认参考。RC 是否改用上线首期坏率仍由
|
False
|
risk_corr_baseline
|
RiskCorrBaseline
|
RC 的默认基准选择方式。 |
'total'
|
ordered_metric_sort_by
|
OrderedMetricSortBy
|
KS/AUC 的默认排序口径。 |
'woe'
|
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
当 |
evaluate ¶
evaluate(
df: DataFrame | DataFrame,
*,
target: str | None = None,
features: list[str] | None = None,
group_col: str | None = None,
time_col: str | None = None,
time_grain: str | None = None,
feature_data_source: dict[str, list[str]] | None = None,
weights_col: str | None = None,
amount_col: str | None = None,
binner: MarsBinnerBase | None = None,
benchmark_df: DataFrame | DataFrame | None = None,
psi_include_missing: bool = False,
psi_include_special: bool = False,
feature_start_aware_reference: bool | None = None,
risk_corr_baseline: RiskCorrBaseline | None = None,
ordered_metric_sort_by: (
OrderedMetricSortBy | None
) = None,
batch_size: int = 100
) -> MarsRiskProfile
对一次数据上下文执行分箱评估。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame | DataFrame
|
待评估样本表。 |
必需 |
target
|
str | None
|
二分类目标列名。为 |
None
|
features
|
list[str] | None
|
本次评估的特征列;不传时自动排除目标列和分组列后选择候选特征。 |
None
|
group_col
|
str | None
|
已存在的分组列名,例如月份、客群或样本切片。 |
None
|
time_col
|
str | None
|
原始日期列名;与 |
None
|
time_grain
|
str | None
|
时间聚合粒度,例如 |
None
|
feature_data_source
|
dict[str, list[str]] | None
|
特征来源映射,只对本次 active features 生效,用于报告中保留来源分层。 |
None
|
weights_col
|
str | None
|
样本权重列名。 |
None
|
amount_col
|
str | None
|
金额列名;传入后会在 |
None
|
binner
|
MarsBinnerBase | None
|
显式复用的分箱器;传入后不会再根据 |
None
|
benchmark_df
|
DataFrame | DataFrame | None
|
基准期样本。未传入 |
None
|
psi_include_missing
|
bool
|
计算 PSI 时是否单独保留缺失值分布。 |
False
|
psi_include_special
|
bool
|
计算 PSI 时是否单独保留特殊值分布。 |
False
|
feature_start_aware_reference
|
bool | None
|
是否按特征上线时间重锚稳定性参考。传入 成功识别的特征按上线日映射到 |
None
|
risk_corr_baseline
|
RiskCorrBaseline | None
|
本次评估使用的 RC 基准;传入 |
None
|
ordered_metric_sort_by
|
OrderedMetricSortBy | None
|
本次评估使用的 KS/AUC 排序口径;传入 |
None
|
batch_size
|
int
|
批量评估时的特征批大小。 |
100
|
返回:
| 类型 | 描述 |
|---|---|
MarsRiskProfile
|
单次风险画像结果,包含评估报告、分箱器、目标列列表和运行元数据。 |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
当必要列缺失、分箱器配置冲突或输入数据无法评估时抛出。 |
mars.analysis.profile_risk ¶
profile_risk(
df: DataFrame | DataFrame,
*,
target: str | list[str] | None = None,
features: list[str] | None = None,
feature_data_source: dict[str, list[str]] | None = None,
group_col: str | None = None,
time_col: str | None = None,
time_grain: str | None = None,
weights_col: str | None = None,
amount_col: str | None = None,
binning_type: Literal[
"native", "optimal", "lite_opt"
] = "native",
method: (
Literal["quantile", "uniform", "cart"] | None
) = None,
n_bins: int | None = None,
min_bin_size: float | int | None = None,
monotonic_trend: (
Literal[
"ascending",
"descending",
"peak",
"valley",
"auto",
"auto_asc_desc",
]
| None
) = None,
missing_values: list[Any] | None = None,
special_values: list[Any] | None = None,
psi_include_missing: bool = False,
psi_include_special: bool = False,
binner_params: dict[str, Any] | None = None,
benchmark_df: DataFrame | DataFrame | None = None,
feature_start_aware_reference: bool = False,
risk_corr_baseline: RiskCorrBaseline = "total",
ordered_metric_sort_by: OrderedMetricSortBy = "woe",
batch_size: int = 100,
n_jobs: int | None = None
) -> MarsRiskProfile
运行高层分箱风险评估工作流。
profile_risk 统一编排分箱器构建、分箱评估、多目标合并和结果对象组装,
最终返回 MarsRiskProfile。函数本身不承担绘图副作用;如需查看趋势图,
请直接调用 report.plot_risk_trends(...)。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
df
|
DataFrame | DataFrame
|
待评估样本表。 |
必需 |
target
|
str | list[str] | None
|
目标列名或目标列列表。传入 |
None
|
features
|
list[str] | None
|
本次参与评估的特征列。传入 |
None
|
feature_data_source
|
dict[str, list[str]] | None
|
特征来源映射,用于在报告中保留数据源维度。 |
None
|
group_col
|
str | None
|
已存在的分组列名。 |
None
|
time_col
|
str | None
|
原始日期列名。 |
None
|
time_grain
|
str | None
|
时间聚合粒度,例如 |
None
|
weights_col
|
str | None
|
样本权重列名。 |
None
|
amount_col
|
str | None
|
金额列名。 |
None
|
binning_type
|
Literal['native', 'optimal', 'lite_opt']
|
自动构建分箱器时使用的分箱器类型。 |
'native'
|
method
|
Literal['quantile', 'uniform', 'cart'] | None
|
高层公开的分箱方法参数。 |
None
|
n_bins
|
int | None
|
高层公开的目标分箱数。传入后映射到底层 |
None
|
min_bin_size
|
float | int | None
|
高层公开的最小分箱样本约束。传入后映射到底层 |
None
|
monotonic_trend
|
Literal['ascending', 'descending', 'peak', 'valley', 'auto', 'auto_asc_desc'] | None
|
高层公开的趋势约束参数。仅对 |
None
|
missing_values
|
list[Any] | None
|
显式透传给分箱器的 |
None
|
special_values
|
list[Any] | None
|
显式透传给分箱器的 |
None
|
psi_include_missing
|
bool
|
计算 PSI 时是否纳入缺失值箱。 |
False
|
psi_include_special
|
bool
|
计算 PSI 时是否纳入特殊值箱。 |
False
|
binner_params
|
dict[str, Any] | None
|
单层高级分箱器参数入口。同一份字典可以同时包含多种分箱器参数;
运行时只读取当前 当前允许的高级参数如下:
|
None
|
benchmark_df
|
DataFrame | DataFrame | None
|
基准期样本。未传显式 |
None
|
feature_start_aware_reference
|
bool
|
是否启用按特征上线时间重锚的稳定性参考,默认为 只有成功识别上线日的特征会改用上线首期的分箱分布计算 PSI,并从 PSI/RC
监控窗口中排除上线前分组;其他特征沿用默认参考。 |
False
|
risk_corr_baseline
|
RiskCorrBaseline
|
RC 的基准选择方式。 |
'total'
|
ordered_metric_sort_by
|
OrderedMetricSortBy
|
KS/AUC 的排序口径。默认 |
'woe'
|
batch_size
|
int
|
批量评估时的特征批大小。 |
100
|
n_jobs
|
int | None
|
显式透传给分箱器的 |
None
|
返回:
| 类型 | 描述 |
|---|---|
MarsRiskProfile
|
单次风险评估结果,包含 |
Notes
report.report_meta["feature_start_aware_reference"] 表示本次是否实际构造出
feature-start reference,而不是简单回显调用参数。已识别的特征及上线日期分别
保存在 feature_start_reference_features 和 feature_start_reference_dates 中。
示例:
>>> import polars as pl
>>> from mars.analysis import profile_risk
>>> df = pl.DataFrame({"age": [20, 30, 40, 50], "y": [0, 0, 1, 1]})
>>> profile = profile_risk(
... df,
... target="y",
... features=["age"],
... method="quantile",
... n_bins=3,
... )
>>> profile.targets
['y']
>>> temporal_df = pl.DataFrame(
... {
... "dt": [
... "2024-01-01", "2024-01-02", "2024-01-03",
... "2024-02-15", "2024-02-16", "2024-02-17",
... ],
... "score": [None, None, None, 0.1, 0.5, 0.9],
... "y": [0, 1, 0, 0, 1, 1],
... }
... )
>>> temporal_profile = profile_risk(
... temporal_df,
... target="y",
... features=["score"],
... time_col="dt",
... time_grain="month",
... feature_start_aware_reference=True,
... )
>>> temporal_profile.report.report_meta["feature_start_reference_features"]
['score']
mars.analysis.MarsRiskProfile
dataclass
¶
单次风险画像结果。
MarsRiskProfile 是 MarsBinEvaluator.evaluate 和 profile_risk 的统一返回对象,
用来把评估报告、拟合后的分箱器、本次目标列和元数据放在同一个结果容器中。
调用方可以直接使用 report 查看或导出报表,也可以复用 binner 对新样本做转换。
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
report |
MarsBinningReport
|
风险评估报告,包含汇总表、明细表、趋势表和导出方法。 |
binner |
MarsBinnerBase
|
本次评估拟合或显式传入的分箱器。 |
targets |
list of str
|
本次画像覆盖的目标列列表;无标签画像时为空列表。 |
metadata |
dict
|
本次运行的列名、特征范围、分箱配置和其他上下文信息。 |