Interpret
This is the reference to the functions contained in
interpret
. For now, they are all accesible directly
through machine-learning-datasets
and you don't
need to use the interpret
namespace.
Common Utility Functions
approx_predict_ts(X, X_df, gen_X, ts_mdl, dist_metric='euclidean', lookback=0, filt_fn=None, X_scaler=None, y_scaler=None, progress_bar=False, no_info=None)
Approximately predicts time series values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
ArrayLike
|
The input time series data. |
required |
X_df |
DataFrame
|
The input time series data as a DataFrame. |
required |
gen_X |
ndarray
|
The generated time series data. |
required |
ts_mdl |
BaseModelProtocol
|
The time series model used for prediction. |
required |
dist_metric |
Optional[str]
|
The distance metric used for finding closest datapoint. Defaults to 'euclidean'. |
'euclidean'
|
lookback |
Optional[int]
|
The number of previous time steps to consider for prediction. Defaults to 0. |
0
|
filt_fn |
Optional[Callable]
|
The function used for filtering the input data. Defaults to None. |
None
|
X_scaler |
Optional[BaseTransformerProtocol]
|
The scaler used for scaling the input data. Defaults to None. |
None
|
y_scaler |
Optional[BaseTransformerProtocol]
|
The scaler used for scaling the output data. Defaults to None. |
None
|
progress_bar |
Optional[bool]
|
Whether to display a progress bar during prediction. Defaults to False. |
False
|
no_info |
Optional[ndarray]
|
The value to return if no predictions are made. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: The predicted time series values. |
Raises:
Type | Description |
---|---|
ModuleNotFoundError
|
If |
Source code in machine_learning_datasets/interpret.py
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 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 |
|
compare_confusion_matrices(y_true_1, y_pred_1, y_true_2, y_pred_2, group_1, group_2, plot=True, compare_fpr=False, save_name=None)
Compare confusion matrices for two different groups.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y_true_1 |
ArrayLike
|
True labels for group 1. |
required |
y_pred_1 |
ArrayLike
|
Predicted labels for group 1. |
required |
y_true_2 |
ArrayLike
|
True labels for group 2. |
required |
y_pred_2 |
ArrayLike
|
Predicted labels for group 2. |
required |
group_1 |
str
|
Name of group 1. |
required |
group_2 |
str
|
Name of group 2. |
required |
plot |
Optional[bool], default=True
|
Whether to plot the confusion matrices. |
True
|
compare_fpr |
Optional[bool], default=False
|
Whether to compare the False Positive Rates (FPR) of the two groups. |
False
|
save_name |
Optional[str], default=None
|
Name to save the plot if |
None
|
Returns:
Type | Description |
---|---|
Optional[float]
|
Optional[float]: The ratio between the FPRs of the two groups if |
Source code in machine_learning_datasets/interpret.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
compare_df_plots(df1, df2, title1=None, title2=None, y_label=None, x_label=None, y_formatter=None, x_formatter=None, plot_args=None, save_name=None)
Compare and plot two DataFrames side by side.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df1 |
DataFrame
|
The first DataFrame to compare. |
required |
df2 |
DataFrame
|
The second DataFrame to compare. |
required |
title1 |
Optional[str]
|
Title for the first plot. Defaults to None. |
None
|
title2 |
Optional[str]
|
Title for the second plot. Defaults to None. |
None
|
y_label |
Optional[str]
|
Label for the y-axis. Defaults to None. |
None
|
x_label |
Optional[str]
|
Label for the x-axis. Defaults to None. |
None
|
y_formatter |
Optional[Formatter]
|
Formatter for the y-axis tick labels. Defaults to None. |
None
|
x_formatter |
Optional[Formatter]
|
Formatter for the x-axis tick labels. Defaults to None. |
None
|
plot_args |
Optional[Dict]
|
Additional arguments for the plot. Defaults to None. |
None
|
save_name |
Optional[str]
|
Name to save the plot as. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in machine_learning_datasets/interpret.py
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 |
|
compare_image_predictions(X_mod, X_orig, y_mod, y_orig, y_mod_prob=None, y_orig_prob=None, num_samples=3, title_mod_prefix='Modified: ', title_orig_prefix='Original: ', calc_difference=True, title_difference_prefix='Average difference: ', max_width=14, use_misclass=True, save_name=None)
Compare image predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X_mod |
ndarray
|
Modified images. |
required |
X_orig |
ndarray
|
Original images. |
required |
y_mod |
Union[ndarray, list, tuple]
|
Modified labels. |
required |
y_orig |
Union[ndarray, list, tuple]
|
Original labels. |
required |
y_mod_prob |
Optional[Union[ndarray, list, tuple]]
|
Probabilities of modified labels. Default is None. |
None
|
y_orig_prob |
Optional[Union[ndarray, list, tuple]]
|
Probabilities of original labels. Default is None. |
None
|
num_samples |
Optional[int]
|
Number of samples to display. Default is 3. |
3
|
title_mod_prefix |
Optional[str]
|
Prefix for modified image titles. Default is "Modified: ". |
'Modified: '
|
title_orig_prefix |
Optional[str]
|
Prefix for original image titles. Default is "Original: ". |
'Original: '
|
calc_difference |
Optional[bool]
|
Whether to calculate and display the average difference between modified and original images. Default is True. |
True
|
title_difference_prefix |
Optional[str]
|
Prefix for the average difference title. Default is "Average difference: ". |
'Average difference: '
|
max_width |
Optional[int]
|
Maximum width of the displayed images. Default is 14. |
14
|
use_misclass |
Optional[bool]
|
Whether to use misclassified samples for display. Default is True. |
True
|
save_name |
Optional[str]
|
Name to save the comparison image. Default is None. |
None
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in machine_learning_datasets/interpret.py
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 |
|
compare_img_pred_viz(img_np, viz_np, y_true, y_pred, probs_s=None, title=None, save_name=None)
Compare and visualize the image, predicted label, and probability distribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
img_np |
ndarray
|
The original image as a NumPy array. |
required |
viz_np |
ndarray
|
The visualization image as a NumPy array. |
required |
y_true |
Union[str, int, float]
|
The true label of the image. |
required |
y_pred |
Union[str, int, float]
|
The predicted label of the image. |
required |
probs_s |
Optional[Series]
|
The probability distribution as a Pandas Series. Defaults to None. |
None
|
title |
Optional[str]
|
The title of the plot. Defaults to None. |
None
|
save_name |
Optional[str]
|
The name to save the plot. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in machine_learning_datasets/interpret.py
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 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 |
|
compute_aif_metrics(dataset_true, dataset_pred, unprivileged_groups, privileged_groups, ret_eval_dict=True)
Compute various fairness metrics using the AIF360 library.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_true |
BaseAIF360DSProtocol
|
The true dataset. |
required |
dataset_pred |
BaseAIF360DSProtocol
|
The predicted dataset. |
required |
unprivileged_groups |
List[Dict]
|
List of unprivileged groups. |
required |
privileged_groups |
List[Dict]
|
List of privileged groups. |
required |
ret_eval_dict |
Optional[bool]
|
Whether to return the evaluation dictionary. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Tuple[Optional[Dict], BaseAIF360MetricProtocol]
|
Tuple[Optional[Dict], BaseAIF360MetricProtocol]: A tuple containing the evaluation dictionary (if ret_eval_dict is True) and the AIF360 metric object. |
Raises:
Type | Description |
---|---|
ModuleNotFoundError
|
If the |
Note
This function requires the aif360
library to be installed in order to execute.
Example
dataset_true = ... dataset_pred = ... unprivileged_groups = ... privileged_groups = ... metrics_dict, metrics_cls = compute_aif_metrics(dataset_true, dataset_pred, unprivileged_groups, privileged_groups)
Source code in machine_learning_datasets/interpret.py
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 |
|
create_attribution_grid(attribution, cmap=None, cmap_norm=None)
Create an attribution grid from a given attribution map.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
attribution |
ndarray
|
The attribution map with shape (n, w, h), where n is the number of images and w, h are the width and height of each image. |
required |
cmap |
Optional[Union[str, Colormap]]
|
The colormap to be applied to the grid image. Defaults to None. |
None
|
cmap_norm |
Optional[Union[str, Colormap]]
|
The normalization to be applied to the colormap. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: The attribution grid image with shape (grid_size * w, grid_size * h), where grid_size is the size of the grid calculated as the ceiling of the square root of n. |
Raises:
Type | Description |
---|---|
ValueError
|
If the attribution map does not have 3 dimensions. |
Source code in machine_learning_datasets/interpret.py
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 |
|
create_decision_plot(X, y, model, feature_index, feature_names, X_highlight, filler_feature_values, filler_feature_ranges=None, ax=None, add_constant=True)
Create a decision plot.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
ArrayLike
|
The input feature matrix. |
required |
y |
ArrayLike
|
The target variable. |
required |
model |
BaseModelProtocol
|
The trained model. |
required |
feature_index |
Union[list, tuple]
|
The indices of the features to be used in the plot. |
required |
feature_names |
Union[list, tuple]
|
The names of the features. |
required |
X_highlight |
ndarray
|
The data points to be highlighted in the plot. |
required |
filler_feature_values |
Dict
|
The values to fill the non-selected features. |
required |
filler_feature_ranges |
Optional[Dict]
|
The ranges of the filler features. Defaults to None. |
None
|
ax |
Optional[_AxesBase]
|
The matplotlib axes to plot on. Defaults to None. |
None
|
add_constant |
Optional[bool]
|
Whether to add a constant feature. Defaults to True. |
True
|
Returns:
Name | Type | Description |
---|---|---|
_AxesBase |
_AxesBase
|
The matplotlib axes object containing the decision plot. |
Source code in machine_learning_datasets/interpret.py
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 |
|
describe_cf_instance(X, explanation, class_names, cat_vars_ohe=None, category_map=None, feature_names=None, eps=0.01)
Describes the counterfactual instance and its perturbations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
ArrayLike
|
The original instance. |
required |
explanation |
BaseAlibiExplanationProtocol
|
The explanation object containing the counterfactual instance. |
required |
class_names |
Union[list, Dict]
|
The names of the classes. |
required |
cat_vars_ohe |
Optional[BaseTransformerProtocol]
|
The transformer for one-hot encoded categorical variables. Default is None. |
None
|
category_map |
Optional[Dict]
|
The mapping of categorical variables. Default is None. |
None
|
feature_names |
list
|
The names of the features. Default is None. |
None
|
eps |
Optional[float]
|
The threshold for numerical feature perturbations. Default is 1e-2. |
0.01
|
Raises:
Type | Description |
---|---|
ModuleNotFoundError
|
If |
Returns:
Type | Description |
---|---|
None
|
None |
Note
This function requires the alibi
library to be installed.
Source code in machine_learning_datasets/interpret.py
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 |
|
plot_prob_contour_map(x, y, z, x_intervals=7, y_intervals=7, use_quantiles=False, plot_type='contour', xlabel=None, ylabel=None, title=None, model=None, X_df=None, x_col=None, y_col=None, cmap=None, diff_to_mean=False, annotate=False, color='w', save_name=None)
Plots a probability contour map.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Union[str, Series, ndarray]
|
The x-axis values. Can be a string, pandas series, or numpy array. |
required |
y |
Union[str, Series, ndarray]
|
The y-axis values. Can be a string, pandas series, or numpy array. |
required |
z |
Union[str, Series, ndarray]
|
The z-axis values. Can be a string, pandas series, or numpy array. |
required |
x_intervals |
Optional[int]
|
The number of intervals to divide the x-axis into. Default is 7. |
7
|
y_intervals |
Optional[int]
|
The number of intervals to divide the y-axis into. Default is 7. |
7
|
use_quantiles |
Optional[bool]
|
Whether to use quantiles for discretizing the x and y values. Default is False. |
False
|
plot_type |
Optional[Literal['contour', 'grid']]
|
The type of plot to generate. Default is 'contour'. |
'contour'
|
xlabel |
Optional[str]
|
The label for the x-axis. Default is None. |
None
|
ylabel |
Optional[str]
|
The label for the y-axis. Default is None. |
None
|
title |
Optional[str]
|
The title of the plot. Default is None. |
None
|
model |
Optional[BaseModelProtocol]
|
The model used for prediction. Default is None. |
None
|
X_df |
Optional[DataFrame]
|
The dataset used for prediction. Default is None. |
None
|
x_col |
Optional[str]
|
The column name for the x values in the dataset. Default is None. |
None
|
y_col |
Optional[str]
|
The column name for the y values in the dataset. Default is None. |
None
|
cmap |
Optional[Union[str, Colormap]]
|
The colormap to use for the plot. Default is None. |
None
|
diff_to_mean |
Optional[bool]
|
Whether to subtract the mean value from the z values. Default is False. |
False
|
annotate |
Optional[bool]
|
Whether to annotate the grid plot with the z values. Default is False. |
False
|
color |
Optional[str]
|
The color of the annotations. Default is "w". |
'w'
|
save_name |
Optional[str]
|
The name of the file to save the plot. Default is None. |
None
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in machine_learning_datasets/interpret.py
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 |
|
plot_prob_progression(x, y, x_intervals=7, use_quantiles=False, xlabel=None, ylabel='Observations', title=None, model=None, X_df=None, x_col=None, mean_line=False, figsize=None, x_margin=0.01, save_name=None)
Plots the progression of probabilities for a given dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Union[str, Series, ndarray]
|
The input data for the x-axis. Can be a string, pandas series, or numpy array. |
required |
y |
Union[str, Series, ndarray]
|
The input data for the y-axis. Can be a string, pandas series, or numpy array. |
required |
x_intervals |
Optional[int]
|
The number of intervals to divide the x-axis into. Default is 7. |
7
|
use_quantiles |
Optional[bool]
|
Whether to use quantiles for dividing the x-axis intervals. Default is False. |
False
|
xlabel |
Optional[str]
|
The label for the x-axis. Default is None. |
None
|
ylabel |
Optional[str]
|
The label for the y-axis. Default is 'Observations'. |
'Observations'
|
title |
Optional[str]
|
The title of the plot. Default is None. |
None
|
model |
Optional[BaseModelProtocol]
|
The model used for predictions. Default is None. |
None
|
X_df |
Optional[str]
|
The dataset used for predictions. Default is None. |
None
|
x_col |
Optional[str]
|
The column name for the x-axis data in the dataset. Default is None. |
None
|
mean_line |
Optional[bool]
|
Whether to plot a dashed line representing the mean of the y-axis data. Default is False. |
False
|
figsize |
Optional[Tuple]
|
The size of the figure. Default is None. |
None
|
x_margin |
Optional[float]
|
The margin for the x-axis. Default is 0.01. |
0.01
|
save_name |
Optional[str]
|
The name to save the plot as. Default is None. |
None
|
Returns:
Type | Description |
---|---|
None
|
None |
Raises:
Type | Description |
---|---|
TypeError
|
If x and y are not lists, pandas series, or numpy arrays. |
ValueError
|
If x and y do not have a single dimension, x_intervals is less than 2, or y dimension is not a list, pandas series, or numpy array of integers or floats. |
ValueError
|
If y dimension has less than two values, or if it has two values but the max is not 1 or the min is not 0, or if it has more than two values but the range is not between 0 and 1. |
Source code in machine_learning_datasets/interpret.py
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 |
|
profits_by_thresh(y_profits, y_pred, threshs, var_costs=1, min_profit=None, fixed_costs=0)
Calculate profits, costs, and return on investment (ROI) based on a given threshold.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y_profits |
ndarray
|
Array of profits. |
required |
y_pred |
ndarray
|
Array of predicted values. |
required |
threshs |
Union[list, tuple, ndarray]
|
List, tuple, or array of threshold values. |
required |
var_costs |
Optional[Union[int, float]], default=1
|
Variable costs per unit. |
1
|
min_profit |
Optional[Union[int, float]], default=None
|
Minimum profit threshold. |
None
|
fixed_costs |
Optional[Union[int, float]], default=0
|
Fixed costs. |
0
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: DataFrame containing profits, costs, and ROI for each threshold. |
Example
y_profits = np.array([10, 20, 30, 40, 50]) y_pred = np.array([0.2, 0.4, 0.6, 0.8, 1.0]) threshs = [0.3, 0.6, 0.9] var_costs = 2 min_profit = 15 fixed_costs = 5
profits_by_thresh(y_profits, y_pred, threshs, var_costs, min_profit, fixed_costs)
Output: revenue costs profit roi 0.3 70 15 55 3.666667 0.6 90 20 70 3.500000 0.9 100 25 75 3.000000
Source code in machine_learning_datasets/interpret.py
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 |
|