API Reference
shapleyx.rshdmr(data_file, polys=[10, 5], n_jobs=-1, test_size=0.25, limit=2.0, k_best=1, p_average=2, n_iter=300, verbose=False, method='ard', starting_iter=5, resampling=True, CI=95.0, number_of_resamples=1000, cv_tol=0.05, cv_method='ridge', ard_algorithm='sequential', threshold_lambda=10000.0, cv_folds=10, return_std=False, ard_tol=0.001)
Global Sensitivity Analysis using RS-HDMR with RVM or OMP and linear regression. Examples:
This class implements a global sensitivity analysis framework combining:
- Sparse Random Sampling (SRS)
- High Dimensional Model Representation (HDMR)
- RVM (Relevance Vector Machine) or OMP (Orthogonal Matching Pursuit) for parameter selection
- Linear regression for parameter refinement
| Parameters: |
|
|---|
| Attributes: |
|
|---|
Examples:
# Initialize analyzer with ARD controls
analyzer = rshdmr(data_file='input.csv', polys=[10,5], method='ard_cv',
cv_method='bayesian', ard_algorithm='sequential',
threshold_lambda=1e4, cv_folds=10, return_std=True)
# Run analysis
sobol, shapley, total = analyzer.run_all()
# Make predictions
predictions = analyzer.predict(new_data)
# Get sensitivity indices
pawn_results = analyzer.get_pawn(S=10)
Todo:
- Improve memory management for large expansions
Source code in shapleyx/shapleyx.py
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 | |
eval_all_indices()
Evaluates Sobol indices, Shapley effects, and total sensitivity indices.
Uses the indicies.eval_indices utility.
Updates the following attributes
self.results (pd.DataFrame): DataFrame containing Sobol indices results. self.non_zero_coefficients (pd.DataFrame): DataFrame of non-zero coefficients. self.shap (pd.DataFrame): DataFrame containing Shapley effects. self.total (pd.DataFrame): DataFrame containing total sensitivity indices.
Source code in shapleyx/shapleyx.py
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 | |
get_deltax(num_unconditioned, delta_samples)
Calculate delta indices for the given number of unconditioned variables and delta samples.
This method initializes a DeltaX instance using the provided data and parameters, then computes the delta indices based on the specified number of unconditioned variables and delta samples.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in shapleyx/shapleyx.py
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 | |
get_hx(num_unconditioned, delta_samples)
Calculate delta indices for the given number of unconditioned variables and delta samples.
This method initializes a DeltaX instance using the provided data and parameters, then computes the delta indices based on the specified number of unconditioned variables and delta samples.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in shapleyx/shapleyx.py
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 | |
get_mc_shapley(joint=None, corr=None, N=10000, method='exhaustive', n_perm=1000, B=0, alpha=0.05, random_state=None, f=None, progress=False, k_max=False)
Compute Shapley effects via Monte Carlo with correlated inputs.
Uses a Monte Carlo approach to estimate Shapley effects when input variables may be correlated. The model function can be the trained surrogate model (default) or an arbitrary user-defined function.
Two computation methods are available:
- 'exhaustive': Enumerates all 2^d - 1 non-empty subsets.
Exact but computationally expensive for large d.
- 'permutation': Uses random permutations with lazy caching.
More scalable for higher dimensions.
Bootstrap confidence intervals are available for both methods.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
Using the trained surrogate model with independent inputs:
>>> analyzer = rshdmr(data_file='data.csv', polys=[10, 5])
>>> sobol, shapley, total = analyzer.run_all()
>>> mc_results = analyzer.get_mc_shapley(N=5000, B=500)
Using the surrogate model with a correlation matrix:
>>> corr = np.array([[1.0, 0.5, 0.0],
... [0.5, 1.0, 0.0],
... [0.0, 0.0, 1.0]])
>>> mc_results = analyzer.get_mc_shapley(corr=corr, N=5000)
Using a user-defined function with a custom distribution:
>>> def my_model(x):
... return x[0]**2 + 2*x[1]
>>> joint = MultivariateNormal(
... mean=[0, 0], cov=[[1, 0.5], [0.5, 1]]
... )
>>> mc_results = analyzer.get_mc_shapley(
... joint=joint, f=my_model, N=5000
... )
Source code in shapleyx/shapleyx.py
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 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 | |
get_pawn(S=10)
Estimates PAWN sensitivity indices directly from data.
Uses the pawn.estimate_pawn utility.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in shapleyx/shapleyx.py
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | |
get_pawnx(num_unconditioned, num_conditioned, num_ks_samples, alpha=0.05)
Calculates PAWN sensitivity indices using the surrogate model.
Uses the pawn.pawnx utility.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in shapleyx/shapleyx.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 | |
get_pruned_data()
Generates a pruned dataset containing only the features with non-zero coefficients.
This method creates a new DataFrame that includes only the columns from the original
dataset (X_T_L) that correspond to the labels with non-zero coefficients. Additionally,
it includes the target variable (Y).
In streaming mode the active columns are computed on-the-fly from the lazy basis matrix instead of being sliced from a dense DataFrame.
| Returns: |
|
|---|
Source code in shapleyx/shapleyx.py
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 | |
legendre_expand()
Performs Legendre polynomial expansion on the transformed data self.X_T.
Uses the legendre.legendre_expand utility.
For streaming methods ('omp_stream', 'omp_cv_stream'), builds a
:class:LazyBasisMatrix instead of materialising the full design
matrix, and creates a lightweight DataFrame with column labels only
for downstream compatibility.
Updates the following attributes
self.primitive_variables: Primitive variables from the expansion. self.poly_orders: Polynomial orders used in the expansion. self.X_T_L (pd.DataFrame): The expanded data matrix (dense) or a label-only DataFrame (streaming). self._lazy_basis: LazyBasisMatrix (streaming only).
Source code in shapleyx/shapleyx.py
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 | |
predict(X)
Predicts output for new input data using the trained surrogate model.
If the surrogate model (self.surrogate_model) doesn't exist, it first
creates and fits one using predictor.surrogate.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in shapleyx/shapleyx.py
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 | |
read_data(data_file)
Reads data from a file or DataFrame.
Initializes the self.X (features) and self.Y (target) attributes.
| Parameters: |
|
|---|
| Raises: |
|
|---|
Source code in shapleyx/shapleyx.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
run_all()
Execute a complete sequence of steps for RS-HDMR (Random Sampling High-Dimensional Model Representation) analysis.
This method performs the following steps in sequence:
- Transforms the input data to a unit hypercube.
- Builds basis functions using Legendre polynomials.
- Runs regression analysis to fit the model.
- Calculates and displays RS-HDMR model performance statistics.
- Evaluates Sobol indices to quantify the contribution of each input variable to the output variance.
- Calculates Shapley effects to measure the importance of each input variable.
- Computes the total index to assess the overall impact of input variables.
- If resampling is enabled, performs bootstrap resampling to estimate confidence intervals for Sobol indices and Shapley effects.
- Prints a completion message with a randomly selected quote.
| Returns: |
|
|---|
Notes
- The method assumes that the necessary data and configurations are already set in the class instance.
- If resampling is enabled (
self.resamplingis True), confidence intervals (CIs) are calculated for Sobol indices and Shapley effects. - The method uses helper functions like
transform_data,legendre_expand,run_regression,stats,plot_hdmr,eval_sobol_indices,get_shapley, andget_total_indexto perform specific tasks. - The completion message includes a randomly selected quote for a touch of inspiration.
Example
sobol_indices, shapley_effects, total_index = instance.run_all() print(sobol_indices) print(shapley_effects) print(total_index)
Source code in shapleyx/shapleyx.py
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 | |
run_plot_hdmr()
Plots the High-Dimensional Model Representation (HDMR) of the model's predictions.
This method uses the plot_hdmr function from the stats module to visualize the
HDMR of the actual values (self.Y) against the predicted values (self.y_pred).
| Returns: |
|
|---|
Source code in shapleyx/shapleyx.py
338 339 340 341 342 343 344 345 346 347 348 | |
run_regression()
Runs the regression analysis using the specified method.
Uses the regression.regression utility based on self.method.
Updates the following attributes
self.coef_ (np.array): The regression coefficients obtained from the fit. self.y_pred (np.array): The predicted values based on the fitted model.
Source code in shapleyx/shapleyx.py
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 | |
run_stats()
Calculates and stores evaluation statistics for the fitted model.
Uses the stats.stats utility.
Updates the following attributes
self.evs (dict): A dictionary containing evaluation statistics (e.g., R^2, MSE).
Source code in shapleyx/shapleyx.py
328 329 330 331 332 333 334 335 336 | |
transform_data()
Transforms the input data self.X into a unit hypercube.
Updates the following attributes
self.ranges (list): The ranges (min, max) of the original data features. self.X_T (pd.DataFrame): The transformed data matrix within the unit hypercube.
Source code in shapleyx/shapleyx.py
247 248 249 250 251 252 253 254 255 256 257 | |