Binary and SHAP-IMV API¶
Evaluator¶
imvpy.shap_imv.BinaryIMV
¶
Evaluator for computing InterModel Vigorish (IMV) and SHAP-IMV values for binary classification.
This class implements the IMV framework which measures the information gain from adding features to a model. It supports binary classification with k-fold cross-validation or train-test split evaluation strategies.
Core IMV functions (ll, get_w, calculate_imv) are imported from imvpy.core, ensuring consistency across all IMV implementations.
Parameters:
-
data(DataFrame) –Complete-case feature and binary-outcome data.
-
outcome_variable(str) –Name of the 0/1 target column.
-
optional_explanatory_variables(list[str]) –Feature universe whose full power set will be evaluated.
-
model_creator(callable) –Zero-argument factory returning a fresh binary classifier with
fitandpredict_proba. Positive-class probability must be column 1. -
split_method(str, default:'kfold') –One of
"kfold","stratified_kfold","train_test_split", or"stratified_train_test_split". Default:"kfold". -
n_splits(int, default:5) –Fold count in K-fold modes. Default: 5.
-
prop_test(float, default:0.2) –Test fraction in holdout modes. Default: 0.2.
-
model_type(str, default:'classification') –Must be
"classification". Default:"classification". -
all_combinations_imv(dict, default:None) –Precomputed coalition mapping in the format returned by :meth:
run_evaluation. Default: None. -
random_seed(int, default:42) –Split random state. Default: 42.
-
n_jobs(int, default:1) –joblib workers across coalitions. Default: 1.
-
verbose(bool, default:False) –Show progress and summaries. Default: False.
Examples:
>>> from sklearn.linear_model import LogisticRegression
>>> from imvpy import BinaryIMV
>>>
>>> evaluator = BinaryIMV(
... data=df,
... outcome_variable='target',
... optional_explanatory_variables=['age', 'income', 'education'],
... model_creator=lambda: LogisticRegression(max_iter=1000),
... split_method='kfold',
... n_splits=5,
... prop_test=0.2,
... model_type='classification'
... )
>>> evaluator.run_evaluation()
>>> evaluator.evaluate_imvshapley()
Source code in src/imvpy/shap_imv/evaluator.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 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 350 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 413 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 476 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 562 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 | |
calculate_imv_score
¶
Calculate IMV score comparing two trained models.
Uses the shared calculate_imv() function from imvpy.core. Computes IMV by comparing predictions from a basic model (intercept-only) and an enhanced binary classifier (with features).
Parameters:
-
model_basic(object) –Trained basic/null model (intercept only)
-
model_enhanced(object) –Trained enhanced model with features
-
X_basic(DataFrame) –Basic features (constant only)
-
X_enhanced(DataFrame) –Enhanced features (all variables)
-
y(Series) –True labels/targets
Returns:
-
float–IMV score for this model comparison
Raises:
-
ValueError–If model_type is not 'classification'
Note
Uses predict_proba()[:, 1] for positive class probability.
Source code in src/imvpy/shap_imv/evaluator.py
compute_imv_method
¶
Compute IMV for a specific combination of features.
Trains models for a given feature subset and evaluates IMV score using either k-fold cross-validation or train-test split.
Parameters:
-
combination(tuple) –Tuple of feature names to include in the model
Returns:
-
tuple–(combination, mean_imv_score, list_of_fold_scores) - combination: Input feature tuple - mean_imv_score: Average IMV across all folds/splits - list_of_fold_scores: Individual IMV score for each fold
Note
- Always includes 'constant' column for intercept
- Basic model uses only constant, enhanced model uses all features in combination
- For kfold: Returns mean across all folds
- For train_test_split: Returns single score in a list
Source code in src/imvpy/shap_imv/evaluator.py
run_evaluation
¶
Run IMV evaluation for all possible feature combinations.
Computes IMV scores for all 2^n combinations of features (power set), where n is the number of optional explanatory variables. Uses parallel processing to speed up computation.
Side Effects
- Populates self.all_combinations_imv with results
- Prints the best performing feature combination when
verbose=True
Returns:
-
dict–Mapping from each feature tuple to
(mean_imv, list_of_fold_scores). The same mapping is assigned toself.all_combinations_imv.
Process
- Generate all possible feature subsets (including empty set)
- Compute IMV for each subset with the configured joblib worker count
- Store results as {combination: (mean_imv, fold_scores)}
- Identify and report best performing combination
Note
- Computational complexity: O(2^n * k * m) where n=features, k=folds, m=training time per model
- Uses joblib.Parallel with
self.n_jobs(default 1) - Progress shown via tqdm progress bar
Example
evaluator.run_evaluation() Evaluating IMV combinations: 100%|██████████| 8/8 Best explanatory variables' combination: ('age', 'income'), with the highest IMV score: 0.234
Source code in src/imvpy/shap_imv/evaluator.py
plot_single_var_combinations_layered_violin_centralized_zero
¶
Plot violin plot for single-variable IMV scores.
Creates a horizontal violin plot showing the distribution of IMV scores across folds for each individual variable (models with only one feature). Useful for understanding individual variable performance and consistency.
Parameters:
-
ax(Axes, default:None) –Axes to plot on. If None, creates new figure.
-
figsize(tuple, default:(6, 4)) –Figure size if creating new figure. Default: (6, 4)
Returns:
-
tuple or Axes or None–- If ax=None: Returns (fig, ax) tuple - If ax provided: Returns ax - If no single-variable combinations: Returns None
Visualization Details
- X-axis: IMV scores
- Y-axis: Variable names
- Inner quartiles shown within violins
- Color scheme: canonical IMV publication palette
Note
Must call run_evaluation() before plotting. Only shows variables used individually (combination length = 1).
Example
fig, ax = evaluator.plot_single_var_combinations_layered_violin_centralized_zero() plt.show()
Source code in src/imvpy/shap_imv/evaluator.py
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 350 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 | |
calculate_weight
staticmethod
¶
Calculate Shapley weight for a given coalition size.
Computes the weight used in Shapley value calculation, which depends on the size of the feature subset (coalition) and total number of features.
Parameters:
-
s_size(int) –Size of the current feature subset (number of features)
-
n(int) –Total number of features
Returns:
-
float–Shapley weight for this coalition size
Mathematical Formula
weight = |S|! * (n - |S| - 1)! / n! where |S| is the subset size
Note
This weight ensures fair attribution in cooperative game theory. All weights for a given feature sum to 1.0.
Source code in src/imvpy/shap_imv/evaluator.py
calculate_imvshapley_value
¶
Calculate SHAP-IMV value for a single variable.
Computes the Shapley value using IMV as the characteristic function. This provides a fair attribution of information gain to each feature by considering all possible feature coalitions.
Parameters:
-
variable(str) –Name of the variable to compute SHAP-IMV for
Returns:
-
float–SHAP-IMV value for the variable (rounded to 3 decimals)
Mathematical Formula
SHAP-IMV(v) = Σ [weight(|S|, n) * (IMV(S ∪ {v}) - IMV(S))] where sum is over all subsets S not containing v
Process
- For each combination containing the variable
- Compute marginal contribution: IMV(with v) - IMV(without v)
- Weight by Shapley weight based on coalition size
- Sum all weighted contributions
Interpretation
- Positive: Variable adds information on average
- Negative: Variable reduces model information (rare)
- Magnitude: Average marginal contribution across all contexts
Warns:
-
IncompleteCoalitionWarning–If the supplied coalition mapping lacks a subset required for the exact Shapley sum. The compatibility fallback is not a valid additive Shapley value.
Note
Prints the computed value only when verbose=True and always
returns it. Call run_evaluation() first to populate
all_combinations_imv.
Source code in src/imvpy/shap_imv/evaluator.py
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 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 | |
evaluate_imvshapley
¶
Compute and visualize SHAP-IMV values for all variables.
Calculates SHAP-IMV values for each feature and creates a horizontal bar plot showing feature importance ranked from highest to lowest.
Parameters:
-
ax(Axes, default:None) –Axes to plot on. If None, creates new figure.
-
figsize(tuple, default:(12, 4)) –Base figure size. Height auto-adjusts based on number of variables (minimum 0.5 inches per variable). Default: (12, 4)
Returns:
-
tuple or Axes–- If ax=None: Returns (fig, ax) tuple - If ax provided: Returns ax
Visualization Details
- Bars sorted by SHAP-IMV value (descending)
- Color gradient from the canonical IMV publication palette
- Thin black bar outlines and dashed value-axis grid
- Values displayed on bars
Process
- Compute SHAP-IMV for each variable
- Sort variables by importance (descending)
- Create colored horizontal bar plot
- Annotate bars with numeric values
Note
Must call run_evaluation() before this method. Prints individual
SHAP-IMV values during computation only when verbose=True.
Example
fig, ax = evaluator.evaluate_imvshapley(figsize=(14, 6)) SHAP-IMV value for variable age: 0.145 SHAP-IMV value for variable income: 0.112 ... plt.tight_layout() plt.show()
Source code in src/imvpy/shap_imv/evaluator.py
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 562 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 | |
Incomplete coalition warning¶
imvpy.shap_imv.IncompleteCoalitionWarning
¶
Bases: UserWarning
The coalition results are missing subsets the exact Shapley sum requires.
Emitted by :meth:BinaryIMV.calculate_imvshapley_value. Absent coalitions are
substituted with IMV 0, so the result is not a valid Shapley value and will
not satisfy additivity.
Source code in src/imvpy/shap_imv/evaluator.py
IMVEvaluator is an identity alias of BinaryIMV. It is documented in
Compatibility but should not be used in new
code.