Analysis¶
analysis
¶
Classes¶
SHAPAnalyzer
¶
SHAPAnalyzer(backend: Backend, min_abs_shap: float = 0.0)
Analyze SHAP explanations stored in a backend.
Provides methods for computing summary statistics, comparing time periods, and detecting changes in feature importance over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
Backend
|
Backend for retrieving stored SHAP explanations. |
required |
min_abs_shap
|
float
|
Minimum mean absolute SHAP value threshold (default: 0.0). Features below this threshold are excluded from results. Useful for filtering out low-impact features and reducing noise. |
0.0
|
Examples:
>>> from datetime import datetime
>>> from shapmonitor.backends import ParquetBackend
>>> from shapmonitor.analysis import SHAPAnalyzer
>>> backend = ParquetBackend("/path/to/shap_logs")
>>> analyzer = SHAPAnalyzer(backend, min_abs_shap=0.01)
>>> summary = analyzer.summary(datetime(2025, 1, 1), datetime(2025, 1, 31))
Source code in shapmonitor/analysis/_analyzer.py
39 40 41 | |
Attributes¶
Functions¶
fetch_shap_values
¶
fetch_shap_values(**kwargs) -> DFrameLike
Fetch raw SHAP values from the backend within a date range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
|
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Raw SHAP values indexed by timestamp. |
Source code in shapmonitor/analysis/_analyzer.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | |
summary
¶
summary(
start_dt: datetime | date | None = None,
end_dt: datetime | date | None = None,
batch_id: str | None = None,
model_version: str | None = None,
sort_by: str = "mean_abs",
top_k: int | None = None,
) -> DFrameLike
Compute summary statistics for SHAP values in a date range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_dt
|
datetime | date
|
Start of the date range (inclusive). |
None
|
end_dt
|
datetime | date
|
End of the date range (inclusive). |
None
|
batch_id
|
str
|
Batch ID to filter results to a specific batch. |
None
|
model_version
|
str
|
Model version to filter results to a specific model version. |
None
|
sort_by
|
str
|
Column to sort results by (default: 'mean_abs'). Options: 'mean_abs', 'mean', 'std', 'min', 'max'. |
'mean_abs'
|
top_k
|
int | None
|
If set, return only the top k features after sorting. Must be a positive integer. Default is None (return all features). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Summary statistics indexed by feature name (dtype: float32). Columns: - mean_abs: Mean of absolute SHAP values (feature importance) - mean: Mean SHAP value (contribution direction) - std: Standard deviation of SHAP values - min: Minimum SHAP value - max: Maximum SHAP value Attributes: - n_samples: Total number of samples in the date range |
Notes
Features with mean_abs below min_abs_shap threshold are excluded.
Source code in shapmonitor/analysis/_analyzer.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | |
compare_time_periods
¶
compare_time_periods(
period_ref: Period,
period_curr: Period,
sort_by: str = "psi",
top_k: int | None = None,
) -> DFrameLike
Compare SHAP explanations between two time periods.
Useful for detecting feature importance drift, ranking changes, and sign flips in model behavior over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period_ref
|
Period
|
Tuple of (start_dt, end_dt) defining the reference date range (both inclusive). |
required |
period_curr
|
Period
|
Tuple of (start_dt, end_dt) defining the current date range (both inclusive). |
required |
sort_by
|
str
|
Column to sort results by (default: 'psi'). |
'psi'
|
top_k
|
int | None
|
If set, return only the top k features after sorting. Must be a positive integer. Default is None (return all features). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Comparison statistics indexed by feature name. Columns: - psi: Population Stability Index between periods - mean_abs_1, mean_abs_2: Feature importance per period - delta_mean_abs: Absolute change (period_2 - period_1) - pct_delta_mean_abs: Percentage change from period_1 - mean_1, mean_2: Mean SHAP value (direction) per period - rank_1, rank_2: Feature importance rank per period - delta_rank: Rank change (positive = less important) - rank_change: 'increased', 'decreased', or 'no_change' - sign_flip: True if contribution direction changed Attributes: - n_samples_1: Sample count in period 1 - n_samples_2: Sample count in period 2 |
Notes
Features with mean_abs below min_abs_shap threshold are excluded.
Uses outer join, so features appearing in only one period will have NaN.
Below is a guideline for interpreting PSI values:
| PSI Value | Interpretation |
|---|---|
| 0 | Identical distributions |
| < 0.1 | No significant shift |
| 0.1 - 0.25 | Moderate shift, investigate |
| 0.25 - 0.5 | Significant shift |
| > 0.5 | Severe shift |
Source code in shapmonitor/analysis/_analyzer.py
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | |
compare_batches
¶
compare_batches(
batch_ref: str,
batch_curr: str,
sort_by: str = "psi",
top_k: int | None = None,
) -> DFrameLike
Compare SHAP explanations between two batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_ref
|
str
|
Identifier for the first batch. |
required |
batch_curr
|
str
|
Identifier for the second batch. |
required |
sort_by
|
str
|
Column to sort results by (default: 'psi'). |
'psi'
|
top_k
|
int | None
|
If set, return only the top k features after sorting. Must be a positive integer. Default is None (return all features). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Comparison of SHAP statistics between the two batches. Columns: - psi: Population Stability Index between periods - mean_abs_1, mean_abs_2: Feature importance per period - delta_mean_abs: Absolute change (period_2 - period_1) - pct_delta_mean_abs: Percentage change from period_1 - mean_1, mean_2: Mean SHAP value (direction) per period - rank_1, rank_2: Feature importance rank per period - delta_rank: Rank change (positive = less important) - rank_change: 'increased', 'decreased', or 'no_change' - sign_flip: True if contribution direction changed Attributes: - n_samples_1: Sample count in period 1 - n_samples_2: Sample count in period 2 |
Notes
Features with mean_abs below min_abs_shap threshold are excluded.
Uses outer join, so features appearing in only one period will have NaN.
Below is a guideline for interpreting PSI values:
| PSI Value | Interpretation |
|---|---|
| 0 | Identical distributions |
| < 0.1 | No significant shift |
| 0.1 - 0.25 | Moderate shift, investigate |
| 0.25 - 0.5 | Significant shift |
| > 0.5 | Severe shift |
Source code in shapmonitor/analysis/_analyzer.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 | |
compare_versions
¶
compare_versions(
model_version_ref: str,
model_version_curr: str,
sort_by: str = "psi",
top_k: int | None = None,
) -> DFrameLike
Compare SHAP explanations across different model versions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_version_ref
|
str
|
Reference model version identifier. |
required |
model_version_curr
|
str
|
Current model version identifier. |
required |
sort_by
|
str
|
Column to sort results by (default: 'psi'). |
'psi'
|
top_k
|
int | None
|
If set, return only the top k features after sorting. Must be a positive integer. Default is None (return all features). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Comparison of SHAP statistics across model versions. Columns: - psi: Population Stability Index between periods - mean_abs_1, mean_abs_2: Feature importance per period - delta_mean_abs: Absolute change (period_2 - period_1) - pct_delta_mean_abs: Percentage change from period_1 - mean_1, mean_2: Mean SHAP value (direction) per period - rank_1, rank_2: Feature importance rank per period - delta_rank: Rank change (positive = less important) - rank_change: 'increased', 'decreased', or 'no_change' - sign_flip: True if contribution direction changed Attributes: - n_samples_1: Sample count in period 1 - n_samples_2: Sample count in period 2 |
Notes
Features with mean_abs below min_abs_shap threshold are excluded.
Uses outer join, so features appearing in only one period will have NaN.
Below is a guideline for interpreting PSI values:
| PSI Value | Interpretation |
|---|---|
| 0 | Identical distributions |
| < 0.1 | No significant shift |
| 0.1 - 0.25 | Moderate shift, investigate |
| 0.25 - 0.5 | Significant shift |
| > 0.5 | Severe shift |
Source code in shapmonitor/analysis/_analyzer.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | |
compare_adversarial
¶
compare_adversarial(
period_ref: Period,
period_curr: Period,
classifier: Any | None = None,
cv: int = 5,
sort_by: str = "adv_importance",
top_k: int | None = None,
random_state: int | None = None,
) -> DFrameLike
Compare SHAP distributions between two periods using adversarial validation.
Trains a binary classifier to distinguish SHAP values from period_ref
(label 0) vs period_curr (label 1). The cross-validated AUC measures
overall distributional shift; per-feature importances reveal which SHAP
dimensions drive the separability — complementing the univariate PSI score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period_ref
|
Period
|
Tuple of (start_dt, end_dt) defining the reference date range. |
required |
period_curr
|
Period
|
Tuple of (start_dt, end_dt) defining the current date range. |
required |
classifier
|
sklearn estimator
|
Sklearn-compatible classifier with |
None
|
cv
|
int
|
Number of stratified k-fold splits (default: 5). |
5
|
sort_by
|
str
|
Column to sort results by (default: 'adv_importance'). |
'adv_importance'
|
top_k
|
int | None
|
If set, return only the top k features. Must be a positive integer. |
None
|
random_state
|
int | None
|
Random state for the default classifier and CV splitter. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Comparison statistics indexed by feature name. Columns: - adv_importance: Feature's contribution to classifier separability - mean_abs_1, mean_abs_2: Mean absolute SHAP value per period - delta_mean_abs: Absolute importance change (period_2 - period_1) Attributes: - adversarial_auc: Cross-validated AUC (0.5 = no shift, 1.0 = max shift) - n_samples_ref: Sample count in the reference period - n_samples_curr: Sample count in the current period |
Raises:
| Type | Description |
|---|---|
ValueError
|
If top_k < 1 or sort_by is not a valid column name. |
Notes
Returns an empty DataFrame if either period contains no data.
To run adversarial validation on raw input feature distributions (not SHAP),
use adversarial_auc from shapmonitor.analysis.metrics directly with
backend.read(...).filter(like="feat_").
AUC interpretation guide:
| AUC | Interpretation |
|---|---|
| 0.50 | Distributions are indistinguishable |
| 0.50–0.65 | Minor differences, likely noise |
| 0.65–0.80 | Moderate shift — worth investigating |
| 0.80–0.90 | Strong shift detected |
| > 0.90 | Severe — clearly different regimes |
Source code in shapmonitor/analysis/_analyzer.py
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 | |
compare_adversarial_batches
¶
compare_adversarial_batches(
batch_ref: str,
batch_curr: str,
classifier: Any | None = None,
cv: int = 5,
sort_by: str = "adv_importance",
top_k: int | None = None,
random_state: int | None = None,
) -> DFrameLike
Compare SHAP distributions between two batches using adversarial validation.
Trains a binary classifier to distinguish SHAP values from batch_ref
(label 0) vs batch_curr (label 1). The cross-validated AUC measures
overall distributional shift; per-feature importances reveal which SHAP
dimensions drive the separability — complementing the univariate PSI score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_ref
|
str
|
Identifier for the reference batch. |
required |
batch_curr
|
str
|
Identifier for the current batch. |
required |
classifier
|
sklearn estimator
|
Sklearn-compatible classifier with |
None
|
cv
|
int
|
Number of stratified k-fold splits (default: 5). |
5
|
sort_by
|
str
|
Column to sort results by (default: 'adv_importance'). |
'adv_importance'
|
top_k
|
int | None
|
If set, return only the top k features. Must be a positive integer. |
None
|
random_state
|
int | None
|
Random state for the default classifier and CV splitter. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Comparison statistics indexed by feature name. Columns: - adv_importance: Feature's contribution to classifier separability - mean_abs_1, mean_abs_2: Mean absolute SHAP value per batch - delta_mean_abs: Absolute importance change (batch_2 - batch_1) Attributes: - adversarial_auc: Cross-validated AUC (0.5 = no shift, 1.0 = max shift) - n_samples_ref: Sample count in the reference batch - n_samples_curr: Sample count in the current batch |
Raises:
| Type | Description |
|---|---|
ValueError
|
If top_k < 1 or sort_by is not a valid column name. |
Notes
Returns an empty DataFrame if either batch contains no data.
Batch sizes sampled via sample_rate may be small. Ensure each batch
has enough rows for the chosen cv splits (at least 2 * cv samples
total is recommended) for stable AUC estimates.
AUC interpretation guide:
| AUC | Interpretation |
|---|---|
| 0.50 | Distributions are indistinguishable |
| 0.50–0.65 | Minor differences, likely noise |
| 0.65–0.80 | Moderate shift — worth investigating |
| 0.80–0.90 | Strong shift detected |
| > 0.90 | Severe — clearly different regimes |
Source code in shapmonitor/analysis/_analyzer.py
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 | |