Anchors and Counterfactual Explanations
local graph
uuid: “node-book_interpretable-machine-learning-with-python-second-edition_chapter-06-anchors-and-counterfactual-explanations”
filename_must_equal_uuid: true
node_id: “uuid”
node_type: “chapter-node”
schema_profile: world.chapter_node.v1
status: “active”
entropy: “high”
manifold: “world”
domain:
“imagineworld.net”
authority: “informs”
layer: “corpus”
book_title: “Interpretable Machine Learning with Python - Second Edition”
book_subtitle: “[Subtitle Not Provided in Source]”
book_author: “[Author Not Provided in Source]”
book_publisher: “Packt Publishing (Inferred from content)”
book_year: “[Year Not Provided in Source]”
book_edition: “Second Edition”
total_chapters: 14
total_source_pages: “[Source Page Count Unknown]”
ocr_source: “Verbatim text provided by user”
ocr_quality_class: “digital_native”
verification_status: “unsampled”
stitched_by: “manual_conversion_agent”
generated_at: “2023-10-27”
governed_by:
“kernel-000-identity”
“kernel-009-provenance”
“kernel-012-entropy”
“kernel-009-provenance”
anchors_into:
“eng-04-the-lawful-node-contract_v0.0.1”
“eng-05-the-profile-and-rosetta-system_v0.0.1”
“eng-08-the-parse-pipeline_v0.0.1”
“eng-09-the-validation-engine_v0.0.1”
“eng-12-the-in-memory-graph-and-traversal_v0.0.1”
grounded_by:
“kernel-001-coherence”
“kernel-013-singularity-interface”
source_router:
“library-reference_imagineworld-kb”
“plane-world-domain-imagineworld-index-master-root-03292026_v0.1.1”
pillar_membership: “J — architecture_design_craft”
book_parent: “node-book_interpretable-machine-learning-with-python-second-edition”
previous_chapter: “node-book_interpretable-machine-learning-with-python-second-edition_chapter-05-local-model-agnostic-interpretation-methods”
next_chapter: “node-book_interpretable-machine-learning-with-python-second-edition_chapter-07-visualizing-convolutional-neural-networks”
chapter_num: 6
chapter_title: “Anchors and Counterfactual Explanations”
body_bytes: 26034
validation:
filename_must_equal_uuid: True
verbatim_body_from_ocr: True
Chapter 6 — Anchors and Counterfactual Explanations
In previous chapters, we learned how to attribute model decisions to features and their interactions with state-of-the-art global and local model interpretation methods. However, the decision boundaries are not always easy to define or interpret with these methods. Wouldn’t it be nice to be able to derive human-interpretable rules from model interpretation methods? In this chapter, we will cover a few human-interpretable, local, classification-only model interpretation methods. We will first learn how to use scoped rules called anchors to explain complex models with statements such as if X conditions are met, then Y is the outcome. Then, we will explore counterfactual explanations that follow the form if Z conditions aren’t met, then Y is not the outcome.
These are the main topics we are going to cover in this chapter:
Understanding anchor explanations
Exploring counterfactual explanations
Let’s begin!
Technical requirements
This chapter’s example uses the mldatasets, pandas, numpy, sklearn, catboost, matplotlib, seaborn, alibi, tensorflow, shap, and witwidget libraries. Instructions on how to install all of these libraries are in the Preface.
The code for this chapter is located here: https://packt.link/tH0y7.
The mission
In the United States, for the last two decades, private companies and nonprofits have developed criminal Risk Assessment Instruments/Tools (RAIs), most of which employ statistical models. As many states can no longer afford their large prison populations, these methods have increased in popularity, guiding judges and parole boards through every step of the prison system.
These are high-impact decisions that can determine if a person is released from prison. Can we afford for these decisions to be wrong? Can we accept the recommendations from these systems without understanding why they were made? Worst of all, we don’t exactly know how an assessment was made. The risk is usually calculated with a white-box model, but, in practice, a black-box model is used because it is proprietary. Predictive performance is also relatively low, with median AUC scores for a sample of nine tools ranging between 0.57 and 0.74 according to the paper Performance of Recidivism Risk Assessment Instruments in U.S. Correctional Settings.
Even though traditional statistical methods are still the norm for criminal justice models, to improve performance, some researchers have proposed leveraging more complex models, such as Random Forest with larger datasets. Far from being science fiction drawn from Minority Report or Black Mirror, in some countries, scoring people based on their likelihood of engaging in antisocial, or even antipatriotic, behavior with big data and machine learning is already a reality.
As more and more AI solutions attempt to make life-changing predictions about us with our data, fairness must be properly assessed, and all its ethical and practical implications must be adequately discussed. Chapter 1, Interpretation, Interpretability, and Explainability; and Why Does It All Matter?, covered how fairness is an integral concept for machine learning interpretation. You can evaluate fairness in any model, but fairness is especially difficult when it involves human behavior. The dynamics between human psychological, neurological, and sociological factors are extremely complicated. In the context of predicting criminal behavior, it boils down to what factors are potentially to blame for a crime, as it wouldn’t be fair to include anything else in a model, and how these factors interact.
Quantitative criminologists are still debating the best predictors of criminality and their root causes. They’re also debating whether it is ethical to blame a criminal for these factors to begin with. Thankfully, demographic traits such as race, gender, and nationality are no longer used in criminal risk assessments. But this doesn’t mean that these methods are no longer biased. Scholars recognize the problem and are proposing solutions.
This chapter will examine racial bias in one of the most widely used risk assessment tools. Given this topic’s sensitive and relevant nature, it was essential to provide a modicum of context about criminal risk assessment tools and how machine learning and fairness connect with all of them. We won’t go into much more detail, but understanding the context is important to appreciate how machine learning could perpetuate structural inequality and unfair biases.
Now, let’s introduce you to your mission for this chapter!
Unfair bias in recidivism risk assessments
Imagine a scenario of an investigative journalist writing an article on an African American defendant detained while awaiting trial. A tool called Correctional Offender Management Profiling for Alternative Sanction (COMPAS) deemed him as being at risk of recidivism. Recidivism is when someone relapses into criminal behavior. And the score convinced the judge that the defendant had to be detained without considering any other arguments or testimonies. He was locked up for many months, and in the trial, was found not guilty. Over five years have passed since the trial, and he hasn’t been accused of any crime. You could say the prediction for recidivism was a false positive.
The journalist has reached out to you because she would like to ascertain with data science whether there was unfair bias in this case. The COMPAS risk assessment is computed using 137 questions (https://www.documentcloud.org/documents/2702103-Sample-Risk-Assessment-COMPAS-CORE.html). It includes questions such as the following:
“Based on the screener’s observations, is this person a suspected or admitted gang member?”
“How often have you moved in the last 12 months?”
“How often do you have barely enough money to get by?”
Psychometric LIKERT scale questions such as “I have never felt sad about things in my life.”
Even though race is not one of the questions, many of these questions may correlate with race. Not to mention, in some cases, they can be more a question of subjective opinion than fact, and thus be prone to bias.
The journalist cannot provide you with the 137 answered questions or the COMPAS model because this data is not publicly available. However, thankfully, all defendants’ demographic and recidivism data for the same county in Florida is available.
The approach
You have decided to do the following:
Train a proxy model: You don’t have the original features or model, but all is not lost because you have the COMPAS scores—the labels. And we also have features relevant to the problem we can connect to these labels with models. By approximating the COMPAS model via the proxies, you can assess the fairness of the COMPAS decisions. In this chapter, we will train a CatBoost model.
Anchor explanations: Using this method will unearth insights into why the proxy model makes specific predictions using a series of rules called anchors, which tell you where the decision boundaries lie. The boundaries are relevant for our mission because we want to know why the defendant has been wrongfully predicted to recidivate. It’s an approximate boundary to the original model, but there’s still some truth to it.
Counterfactual explanations: While Anchor explains why a decision was made, counterfactuals can be useful to examine why a decision was not made. This is particularly useful in inspecting the fairness of decisions. We will use an unbiased method to find counterfactuals and then use the What-If Tool (WIT) to explore counterfactuals and fairness further.
The preparations
You will find the code for this example here: https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/blob/main/06/Recidivism.ipynb.
Loading the libraries
To run this example, you need to install the following libraries:
mldatasets to load the dataset pandas and numpy to manipulate the dataset sklearn (scikit-learn), and catboost to split the data and fit the models matplotlib, seaborn, alibi, tensorflow, shap, and witwidget to visualize the interpretations You should load all of them first:
import mathimport mldatasetsimport pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn import metricsfrom catboost import CatBoostClassifierimport matplotlib.pyplot as pltimport seaborn as snsfrom alibi.utils.mapping import ohe_to_ord, ord_to_oheimport tensorflow as tffrom alibi.explainers import AnchorTabular, CounterFactualProtoimport shapimport witwidgetfrom witwidget.notebook.visualization import WitWidget, \ WitConfigBuilderLet’s check that TensorFlow has loaded the right version with print(tf.version). It should be 2.0 or above. We should also disable eager execution and verify that it worked with this command. The output should say that it’s False:
tf.compat.v1.disable_eager_execution()print('Eager execution enabled:', tf.executing_eagerly())Understanding and preparing the data
We load the data like this into a DataFrame called recidivism_df:
recidivism_df = mldatasets.load("recidivism-risk", prepare=True)There should be almost 15,000 records and 23 columns. We can verify this was the case with info():
recidivism_df.info()The following output checks out. All features are numeric with no missing values, and categorical features have already been one-hot-encoded for us:
Int64Index: 14788 entries, 0 to 18315Data columns (total 23 columns):Column Non-Null Count Dtype
Section titled “Column Non-Null Count Dtype”0 age 14788 non-null int8 1 juv_fel_count 14788 non-null int8 2 juv_misd_count 14788 non-null int8 3 juv_other_count 14788 non-null int64 4 priors_count 14788 non-null int8 5 is_recid 14788 non-null int8 6 sex_Female 14788 non-null uint8 7 sex_Male 14788 non-null uint8 8 race_African-American 14788 non-null uint8 9 race_Asian 14788 non-null uint8 13 race_Other 14788 non-null uint8 14 c_charge_degree_(F1) 14788 non-null uint8 15 c_charge_degree_(F2) 14788 non-null uint8 21 c_charge_degree_Other 14788 non-null uint8 22 compas_score 14788 non-null int64
The data dictionary
There are only nine features, but they become 22 columns because of the categorical encoding:
age: Continuous; the age of the defendant (between 18 and 96).
juv_fel_count: Ordinal; the number of juvenile felonies (between 0 and 2).
juv_misd_count: Ordinal; the number of juvenile misdemeanors (between 0 and 1).
juv_other_count: Ordinal; the number of juvenile convictions that are neither felonies nor misdemeanors (between 0 and 1).
priors_count: Ordinal; the number of prior crimes committed (between 0 and 13).
is_recid: Binary; did the defendant recidivate within 2 years (1 for yes, 0 for no)?
sex: Categorical; the gender of the defendant.
race: Categorical; the race of the defendant.
c_charge_degree: Categorical; the degree of what the defendant is currently being charged with. The United States classifies criminal offenses as felonies, misdemeanors, and infractions, ordered from most serious to least. These are subclassified in the form of degrees, which go from 1st (most serious offenses) to 3rd or 5th (least severe). However, even though this is standard for federal offenses, it is tailored to state law. For felonies, Florida (http://www.dc.state.fl.us/pub/scoresheet/cpc_manual.pdf) has a level system that determines the severity of a crime regardless of the degree, and this goes from 10 (most severe) to 1 (least).
The categories of this feature are prefixed with F for felonies and M for misdemeanors. They are followed by a number, which is a level for felonies and a degree for misdemeanors.
compas_score: Binary; COMPAS scores defendants as “low,” “medium,” or “high” risk. In practice, “medium” is often treated as “high” by decision-makers, so this feature has been converted to binary to reflect this behavior: 1: high/medium risk and 0: low risk.
Examining predictive bias with confusion matrices
There are two binary features in the dataset. The first one is the recidivism risk prediction made by COMPAS (compas_score). The second one (is_recid) is the ground truth because it’s what happened within 2 years of the defendant’s arrest. Just as you would with the prediction of any model against its training labels, you can build confusion matrices with these two features. scikit-learn can produce one with the confusion_matrix function (cf_matrix), and we can then create a Seaborn heatmap with it. Instead of plotting the number of True Negatives (TNs), False Positives (FPs), False Negatives (FNs), and True Positives (TPs), we can plot percentages with a simple division (cf_matrix/np.sum(cf_matrix)). The other parameters of heatmap only assist with formatting:
cf_matrix = metrics.confusion_matrix( recidivism_df.is_recid, recidivism_df.compas_score)sns.heatmap( cf_matrix/np.sum(cf_matrix), annot=True, fmt='.2%', cmap='Blues', annot_kws={'size':16})The preceding code outputs Figure 6.1. The top-right corner is FPs, which are nearly one-fifth of all predictions, and together with the FNs in the bottom-left corner, they make up over two-thirds:

Figure 6.1: Confusion matrix between the predicted risk of recidivism (compas_score) and the ground truth (is_recid)
Figure 6.1 shows that the COMPAS model’s predictive performance is not very good, especially if we assume that criminal justice decision-makers are taking medium or high risk assessments at face value. It also tells us that FP and FNs occur at a similar rate. Nevertheless, simple visualizations such as the confusion matrix obscure predictive disparities between subgroups of a population. We can quickly compare disparities between two subgroups that historically have been treated differently by the United States criminal justice system. To this end, we first subdivide our DataFrame into two DataFrames: one for Caucasians (recidivism_c_df) and another for African Americans (recidivism_aa_df). Then we can generate confusion matrices for each DataFrame and plot them side by side with the following code:
recidivism_c_df =\recidivism_df[recidivism_df['race_Caucasian'] == 1]recidivism_aa_df =\recidivism_df[recidivism_df['race_African-American'] == 1]_ = mldatasets.compare_confusion_matrices( recidivism_c_df.is_recid, recidivism_c_df.compas_score, recidivism_aa_df.is_recid, recidivism_aa_df.compas_score, 'Caucasian', 'African-American', compare_fpr=True)The preceding snippet generated Figure 6.2. At a glance, you can tell that it’s like the confusion matrix for Caucasians has been flipped 90 degrees to form the African American confusion matrix, and even then, it is still less unfair. Pay close attention to the difference between FPs and TNs. As a Caucasian defendant, a result is more than half as likely to be an FP than a TN, but as an African American, it is a few percentage points more likely. In other words, an African American defendant who doesn’t re-offend is predicted to be at risk of recidivating more than half of the time:

Figure 6.2: Comparison of the confusion matrices for the predicted risk of recidivism (compas_score) and the ground truth (is_recid) between African Americans and Caucasians in the dataset Instead of eyeballing it by looking at the plots, we can measure the False Positive Rate (FPR), which is the ratio between these two measures (FP / (FP + TN)) at risk of recidivism more often.
Data preparation
Before we move on to the modeling and interpretation, we have one last step.
Since prepare=True for the data loading, all we do now is split the data into a training and test dataset. As usual, it is critical to set your random states so that all your findings are reproducible. We will then set y to be our target variable (compas_score) and set X as every other feature except for is_recid, because this is the ground truth. Lastly, we split y and X into train and test datasets as we have before:
rand = 9np.random.seed(rand)y = recidivism_df['compas_score']X = recidivism_df.drop( ['compas_score', 'is_recid'], axis=1).copy()X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=rand)Now, let’s get started!Modeling
First, let’s quickly train the model we will use throughout this chapter.
Proxy models are a means to emulate output from a black-box model just like global surrogate models, which we covered in Chapter 4, Global Model-Agnostic Interpretation Methods. So, are they the same thing? In machine learning, surrogate and proxy are terms that are often used interchangeably. However, semantically, surrogacy relates to substitution and proxy relates more to a representation. So, we call these proxy models to distinguish that we don’t have the exact training data. Therefore, you only represent the original model because you cannot substitute it. For the same reason, unlike interpretation with surrogates, which is best served by simpler models, a proxy is best suited to complex models that can make up for the difference in training data with complexity.
We will train a CatBoost classifier. For those of you who aren’t familiar with CatBoost, it’s an efficient boosted ensemble tree method. It’s similar to LightGBM, except it uses a new technique called Minimal Variance Sampling (MVS) instead of Gradient-Based One-Side Sampling (GOSS). Unlike LightGBM, it grows trees in a balanced fashion. It’s called CatBoost because it can automatically encode categorical features, and it’s particularly good at tackling overfitting, with unbiased treatment of categorical features and class imbalances. We won’t go into a whole lot of detail, but it was chosen for this exercise for those reasons.
As a tree-based model class, you can specify a maximum depth value for CatBoostClassifier. We are setting a relatively high learning_rate value and a lower iterations value (the default is 1,000). Once we have used fit on the model, we can evaluate the results with evaluate_class_mdl:
cb_mdl = CatBoostClassifier( iterations=500, learning_rate=0.5, depth=8)fitted_cb_mdl = cb_mdl.fit( X_train, y_train, verbose=False)y_train_cb_pred, y_test_cb_prob, y_test_cb_pred = \mldatasets.evaluate_class_mdl( fitted_cb_mdl, X_train, X_test, y_train, y_test)You can appreciate the output of evaluate_class_mdl for our CatBoost model in Figure 6.3:

Figure 6.3: Predictive performance of our CatBoost model From the optics of fairness, we care more about FPs than FNs because it’s more unfair to put an innocent person in prison than it is to leave a guilty person on the streets. Therefore, we should aspire to have higher precision than recall. Figure 6.3 confirms this, as well as a healthy ROC curve, ROC-AUC, and MCC.
The predictive performance for the model is reasonably accurate considering it’s a proxy model meant to only approximate the real thing with different, yet related, data.
Getting acquainted with our “instance of interest”
The journalist reached out to you with a case in mind: the African American defendant who was falsely predicted to have a high risk of recidivism. This case is #5231 and is your main instance of interest. Since our focus is racial bias, we’d like to compare it with similar instances but of different races. To that end, we found case #10127 (Caucasian) and #2726 (Hispanic).
We can look at the data for all three. Since we will keep referring to these instances throughout this chapter, let’s first save the indexes of the African American (idx_aa), Hispanic (idx_h), and Caucasian (idx_c) cases. Then, we can subset the test dataset by these indexes. Since we have to make sure that our predictions match, we will concatenate this subsetted test dataset to the true labels (y_test) and the CatBoost predictions (y_test_cb_pred):
idx_aa = 5231idx_h = 2726idx_c = 10127eval_idxs = X_test.index.isin([idx_aa, idx_h, idx_c])X_test_evals = X_test[eval_idxs]eval_compare_df = pd.concat( [ pd.DataFrame( {'y':y_test[eval_idxs]}, index=[idx_c, idx_h, idx_aa] ), pd.DataFrame( {'y_pred':y_test_cb_pred[eval_idxs]}, index=[idx_c, idx_h, idx_aa] ), X_test_evals ], axis=1).transpose()eval_compare_dfThe preceding code produces the DataFrame in Figure 6.4. You can tell that the predictions match the true labels, and our main instance of interest was the only one predicted as a medium or high risk of recidivism. Besides race, the only other differences are with c_charge_degree and one minor age difference:

Figure 6.4: Observations #5231, #10127, and #2726 side by side with feature differences highlighted Throughout this chapter, we will pay close attention to these differences to see whether they played a large role in producing the prediction difference. All the methods we will cover will complete the picture of what can determine or change the proxy model’s decision, and, potentially, the COMPAS model by extension. Now that we have completed the setup, we will move forward with employing the interpretation methods.
Understanding anchor explanations
In Chapter 5, Local Model-Agnostic Interpretation Methods, we learned that LIME trains a local surrogate model (specifically a weighted sparse linear model) on a perturbed version of your dataset in the neighborhood of your instance of interest. The result is that you approximate a local decision boundary that can help you interpret the model’s prediction for it.
Like LIME, anchors are also derived from a model-agnostic perturbation-based strategy. However, they are not about the decision boundary but the decision region. Anchors are also known as scoped rules because they list some decision rules that apply to your instance and its perturbed neighborhood. This neighborhood is also known as the perturbation space. An important detail is to what extent the rules apply to it, known as precision.
Imagine the neighborhood around your instance. You would expect the points to have more similar predictions the closer you got to your instance, right? So, if you had decision rules that defined these predictions, the smaller the area surrounding your instance, the more precise your rules. This concept is called coverage, which is the percentage of your perturbation space that yields a specific precision.
Unlike LIME, anchors don’t fit a local surrogate model to explain your chosen instance’s prediction. Instead, they explore possible candidate decision rules using an algorithm called Kullback-Leibler divergence Lower and Upper Confidence Bounds (KL-LUCB), which is derived from a Multi-Armed Bandit (MAB) algorithm.
MABs are a family of reinforcement learning algorithms about maximizing the payoff when you have limited resources to explore all unknown possibilities. The algorithm originated from understanding how casino slot machine players could maximize their payoff by playing multiple machines. It’s called multi-armed bandit because slot machine players are known as one-armed bandits. Yet players don’t know which machine will yield the highest payoff, can’t try all of them at once, and have finite funds. The trick is to learn how to balance exploration (trying unknown slot machines) with exploitation (using those you already have reasons to prefer).
In the anchors’ case, each slot machine is a potential decision rule, and the payoff is how much precision it yields. The KL-LUCB algorithm uses confidence regions based on the Kullback-Leibler divergence between the distributions to find the decision rule with the highest precision sequentially, yet efficiently.
Preparations for anchor and counterfactual explanations with alibi
Several small steps need to be performed to help the alibi library produce human-friendly explanations. The first one pertains to the prediction since the model may output a 1 or 0, but it’s easier to understand a prediction by its name. To help us with this, we need a list with the class names where the 0 position matches our negative class name and 1 matches the positive one:
class_names = ['Low Risk', 'Medium/High Risk']Next, let’s create a numpy array with our main instance of interest and print it out. Please note that the single-dimension array needs to be expanded (np.expand_dims) so that it’s understood by alibi:
X_test_eval = np.expand_dims( X_test.values[ X_test.index.get_loc(idx_aa) ], axis=0)print(X_test_eval)The preceding code outputs an array with the 21 features, of which 12 were the result of One-Hot Encoding (OHE):
[[23 0 0 0 2 0 1 1 0 ... 0 1 0 0 0 0]]A problem with making human-friendly explanations arises when you have OHE categories. To both the machine learning model and the explainer, each OHE feature is separate from the others. Still, to the human interpreting the outcomes, they cluster together as categories of their original features.
The alibi library has several utility functions to deal with this problem, such as ohe_to_ord, which takes a one-hot-encoded instance and puts it in an ordinal format. To use this function, we first define a dictionary (cat_vars_ohe) that tells alibi where the categorical variables are in our features and how many categories each one has. For instance, in our data, gender starts at the 5th index and has two categories, which is why our cat_vars_ohe dictionary begins with 5: 2. Once you have this dictionary, ohe_to_ord can take your instance (X_test_eval) and output it in ordinal format, where each categorical variable takes up a single feature. This utility function will prove useful for Alibi’s counterfactual explanations, where the explainer will need this dictionary to map categorical features together:
cat_vars_ohe = {5: 2, 7: 6, 13: 8}print(ohe_to_ord(X_test_eval, cat_vars_ohe)[0])The preceding code outputs the following array:
[[23 0 0 0 2 1 0 3]]For when it’s in ordinal format, Alibi will need a dictionary that provides names for each category and a list of feature names:
category_map = { 5: ['Female', 'Male'], 6: [ 'African-American', 'Asian', 'Caucasian', 'Hispanic', 'Native American', 'Other' ], 7: [ 'Felony 1st Degree', 'Felony 2nd Degree', 'Felony 3rd Degree', 'Felony 7th Degree', 'Misdemeanor 1st Degree', 'Misdemeanor 2nd Degree', 'Misdemeanor 3rd Degree', 'Other Charge Degree' ]}feature_names = [ 'age', 'juv_fel_count', 'juv_misd_count', 'juv_other_count', 'priors_count', 'sex', 'race', 'c_charge_degree']However, Alibi’s anchor explanations use the data as it is provided to our models. We are using OHE data, so we need a category map for that format. Of course, the OHE features are all binary, so they only have two “categories” each:
category_map_ohe = { 5: ['Not Female', 'Female'], 6: ['Not Male', 'Male'], 7:['Not African American', 'African American'], 8:['Not Asian', 'Asian'], 9:['Not Caucasian', 'Caucasian'], 10:['Not Hispanic', 'Hispanic'], 11:['Not Native American', 'Native American'], 12:['Not Other Race', 'Other Race'], 19:['Not Misdemeanor 3rd Deg', 'Misdemeanor 3rd Deg'], 20:['Not Other Charge Degree', 'Other Charge Degree']}Local interpretations for anchor explanations
All Alibi explainers require a predict function, so we create a lambda function called predict_cb_fn for our CatBoost model. Please note that we are using predict_proba for the classifier’s probabilities. Then, to initialize AnchorTabular, we also provide it with our features’ names as they are in our OHE dataset and the category map (category_map_ohe). Once it has initialized, we fit it with our training data:
predict_cb_fn = lambda x: fitted_cb_mdl.predict_proba(x)anchor_cb_explainer = AnchorTabular( predict_cb_fn, X_train.columns, categorical_names=category_map_ohe)anchor_cb_explainer.fit(X_train.values)Before we leverage the explainer, it’s good practice to check that the anchor “holds.” In other words, we should check that the MAB algorithm found decision rules that help explain the prediction. To verify this, you use the predictor function to check that the prediction is the same as the one you expect for this instance. Right now, we are using idx_aa, which is the case of the African American defendant:
print( 'Prediction: %s' % class_names[anchor_cb_explainer. predictor(X_test.loc[idx_aa].values)[0]])The preceding code outputs the following:Prediction: Medium/High RiskWe can proceed to use the explain function to generate an explanation for our instance. We can set our precision threshold to 0.85, which means we expect the predictions on anchored observations to be the same as our instance at least 85% of the time. Once we have an explanation, we can print the anchors as well as their precision and coverage:
anchor_cb_explanation = anchor_cb_explainer.explain( X_test.loc[idx_aa].values,threshold=0.85, seed=rand)print('Anchor: %s' % (' AND'.join(anchor_cb_explanation.anchor)))print('Precision: %.3f' % anchor_cb_explanation.precision)print('Coverage: %.3f' % anchor_cb_explanation.coverage)The following output was generated by the preceding code. You can tell that age, priors_count, and race_African-American are factors at 86% precision. Impressively, this rule applies to almost a third of all the perturbation space’s instances with a coverage of 0.29:
Anchor: age <= 25.00 AND priors_count > 0.00 AND race_African-American = African AmericanPrecision: 0.863Coverage: 0.290We can try the same code but with a 5% bump in the precision threshold set to 0.9. We observe the same three anchors that were generated from the previous example with three additional anchors:
Anchor: age <= 25.00 AND priors_count > 0.00 AND race_African-American = African American AND c_charge_degree_(M1) = Not Misdemeanor 1st Deg AND c_charge_degree_(F3) = Not Felony 3rd Level AND race_Caucasian = Not CaucasianPrecision: 0.903Coverage: 0.290Interestingly enough, although precision did increase by a few percentage points, coverage stayed the same. At this level of precision, we may confirm that race is a significant factor because being African American is an anchor, but so is not being Caucasian. Another factor was c_charge_degree. The explanation reveals that being accused of a first-degree misdemeanor or third-level felony would have been better. Understandably, a seventh-level felony is a more serious charge than these two.
Another way of understanding why a model made a specific prediction is by looking for a similar datapoint that had the opposite prediction and examining why the alternative decision was made. The decision boundary crosses between both points, so it’s helpful to contrast decision explanations from both sides of the boundary. This time, we will use idx_c, which is the case for the Caucasian defendant with a threshold of 85% and which outputs the anchors as follows:
Anchor: priors_count <= 2.00 AND race_African-American = Not African American AND c_charge_degree_(M1) = Misdemeanor 1st DegPrecision: 0.891Coverage: 0.578The first anchor is priors_count <= 2.00, but on the other side of the boundary, the first two anchors were age <= 25.00 and priors_count > 0.00. In other words, for an African American under or equal to the age of 25, any number of priors is enough to categorize them as having a medium/high risk of recidivism (86% of the time). On the other hand, a Caucasian person will be predicted as low risk if the priors don’t exceed two and they were not accused of a first-degree misdemeanor (89% of the time and with 58% coverage). These decision rules suggest a biased decision based on race with different standards applied to different racial groups. A double standard is when different rules are applied when, in principle, the situation is the same. In this case, the different rules for priors_count and the absence of age as a factor for Caucasians constitute double standards.We can now try a Hispanic defendant (idx_h) to observe whether double standards are also found in this instance. We just run the same code as before but replace idx_c with idx_h:
Anchor: priors_count <= 2.00 AND race_African-American = Not African American AND juv_fel_count <= 0.00 AND sex_Male = MalePrecision: 0.851Coverage: 0.578The explanations for the Hispanic defendant confirm the different standard with priors_count and that race continues to be a strong factor since there’s one anchor for not being African American and another one for being Hispanic.
For specific model decisions, anchor explanations answer the question why? However, by comparing similar instances that are only slightly different but have different predictions, we have explored the question what if? In the next section, we will expand on this question further.
Exploring counterfactual explanations
Counterfactuals are an integral part of human reasoning. How many of us have muttered the words “If I had done X instead, my outcome y would have been different”? There’s always one or two things that, if done differently, could lead to the outcomes we prefer!
In machine learning outcomes, you can leverage this way of reasoning to make for extremely human-friendly explanations where we can explain decisions in terms of what would need to change to get the opposite outcome (the counterfactual class). After all, we are often interested in knowing how to make a negative outcome better. For instance, how do you get your denied loan application approved or decrease your risk of cardiovascular disease from high to low? However, hopefully, answers to those questions aren’t a huge list of changes. You prefer the smallest number of changes required to change your outcome.
Regarding fairness, counterfactuals are an important interpretation method, in particular when there are elements involved that we can’t change or shouldn’t have to change. For instance, if you perform exactly the same job and have the same level of experience as your co-worker, you expect to have the same salary, right? If you and your spouse share the same assets and credit history but have different credit scores, you have to wonder why. Does it have to do with gender, race, age, or even political affiliations? Whether it’s a compensation, credit rating, or recidivism risk model, you’d hope that similar people were treated similarly.
Finding counterfactuals is not particularly hard. All we have to do is change our instance of interest slightly until it changes the outcome. And maybe there’s an instance already in the dataset just like that!
In fact, you could say that the three instances we examined with anchors in the previous section are close enough to be counterfactuals of each other, except for the Caucasian and Hispanic cases, which have the same outcome. But the Caucasian and Hispanic instances were “cherry-picked” by looking for datapoints with the same criminal history but different races to the instance of interest. Perhaps by comparing similar points, mostly except for race, we limited the scope in such a way that we confirmed what we hoped to confirm, which is that race matters to the model’s decision-making.
This is an example of selection bias. After all, counterfactuals are inherently selective because they focus on a few feature changes. And even with a few features, there are so many possible permutations that change the outcome, which means that a single point could have hundreds of counterfactuals. And not all of these will tell a consistent story. This phenomenon is called the Rashomon effect. It is named after a famous Japanese movie about a murder mystery. And as we have come to expect from murder mysteries, witnesses have different recollections of what happened. But in the same way that it’s difficult to rely on a single witness, you cannot rely on a single counterfactual. Also, in the same way that great detectives are trained to look for clues everywhere in connection to the scene of a crime (even if it contradicts their instincts), counterfactuals shouldn’t be “cherry-picked” because they conveniently tell the story we want them to tell.
Fortunately, there are algorithmic ways of looking for counterfactual instances in an unbiased manner. Typically, these involve finding the closest points with different outcomes, but there are different ways of measuring the distance between points. For starters, there’s the L1 distance (also known as the Manhattan distance) and L2 distance (also known as the Euclidean distance), among many others. But there’s also the question of normalizing the distances because not all features have the same scale. Otherwise, they would be biased against features with smaller scales, such as one-hot-encoded features. There are many normalization schemes to choose from too. You could use standard deviation, min-max scaling, or even median absolute deviation [9].
In this section, we will explain and use one advanced counterfactual finding method. Then, we will explore Google’s What If Tool (WIT). It has a simple L1- and L2-based counterfactual finder, which is limited to the dataset but makes up for it with other useful interpretation features.
Counterfactual explanations guided by prototypes
The most sophisticated counterfactual finding algorithms do the following:
Loss: These leverage a loss function that helps us optimize finding the counterfactuals closest to our instance of interest.
Perturbation: These tend to operate with a perturbation space much like anchors do, changing as few features as possible. Please note that counterfactuals don’t have to be real points in your dataset. That would be far too limiting. Counterfactuals exist in the realm of the possible, not of the necessarily known.
Distribution: However, counterfactuals have to be realistic, and therefore, interpretable. For example, a loss function could help determine that age < 0 alone is enough to make any medium-/high-risk instance low-risk. This is why counterfactuals should lie close to the statistical distributions of your data, especially class-specific distributions. They also should not be biased against smaller-scale features, namely categorical variables.
Speed: These run fast enough to be useful in real-world scenarios.
Alibi’s Counterfactuals Guided by Prototypes (CounterFactualProto) has all these properties. It has a loss function that includes both L1 (Lasso) and L2 (Ridge) regularization as a linear combination, just like Naïve Elastic Net does

but with a weight (

) only on the L1 term. The clever part of this algorithm is that it can (optionally) use an autoencoder to understand the distributions. We will leverage one in Chapter 7, Visualizing Convolutional Neural Networks. However, what’s important to note here is that autoencoders, in general, are neural networks that learn a compressed representation of your training data. This method incorporates loss terms from the autoencoder, such as one for the nearest prototype. A prototype is the dimensionality-reduced representation of the counterfactual class.
If an autoencoder is not available, the algorithm uses a tree often used for multidimensional search (k-d trees) instead. With this tree, the algorithm can efficiently capture the class distributions and choose the nearest prototype. Once it has the prototype, the perturbations are guided by it. Incorporating a prototype loss term in the loss function ensures that the resulting perturbations will be close enough to the prototype that is in distribution for the counterfactual class. Many modeling classes and interpretation methods overlook the importance of treating continuous and categorical features differently.
CounterFactualProto can use two different distance metrics to compute the pairwise distances between categories of a categorical variable: Modified Value Difference Metric (MVDM) and Association-Based Distance Metric (ABDM) and can even combine both. Another way in which CounterFactualProto ensures meaningful counterfactuals is by limiting permutated features to predefined ranges. We can use the minimum and maximum values of features to generate a tuple of arrays (feature_range):
feature_range = ( X_train.values.min(axis=0).reshape(1,21).astype(np.float32),\ X_train.values.max(axis=0).reshape(1,21).astype(np.float32))print(feature_range)The preceding code outputs two arrays – the first one with the minimum and the second with the maximum of all features:
(array([[18., 0., ... , 0., 0., 0.]], dtype=float32), array([[96., 20., ... , 1., 1., 1.]], dtype=float32))We can now instantiate an explainer with CounterFactualProto. As arguments, it requires the model’s predict function (predict_cb_fn), the shape of the instance you want to explain (X_test_eval.shape), the maximum amount of optimization iterations to perform (max_iterations), and the feature range for perturbed instances (feature_range). Many hyperparameters can be chosen, including the

weight to apply to the L1 loss (beta) and the θ weight to apply to the prototype loss (theta). Also, you must specify whether to use the k-d tree or not (use_kdtree) when the autoencoder model isn’t provided. Once the explainer is instantiated, you fit it to the test dataset. We are specifying the distance metric for categorical features (d_type) as the combination of ABDM and MVDM:
cf_cb_explainer = CounterFactualProto( predict_cb_fn, c_init=1, X_test_eval.shape, max_iterations=500, feature_range=feature_range, beta=.01, theta=5, use_kdtree=True)cf_cb_explainer.fit(X_test.values, d_type='abdm-mvdm')Creating an explanation with an explainer is similar to how it was with anchors. Just pass the instance (X_test_eval) to the explain function. However, outputting the results is not as straightforward, mainly because of the features converting between one-hot-encoded and ordinal, and interactions among the features. The documentation for Alibi (https://docs.seldon.io/projects/alibi/) has a detailed example of how this is done.
We will instead use a utility function called describe_cf_instance that does this for us using the instance of interest (X_test_eval), explanation (cf_cb_explanation), class names (class_names), one-hot-encoded category locations (cat_vars_ohe), category map (category_map), and feature names (feature_names):
cf_cb_explanation = cf_cb_explainer.explain(X_test_eval)mldatasets.describe_cf_instance( X_test_eval, cf_cb_explanation, class_names, cat_vars_ohe, category_map, feature_names)The following output was produced by the preceding code:
Instance Outcomes and Probabilities
original: Medium/High Risk [0.46732193 0.53267807]counterfactual: Low Risk [0.50025815 0.49974185] Categorical Feature Counterfactual Perturbations
sex: Male --> Female race: African-American --> Asianc_charge_degree: Felony 7th Degree --> Felony 1st DegreeNumerical Feature Counterfactual Perturbations
priors_count: 2.00 --> 1.90You can appreciate from the output that the instance of interest (“original”) has a 53.26% probability of being Medium/High Risk, but the counterfactual is barely on the Low Risk side with 50.03%! A counterfactual that is slightly on the other side is what we would like to see because that likely means that it is as close as possible to our instance of interest. There are four feature differences between them, three of which are categorical (sex, race, and c_charge_degree). The fourth difference is the priors_count numerical feature, which is treated as continuous since the explainer doesn’t know it’s discrete. In any case, the relationship should be monotonic, meaning an increase in one variable is consistent with a decrease or increase in the other. In this case, fewer priors should always mean lower risk, which means we can interpret the 1.90 as a 1 because if 0.1 fewer priors helped reduce the risk, a whole prior should also do so.
A more powerful insight derived from CounterFactualProto’s output is that two demographic features were present in the closest counterfactual to this feature. One was found with a method that is designed to follow our classes’ statistical distributions and isn’t biased against or in favor of specific types of features. And even though it is surprising to see Asian females in our counterfactual because it doesn’t fit the narrative that Caucasian males are getting preferential treatment, it is concerning to realize that race appears in the counterfactual at all.
The Alibi library has several counterfactual finding methods, including one that leverages reinforcement learning. Alibi also uses k-d trees for its trust score, which I highly recommend as well! The trust score measures the agreement between any classifier and a modified nearest neighbors classifier. The reasoning behind this is that a model’s predictions should be consistent on a local level to be trustworthy. In other words, if you and your neighbor are almost the same in every way, why would you be treated differently?
Counterfactual instances and much more with WIT
Google’s WIT is a very versatile tool. It requires very little input or preparation and opens up in your Jupyter or Colab notebook as an interactive dashboard with three tabs:
Datapoint editor: To visualize your datapoints, edit them, and explain their predictions.
Performance: To see high-level model performance metrics (for all regression and classification models). For binary classification, this tab is called Performance and Fairness because, in addition to high-level metrics, predictive fairness can be compared between your dataset’s feature-based slices.
Features: To view general feature statistics.
Given that the Features tab doesn’t relate to model interpretations, we will explore only the first two in this section.
Configuring WIT
Optionally, we can enrich our interpretations in WIT by creating attributions, which are values that explain how much each feature contributes to each prediction. You could use any method to generate attributions, but we will use SHAP. We covered SHAP first in Chapter 4, Global Model-Agnostic Interpretation Methods. Since we will interpret our CatBoost model in the WIT dashboard, the SHAP explainer that is most suitable is TreeExplainer, but DeepExplainer would work for the neural network (and KernelExplainer for both). To initialize TreeExplainer, we need to pass the fitted model (fitted_cb_mdl):
shap_cb_explainer = shap.TreeExplainer(fitted_cb_mdl)WIT requires all the features in the dataset (including the labels). We will use the test dataset, so you could concatenate X_test and y_test, but even those two exclude the ground truth feature (is_recid). One way of getting all of them is to subset recidivism_df with the test dataset indexes (y_test.index). WIT also needs our data and columns in list format so we can save them as variables for later use (test_np and cols_l).
Lastly, for predictions and attributions, we will need to remove our ground truth (is_recid) and classification label (compas_score), so let’s save the index of these columns (delcol_idx):
test_df = recidivism_df.loc[y_test.index]test_np = test_df.valuescols_l = test_df.columnsdelcol_idx = [ cols_l.get_loc("is_recid"), cols_l.get_loc("compas_score")]WIT has several useful functions for customizing the dashboard, such as setting a custom distance metric (set_custom_distance_fn), displaying class names instead of numbers (set_label_vocab), setting a custom predict function (set_custom_predict_fn), and a second predict function to compare two models (compare_custom_predict_fn).
In addition to set_label_vocab, we are going to only use a custom predict function (custom_predict_with_shap). All it needs to function is to take an array with your examples_np dataset and produce some predictions (preds). However, we first must remove features that we want in the dashboard but weren’t used for the training (delcol_idx). This function’s output is a dictionary with the predictions stored in a predictions key. But we’d also like some attributions, which is why we need an attributions key in that dictionary. Therefore, we take our SHAP explainer and generate shap_values, which is a numpy array. However, attributions need to be a list of dictionaries to be understood by the WIT dashboard. To this end, we iterate shap_output and convert each observation’s SHAP values array into a dictionary (attrs) and then append this to a list (attributions):
def custom_predict_with_shap(examples_np): #For shap values, we only need the same features #that were used for training inputs_np = np.delete(np.array(examples_np),delcol_idx,axis=1) #Get the model's class predictions preds = predict_cb_fn(inputs_np) #With test data, generate SHAP values which converted #to a list of dictionaries format keepcols_l = [c for i, c in enumerate(cols_l)\ if i not in delcol_idx] shap_output = shap_cb_explainer.shap_values(inputs_np) attributions = [] for shap in shap_output: attrs = {} for i, col in enumerate(keepcols_l): attrs[col] = shap[i] attributions.append(attrs) #Prediction function must output predictions/attributions #in dictionary output = {'predictions': preds, 'attributions': attributions} return outputBefore we build the WIT dashboard, it’s important to note that to find our instance of interest in the dashboard, we need to know its position within the numpy array provided to WIT because these don’t have indexes as pandas DataFrames do. To find the position, all we need to do is provide the get_loc function with the index:
print(y_test.index.get_loc(5231))The preceding code outputs as 2910, so we can take note of this number. Building the WIT dashboard is fairly straightforward now. We first initialize a config (WitConfigBuilder) with our test dataset in numpy format (test_np) and our list of features (cols_l). Both are converted to lists with tolist(). Then, we set our custom predict function with set_custom_predict_fn and our target feature (is_recid) and provide our class names. We will use the ground truth this time to evaluate fairness from the perspective of what really happened. Once the config is initialized, the widget (WitWidget) builds the dashboard with it. You can optionally provide a height (the default is 1,000 pixels):
wit_config_builder = WitConfigBuilder( test_np.tolist(), feature_names=cols_l.tolist()).set_custom_predict_fn(custom_predict_with_shap).set_target_feature("is_recid").set_label_vocab(class_names)WitWidget(wit_config_builder, height=800)Datapoint editor
Section titled “Datapoint editor”In Figure 6.5, you can see the WIT dashboard with its three tabs. We will first explore the first tab (Datapoint editor). It has Visualize and Edit panes on the left, and on the right, it can show you either Datapoints or Partial dependence plots. When you have Datapoints selected, you can visualize the datapoints in many ways using the controls in the upper right (the highlighted area A). What we have done in Figure 6.5 is set the following:
- Binning | X-axis:
c_charge_degree_(F7) - Binning | Y-axis:
compas_score - Color By:
race_African-American
Everything else stays the same.
These settings resulted in all our datapoints being neatly organized into two rows and two columns and color-coded by African American or not. The right column is for those with a level 7 charge degree, and the upper row is for those with a Medium/High Risk COMPAS score. We can look for datapoint 2910 in this subgroup (B) by clicking on the top-rightmost item. It should appear in the Edit pane (C). Interestingly enough, the SHAP attributions for this datapoint are three times higher for age than they are for race_African-American. But still, race altogether is second to age in importance. Also, notice that in the Infer pane, you see the predicted probability for Medium/High Risk is approximately 83%:

Figure 6.5: WIT dashboard with our instance of interest
WIT can find the nearest counterfactual using L1 or L2 distances. And it can use either feature values or attributions to calculate the distances. As mentioned earlier, WIT can also include a custom distance-finding function if you add it to the configuration. For now, we will select L2 with the Feature value. In Figure 6.6, these options appear in the highlighted A area. Once you choose a distance metric and enable Nearest counterfactual, it appears side by side with our instance of interest (area B), and it compares their predictions as shown in Figure 6.6 (area C). You can sort the features by Absolute attribution for a clearer understanding of feature importance on a local level. The counterfactual is only 3 years older but has zero priors instead of two, yet that was enough to reduce the Medium/High Risk to nearly 5%:

Figure 6.6: How to find the nearest counterfactual in WIT
While both our instance of interest and counterfactual remain selected, we can visualize them along with all other points. By doing this, you take insights from local interpretations and can create enough context for global understandings. For instance, let’s change our visualization settings to the following:
- Binning | X-axis:
Inference label - Binning | Y-axis:
(none) - Scatter | X-axis:
age - Scatter | Y-axis:
priors_count
Everything else stays the same.
The result of this visualization is depicted in Figure 6.7. You can tell that the Low Risk bins’ points tend to hover in the lower end of priors_count. Both bins show that prior_count and age have a slight correlation, although this is substantially more pronounced in the Medium/High Risk bin. However, what is most interesting is the sheer density of African American datapoints deemed Medium/High Risk in age ranging 18–25 and with prior_count below three, compared to those in the Low Risk bin. It suggests that both lower age and higher priors_count increases risk more for African Americans than others:

Figure 6.7: Visualizing age versus priors_count in WIT
We can try creating our own counterfactuals by editing the datapoint. What happens when we reduce priors_count to one? The answer to this question is depicted in Figure 6.8. Once you make the change and click on the Predict button in the Infer pane, it adds an entry to the last prediction history in the Infer pane. You can tell in Run #2 that the risk reduces nearly to 33.5%, down nearly 50%!

Figure 6.8: Editing the datapoint to decrease priors_count in WIT
Now, what happens if age is only 2 years older but there are two priors? In Figure 6.9, Run #3 tells you that it barely made it inside the Low Risk score:

Figure 6.9: Editing the datapoint to increase the age in WIT
Another feature that the Datapoint editor tab has is Partial dependence plots, which we covered in Chapter 4, Global Model-Agnostic Interpretation Methods. If you click on this radio button, it will modify the right pane to look like Figure 6.10. By default, if a datapoint is selected, the PDPs are local, meaning they pertain to the chosen datapoint. But you can switch to global. In any case, it’s best to sort plots by variation as done in Figure 6.10, where age and priors_count have the highest variation. Interestingly, neither of them is monotonic, which doesn’t make sense. The model should learn that an increase in priors_count should consistently increase risk. It should be the same with a decrease in age. After all, academic research shows that crime tends to peak in the mid-20s and that higher priors increase the likelihood of recidivism. The relationship between these two variables is also well understood, so perhaps some data engineering and monotonic constraints could make sure a model was consistent with known phenomena rather than learning the inconsistencies in the data that lead to unfairness. We will cover this in Chapter 12, Monotonic Constraints and Model Tuning for Interpretability:

Figure 6.10: Local partial dependence plot for age and priors_count
Is there something that can be done to improve fairness in a model that has already been trained? Indeed, there is. The Performance & Fairness tab can help with that.
Performance & Fairness
Section titled “Performance & Fairness”When you click on the Performance & Fairness tab, you will see that it has Configure and Fairness panes on the left. And on the right, you can explore the overall performance of the model (see Figure 6.11). In the upper part of this pane, it has False Positives (%), False Negatives (%), Accuracy (%), and F1 fields. If you expand the pane, it shows the ROC curve, PR curve, confusion matrix, and mean attributions – the average Shapley values. We covered these terms in the previous chapters of this book either directly or indirectly, except for the PR curve. The Precision-Recall (PR) is very much like the ROC curve, except it plots precision against recall instead of TPR versus FPR. In this plot, precision is expected to decrease as recall decreases. Unlike ROC, it’s considered worse than a coin toss when the line is close to the x-axis, and it’s best suited to imbalanced classification problems:

Figure 6.11: Performance & Fairness tab initial view
A classification model will output probabilities that an observation belongs to a class label. We usually take every observation above or equal to 0.5 to belong to the positive class. Otherwise, we predict it to belong to the negative class. This threshold is called the classification threshold, and you don’t always have to use the standard 0.5.
There are many cases in which it is appropriate to perform threshold tuning. One of the most compelling reasons is imbalanced classification problems because often models optimize performance on accuracy alone but end up with bad recall or precision. Adjusting the threshold will improve the metric you care most about:

Figure 6.12: Slicing performance metrics by race_African-American
Another primary reason to adjust thresholds is for fairness. To this end, you need to examine the metric you most care about across different slices of your data. In our case, False Positives (%) is where we can appreciate unfairness the most. For instance, take a look at Figure 6.12. In the Configure pane, we can slice the data by race_African-American, and to the right of it, we can see what we observed at the beginning of this chapter, which is that FPs for African Americans are substantially higher than for other segments. One way to fix this is through an automatic optimization method such as Demographic parity or Equal opportunity. If you are to use one of these, it’s best to adjust Cost Ratio (FP/FN) to tell the optimizer that FPs are worth more than FNs:

Figure 6.13: Adjusting the classification threshold for the dataset sliced by race_African-American
We can also adjust thresholds manually using the default Custom thresholds setting (see Figure 6.13). For these slices, if we want approximate parity with our FPs, we should use 0.78 as our threshold for when race_African-American=1. The drawback is that FNs will increase for this group, not achieving parity on that end. A cost ratio would help determine whether 14.7% in FPs justifies 24.4% in FNs, but to do this, we would have to understand the average costs involved. We will examine odds calibration methods further in Chapter 11, Bias Mitigation and Causal Inference Methods.
Mission accomplished
Section titled “Mission accomplished”This chapter’s mission was to see whether there was unfair bias in predicting whether a particular defendant would recidivate. We demonstrated that the FPR for African American defendants is 1.87 times higher than for Caucasian defendants. This disparity was confirmed with WIT, indicating that the model in question is much more likely to misclassify the positive class based on race. However, this is a global interpretation method, so it doesn’t answer our question regarding a specific defendant. Incidentally, in Chapter 11, Bias Mitigation and Causal Inference Methods, we will cover other global interpretation methods for unfairness.
To ascertain whether the model was racially biased against the defendant in question, we leveraged anchor and counterfactual explanations – they both output race as a primary feature in their explanations. The anchor did it with relatively high precision and coverage, and Counterfactuals Guided by Prototypes found that the closest decision has a different race. That being said, in both cases, race wasn’t the only feature in the explanations. The features usually included any or all of the following: priors_count, age, charge_degree, and sex. The inconsistent rules involving the first three regarding race suggests double standards and the involvement of sex suggests intersectionality. Double standards are when rules are applied unfairly to different groups. Intersectionality is how overlapping identities create different systems of interconnected modes of discrimination. However, we know that females of all races are less likely to recidivate according to academic research. Still, we have to ask ourselves whether females have a structural advantage that makes them privileged in this context. A healthy dose of skepticism can help, since when it comes to bias, there’s usually a more elaborate dynamic going on than meets the eye. The bottom line is that despite all the other factors that interplay with race, and provided that there’s no relevant criminological information that we are missing, yes—there’s racial bias involved in this particular prediction.
Summary
Section titled “Summary”After reading this chapter, you should know how to leverage anchors, to understand the decision rules that impact a classification, and counterfactuals, to grasp what needs to change for the predicted class to change. You also learned how to assess fairness using confusion matrices and Google’s WIT. In the next chapter, we will study interpretation methods for Convolutional Neural Networks (CNNs).
Dataset sources
Section titled “Dataset sources”- ProPublica Data Store, 2019, COMPAS Recidivism Risk Score Data and Analysis. Originally retrieved from https://www.propublica.org/datastore/dataset/compas-recidivism-risk-score-data-and-analysis
Further reading
Section titled “Further reading”- Desmarais, S.L., Johnson, K.L., and Singh, J.P., 2016, Performance of recidivism risk assessment instruments in U.S. correctional settings. Psychol Serv;13(3):206-222: https://doi.org/10.1037/ser0000075
- Berk, R., Heidari, H., Jabbari, S., Kearns, M., and Roth, A., 2017, Fairness in Criminal Justice Risk Assessments: The State of the Art. Sociological Methods & Research.
- Angwin, J., Larson, J., Mattu, S., and Kirchner, L., 2016, Machine Bias. There’s software used across the county to predict future criminals: https://www.propublica.org/article/machine-bias-risk-assessments-in-criminal-sentencing
- Ribeiro, M.T., Singh, S., and Guestrin, C., 2018, Anchors: High-Precision Model-Agnostic Explanations. Proceedings of the AAAI/ACM Conference on AI, Ethics, and Society: https://doi.org/10.1609/aaai.v32i1.11491
- Rocque, M., Posick, C., & Hoyle, J., 2015, Age and Crime. The encyclopedia of crime and punishment, 1–8: https://doi.org/10.1002/9781118519639.wbecpx275
- Dhurandhar, A., Chen, P., Luss, R., Tu, C., Ting, P., Shanmugam, K., and Das, P., 2018, Explanations based on the Missing: Towards Contrastive Explanations with Pertinent Negatives. NeurIPS: https://arxiv.org/abs/1802.07623
- Jiang, H., Kim, B., and Gupta, M.R., 2018, To Trust Or Not To Trust A Classifier. NeurIPS: https://arxiv.org/pdf/1805.11783.pdf