Skip to content
ImagineWorld

Bias Mitigation and Causal Inference Methods

node_idnode-book_interpretable-machine-learning-with-python-second-edition_chapter-11-bias-mitigation-and-causal-inference-methods
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleBias Mitigation and Causal Inference Methods
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 11 — Bias Mitigation and Causal Inference Methods

Section titled “Chapter 11 — Bias Mitigation and Causal Inference Methods”

In Chapter 6, Anchors and Counterfactual Explanations, we examined fairness and its connection to decision-making but limited to post hoc model interpretation methods. In Chapter 10, Feature Selection and Engineering for Interpretability, we broached the topic of cost-sensitivity, which often relates to balance or fairness. In this chapter, we will engage with methods that will balance data and tune models for fairness.

With a credit card default dataset, we will learn how to leverage target visualizers such as class balance to detect undesired bias, then how to reduce it via preprocessing methods such as reweighting and disparate impact remover for in-processing and equalized odds for post-processing. Extending from the topics of Chapter 6, Anchors and Counterfactual Explanations, and Chapter 10, Feature Selection and Engineering for Interpretability, we will also study how policy decisions can have unexpected, counterintuitive, or detrimental effects. A decision, in the context of hypothesis testing, is called a treatment. For many decision-making scenarios, it is critical to estimate their effect and make sure this estimate is reliable.

Therefore, we will hypothesize treatments for reducing credit card default for the most vulnerable populations and leverage causal modeling to determine its Average Treatment Effects (ATE) and Conditional Average Treatment Effects (CATE). Finally, we will test causal assumptions and the robustness of estimates using a variety of methods.

These are the main topics we are going to cover:

  • Detecting bias
  • Mitigating bias
  • Creating a causal model
  • Understanding heterogeneous treatment effects
  • Testing estimate robustness

This chapter’s example uses the mldatasets, pandas, numpy, sklearn, lightgbm, xgboost, matplotlib, seaborn, xai, aif360, econml, and dowhy libraries. Instructions on how to install all these libraries are in the preface.

The code for this chapter is located here:

https://packt.link/xe6ie

Over 2.8 billion credit cards are circulating worldwide, and we collectively spend over 25trillion(US)onthemeveryyear([https://www.ft.com/content/ad826e32−2ee8−11e9−ba00−0251022932c8](https://www.ft.com/content/ad826e32−2ee8−11e9−ba00−0251022932c8)).Thisisanastronomicalamount,nodoubt,butthecreditcardindustry’ssizeisbestmeasurednotbywhatisspent,butbywhatisowed.Cardissuerssuchasbanksmakethebulkoftheirmoneyfrominterest.So,theover25 trillion (US) on them every year ([https://www.ft.com/content/ad826e32-2ee8-11e9-ba00-0251022932c8](https://www.ft.com/content/ad826e32-2ee8-11e9-ba00-0251022932c8)). This is an astronomical amount, no doubt, but the credit card industry’s size is best measured not by what is spent, but by what is owed. Card issuers such as banks make the bulk of their money from interest. So, the over 60 trillion owed by consumers (2022), of which credit card debt is a sizable portion, provides a steady income to lenders in the form of interest. It could be argued this is good for business, but it also poses ample risk because if a borrower defaults before the principal plus operation costs have been repaid, the lender could lose money, especially once they’ve exhausted legal avenues to collect the debt.

When there’s a credit bubble, this problem is compounded because an unhealthy level of debt can compromise lenders’ finances and take their stakeholders down with them when the bubble bursts. Such was the case with the 2008 housing bubble, also known as the subprime mortgage crisis. These bubbles often begin with speculation on growth and seeking unqualified demand to fuel that growth. In the case of the mortgage crisis, the banks offered mortgages to people with no proven capacity to repay. They also, sadly, targeted minorities who had their entire net worth wiped out once the bubble burst. Financial crises and depressions, and every calamity in between, tend to affect those that are most vulnerable at much higher rates.

Credit cards have also been involved in catastrophic bubbles, notably in South Korea in 2003 (https://www.bis.org/repofficepubl/arpresearch_fs_200806.10.pdf) and Taiwan in 2006. This chapter will examine data from 2005, leading to the Taiwanese credit card crisis. By 2006, delinquent credit card debt reached $268 billion owed by over 700,000 people. Just over 3% of the Taiwanese population could not pay even the credit card’s minimum balance and colloquially were known as credit card slaves. Significant societal ramifications ensued, such as a sharp increase in homelessness, drug trafficking/abuse, and even suicide. In the aftermath of the 1997 Asian financial crisis, suicide steadily increased around the region. A 23% jump between 2005 and 2006 pushed Taiwan’s suicide rate to the world’s second highest.

If we trace back the crisis to its root causes, it was about new card-issuing banks having exhausted a saturated real-estate market, slashing requirements to obtain credit cards, which at the time were poorly regulated by authorities.

It hit younger people the most because they typically have less income and experience in managing money. In 2005, the Taiwanese Financial Supervisory Commission issued new regulations to raise credit card applicants’ requirements, preventing new credit card slaves. However, more policies would be needed to attend to the debt and the debtors already in the system.

Authorities started discussing the creation of asset management corporations (AMCs) to take bad debts from the balance sheet of banks. They also wanted to pass a debtors’ repayment regulation that would provide a framework to negotiate a reasonable repayment plan. Neither of these policies were codified into law untill 2006.

Hypothetically, let’s say it’s August 2005, and you have come from the future armed with novel machine learning and causal inference methods! A Taiwanese bank wants to create a classification model to predict customers that will default on their loans. They have provided you with a dataset of 30,000 of their credit card customers. Regulators are still drafting the laws, so there’s an opportunity to propose policies that benefit both the bank and the debtors. When the laws have passed, using the classification model, they can then anticipate which debts they should sell to the AMCs and, with the causal model, estimate which policies would benefit other customers and the bank, but they want to do this fairly and robustly—this is your mission!

The bank has stressed to you how important it is that there’s fairness embedded in your methods because the regulators and the public at large want assurance that banks will not cause any more harm. Their reputation depends on it too, because in recent months, the media has been relentless in blaming them for dishonest and predatory lending practices, causing distrust in consumers. For this reason, they want to use state-of-the-art robustness testing to demonstrate that the prescribed policies will alleviate the problem. Your proposed approach includes the following points:

  • Younger lenders have been reported to be more prone to defaulting on repayment, so you expect to find age bias, but you will also look for bias with other protected groups such as gender.
  • Once you have detected bias, you can mitigate bias with preprocessing, in-processing, and post-processing algorithms using the AI Fairness 360 (AIF360) library. In this process, you will train different models with each algorithm, assess their fairness, and choose the fairest model.
  • To be able to understand the impact of policies, the bank has conducted an experiment on a small portion of customers. With the experimental results, you can fit a causal model through the dowhy library, which will identify the causal effect. These effects are broken down further by the causal model to reveal the heterogeneous treatment effects.
  • Then, you can assess the heterogeneous treatment effects to understand them and decide which treatment is the most effective.
  • Lastly, to ensure that your conclusions are robust, you will refute the results with several methods to see if the effects hold.

Let’s dig in!

You will find the code for this example here: https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python/blob/master/Chapter11/CreditCardDefaults.ipynb.

To run this example, you need to install the following libraries:

  • mldatasets to load the dataset
  • pandas and numpy to manipulate it
  • sklearn (scikit-learn), xgboost, aif360, and lightgbm to split the data and fit the models
  • matplotlib, seaborn, and xai to visualize the interpretations
  • econml and dowhy for causal inference

You should load all of them first, as follows:

import math
import os
import mldatasets
import pandas as pd
import numpy as np
from tqdm.notebook import tqdm
from sklearn import model_selection, tree
import lightgbm as lgb
import xgboost as xgb
from aif360.datasets import BinaryLabelDataset
from aif360.metrics import BinaryLabelDatasetMetric,\
ClassificationMetric
from aif360.algorithms.preprocessing import Reweighing,\
DisparateImpactRemover
from aif360.algorithms.inprocessing import ExponentiatedGradientReduction, GerryFairClassifier
from aif360.algorithms.postprocessing.\
calibrated_eq_odds_postprocessing \
import CalibratedEqOddsPostprocessing
from aif360.algorithms.postprocessing.eq_odds_postprocessing\
import EqOddsPostprocessing
from econml.dr import LinearDRLearner
import dowhy
from dowhy import CausalModel
import xai
from networkx.drawing.nx_pydot import to_pydot
from IPython.display import Image, display
import matplotlib.pyplot as plt
import seaborn as sns

We load the data like this into a DataFrame called ccdefault_all_df:

ccdefault_all_df = mldatasets.load("cc-default", prepare=True)

There should be 30,000 records and 31 columns. We can verify this is the case with info(), like this:

ccdefault_all_df.info()

The preceding code outputs the following:

Int64Index: 30000 entries, 1 to 30000 Data columns (total 31 columns):


0 CC_LIMIT_CAT 30000 non-null int8 1 EDUCATION 30000 non-null int8 2 MARITAL_STATUS 30000 non-null int8 3 GENDER 30000 non-null int8 4 AGE_GROUP 30000 non-null int8 5 pay_status_1 30000 non-null int8 6 pay_status_2 30000 non-null int8 7 pay_status_3 30000 non-null int8 8 pay_status_4 30000 non-null int8 9 pay_status_5 30000 non-null int8 10 pay_status_6 30000 non-null int8 11 paid_pct_1 30000 non-null float64 12 paid_pct_2 30000 non-null float64 13 paid_pct_3 30000 non-null float64 14 paid_pct_4 30000 non-null float64 15 paid_pct_5 30000 non-null float64 16 paid_pct_6 30000 non-null float64 17 bill1_over_limit 30000 non-null float64 18 IS_DEFAULT 30000 non-null int8 19 _AGE 30000 non-null int16 20 _spend 30000 non-null int32 21 _tpm 30000 non-null int16 22 _ppm 30000 non-null int16 23 _RETAIL 30000 non-null int8 24 _URBAN 30000 non-null int8 25 _RURAL 30000 non-null int8 26 _PREMIUM 30000 non-null int8 27 _TREATMENT 30000 non-null int8 28 _LTV 30000 non-null float64 29 _CC_LIMIT 30000 non-null int32 30 _risk_score 30000 non-null float64

The output checks out. All features are numerical, with no missing values because we used prepare=True, which ensures that all null values are imputed. Categorical features are all int8 because they have already been encoded.

There are 30 features, but we won’t use them together because 18 of them are for the bias mitigation exercise, and the remaining 12 that start with an underscore (_) are for the causal inference exercise. Soon, we will split the data into the corresponding datasets for each exercise. It’s important to note that lowercase features have to do with each client’s transactional history, whereas client account or target features are uppercase.

We will use the following features in the bias mitigation exercise:

  • CC_LIMIT_CAT: ordinal; the credit card limit (_CC_LIMIT) separated into eight approximately equally distributed quartiles
  • EDUCATION: ordinal; the customer’s educational attainment level (0: Other, 1: High School, 2: Undergraduate, 3: Graduate)
  • MARITAL_STATUS: nominal; the customer’s marital status (0: Other, 1: Single, 2: Married)
  • GENDER: nominal; the gender of the customer (1: Male, 2: Female)
  • AGE GROUP: binary; denoting if the customer belongs to a privileged age group (1: privileged (26-47 years old), 0: underprivileged (every other age))
  • pay_status_1 pay_status_6: ordinal; the repayment status for the previous six periods from April, pay_status_6, to August 2005, pay_status_1 (-1: payment on time, 1: payment is 1 month delayed, 2: payment is 2 months delayed 8: 8 months delayed, 9: 9 months and above)
  • paid_pct_1 paid_pct_6: continuous; the percentage of the bill due each month from April, paid_pct_6, to August 2005, paid_pct_1, that was paid
  • bill1_over_limit: continuous; the last bill’s ratio in August 2005 over the corresponding credit limit
  • IS_DEFAULT: binary; target variable; whether the customer defaulted

These are the features we will use only in the causal inference exercise:

  • _AGE: continuous; the age in years of the customer.
  • _spend: continuous; how much was spent by each customer in New Taiwan Dollar (NT$).
  • _tpm: continuous; median transactions per month made by the customer with the credit card over the previous 6 months.
  • _ppm: continuous; median purchases per month made by the customer with the credit card over the previous 6 months.
  • _RETAIL: binary; if the customer is a retail customer, instead of a customer obtained through their employer.
  • _URBAN: binary; if the customer is an urban customer.
  • _RURAL: binary; if the customer is a rural customer.
  • _PREMIUM: binary; if the customer is “premium.” Premium customers get cashback offers and other spending incentives.
  • _TREATMENT: nominal; the intervention or policy prescribed to each customer (-1: Not part of the experiment, 0: Control group, 1: Lower Credit Limit, 2: Payment Plan, 3: Payment Plan and Credit Limit).
  • _LTV: continuous; the outcome of the intervention, which is the lifetime value estimated in NT$ given the credit payment behavior over the previous 6 months.
  • _CC_LIMIT: continuous; the original credit card limit in NT$ that the customer had before the treatment. Bankers expect the outcome of the treatment to be greatly impacted by this feature.
  • _risk_score: continuous; the risk score that the bank computed 6 months prior for each customer based on credit card bills’ ratio over their credit card limit. It’s like bill1_over_limit except it’s a weighted average of 6 months of payment history, and it was produced 5 months before choosing the treatment.

We will explain the causal inference features a bit more and their purpose in the following sections. Meanwhile, let’s break down the _TREATMENT feature by its values with value_counts() to understand how we will split this dataset, as follows:

ccdefault_all_df._TREATMENT.value_counts()

The preceding code outputs the following:

-1 28904 3 274 2 274 1 274 0 274

Most of the observations are treatment -1, so they are not part of the causal inference. The remainder was split evenly between the three treatments (1-3) and the control group (0). Naturally, we will use these four groups for the causal inference exercise. However, since the control group wasn’t prescribed treatment, we can use it in our bias mitigation exercise along with the -1 treatments. We have to be careful to exclude customers whose behaviors were manipulated in the bias mitigation exercise. The whole point is to predict which customers are most likely to default under “business as usual” circumstances while attempting to reduce bias.

Our single data preparation step, for now, is to split the datasets, which can be easily done by subsetting the pandas DataFrames using the _TREATMENT column. We will create one DataFrame for each exercise with this subsetting: bias mitigation (ccdefault_bias_df) and causal inference (ccdefault_causal_df). These can be seen in the following code snippet:

ccdefault_bias_df = ccdefault_all_df[
ccdefault_all_df._TREATMENT < 1
]
ccdefault_causal_df =ccdefault_all_df[
ccdefault_all_df._TREATMENT >= 0
]

We will do a few other data preparation steps in the in-depth sections but, for now, we are good to go to get started!

There are many sources of bias in machine learning. As outlined in Chapter 1, Interpretation, Interpretability, and Explainability; and Why Does It All Matter?, there are ample sources of bias. Those rooted in the truths that the data represents, such as systemic and structural ones, lead to prejudice bias in the data. There are also biases rooted in the data, such as sample, exclusion, association, and measurement biases. Lastly, there are biases in the insights we derive from data or models we have to be careful with, such as conservatism bias, salience bias, and fundamental attribution error.

For this example, to properly disentangle so many bias levels, we ought to connect our data to census data for Taiwan in 2005 and historical lending data split by demographics. Then, using these external datasets, control for credit card contract conditions, as well as gender, income, and other demographic data to ascertain if young people, in particular, were targeted for high-interest credit cards they shouldn’t have qualified for. We would also need to trace the dataset to the authors and consult with them and the domain experts to examine the dataset for bias-related data quality issues. Ideally, these steps would be necessary to validate the hypothesis, but that would be a monumental task requiring several chapters’ worth of explanation.

Therefore, in the spirit of expediency, we take the premise of this chapter at face value. That is, due to predatory lending practices, certain age groups are more vulnerable to credit card default, not through any fault of their own. We will also take at face value the quality of the dataset. With these caveats in place, it means that if we find disparities between age groups in the data or any model derived from this data, it can be attributed solely to predatory lending practices.

There are also two types of fairness, outlined here:

  • Procedural fairness: This is about fair or equal treatment. It’s hard to define this term legally because it depends so much on the context.
  • Outcome fairness: This is solely about measuring fair outcomes.

These two concepts aren’t mutually exclusive since the procedure may be fair but the outcome unfair, or vice versa. In this example, the unfair procedure was the offering of high-interest credit cards to unqualified customers. Nevertheless, we are going to focus on outcome fairness in this chapter.

When we discuss bias in machine learning, it will impact protected groups, and within these groups, there will be privileged and underprivileged groups. The latter is a group that is adversely impacted by bias. There are also many ways in which bias is manifested, and thus addressed, as follows:

  • Representation: There can be a lack of representation or an overrepresentation of the underprivileged group. The model will learn either too little or too much about this group, compared to others.
  • Distribution: Differences in the distribution of features between groups can lead the model to make biased associations that can impact model outcomes either directly or indirectly.
  • Probability: For classification problems, class balance discrepancies between groups such as those discussed in Chapter 6, Anchors and Counterfactual Explanations, can lead to the model learning that one group has a higher probability of being part of one class or another. These can be easily observed through confusion matrices or by comparing their classification metrics, such as false positive or false negative rates.
  • Hybrid: A combination of any of the preceding manifestations.

Strategies for any bias manifestation are discussed in the Mitigating bias section, but the kind we address in the chapter pertains to disparities with probability for our main protected attribute (_AGE). We will observe this through these means:

  • Visualizing dataset bias: Observing disparities in the data for the protected feature through visualizations.
  • Quantifying dataset bias: Measuring bias using fairness metrics.
  • Quantifying model bias: We will train a classification model and use other fairness metrics designed for models.

Model bias can be visualized, as we have done already in Chapter 6, Anchors and Counterfactual Explanations, or as we will do in Chapter 12, Monotonic Constraints and Model Tuning for Interpretability. We will quickly explore some other visualizations later in this chapter, in a subsection called Tying it all together! Without further ado, let’s move on to the practical portion of this section.

The data itself tells the story of how probable it is that one group belongs to a positive class versus another. If it’s a categorical feature, these probabilities can be obtained by dividing the value_counts() function for the positive class over all classes. For instance, for gender, we could do this:

ccdefault_bias_df[ ccdefault_bias_df.IS_DEFAULT==1 ].GENDER.value_counts()/ccdefault_bias_df.GENDER.value_counts()

The preceding snippet produces the following output, which shows that males have, on average, a higher probability of defaulting on their credit card:

2 0.206529 1 0.241633

The code for doing this for a continuous feature is a bit more complicated. It is recommended that you use pandas’ qcut to divide the feature into quartiles first and then use the same approach used for categorical features. Fortunately, the plot_prob_progression function does this for you and plots the progression of probabilities for each quartile. The first attribute is a pandas series, an array or list with the protected feature (_AGE), and the second is the same but for the target feature (IS_DEFAULT). We then choose the number of intervals (x_intervals) that we are setting as quartiles (use_quantiles=True).

The rest of the attributes are aesthetic, such as the label, title, and adding a mean_line. The code can be seen in the following snippet:

mldatasets.plot_prob_progression(
ccdefault_bias_df._AGE,
ccdefault_bias_df.IS_DEFAULT,
x_intervals=8,
use_quantiles=True,
xlabel='Age',
mean_line=True,
title='Probability of Default by Age'
)

The preceding code produced the following output, which depicts how the youngest (21-25) and oldest (47-79) are most likely to default. All other groups represent just over one standard deviation from the mean:

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_01.png)

Figure 11.1: Probability of CC default by _AGE

We can call the youngest and oldest quartiles the underprivileged group and all others the privileged group. In order to detect and mitigate unfairness, it is best to code them as a binary feature—and we have done just that with AGE_GROUP. We can leverage plot_prob_progression again, but this time with AGE_GROUP instead of AGE, and we will replace the numbers with labels we can interpret more easily. The code can be seen in the following snippet:

mldatasets.plot_prob_progression(
ccdefault_bias_df.AGE_GROUP.replace({0:'21-25,48+',1:'26-47'}),
ccdefault_bias_df.IS_DEFAULT,
xlabel='Age Group',
title='Probability of Default by Age Group',
mean_line=True
)

The preceding snippet produced the following output, in which the disparities between both groups are pretty evident:

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_02.png)

Figure 11.2: Probability of CC default by AGE_GROUP

Next, let’s bring GENDER back into the picture. We can employ plot_prob_contour_map, which is like plot_prob_progression but in two dimensions, color-coding the probabilities instead of drawing a line. So, the first two attributes are the features we want on the x-axis (GENDER) and y-axis (AGE_GROUP), and the third is the target (IS_DEFAULT). Since both our features are binary, it is best to use plot_type='grid' as opposed to contour. The code can be seen in the following snippet:

mldatasets.plot_prob_contour_map(
ccdefault_bias_df.GENDER.replace({1:'Male',2:'Female'}),
ccdefault_bias_df.AGE_GROUP.replace({0:'21-25,48+',1:'26-47'}),
ccdefault_bias_df.IS_DEFAULT,
xlabel='Gender',
ylabel='Age Group',
annotate=True,
plot_type='grid',
title='Probability of Default by Gender/Age Group'
)

The preceding snippet generates the following output. It is immediately evident how the most privileged group is 26- 47-year-old females, followed by their male counterparts at about 3-4% apart. The same happens with the underprivileged age group:

![Chart, treemap chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_03.png)

Figure 11.3: Probability grid of CC default by GENDER and AGE_GROUP

The gender difference is an interesting observation, and we could present a number of hypotheses as to why females default less. Are they just simply better at managing debt? Does it have to do with their marital status or education? We won’t dig deeper into these questions. Given that we only know of age-based discrimination, we will only use AGE_GROUP in privilege groups but keep GENDER a protected attribute, which will be factored in some fairness metrics we will monitor. Speaking of metrics, we will quantify dataset bias next.

There are three categories of fairness metrics, outlined here:

  • Individual fairness: How close individual observations are to their peers in the data. Distance metrics such as Euclidean and Manhattan distance can serve this purpose.
  • Group fairness: How labels or outcomes between groups are, on average, distant from each other. This can be measured either in the data or for a model.
  • Both: A few metrics measure entropy or variance by factoring inequality both in-group and between groups, such as the Theil index and the coefficient of variation.

We will focus exclusively on group fairness metrics in this chapter.

Before we compute fairness metrics, there are a few pending data preparation steps. Let’s make sure the dataset we will use for the bias mitigation exercise (ccdefault_bias_df) only has the pertinent columns, which are those that don’t begin with an underscore ("_"). On the other hand, the causal inference exercise will include only the underscored columns plus AGE_GROUP and IS_DEFAULT. The code can be seen in the following snippet:

cols_bias_l = ccdefault_all_df.columns[
~ccdefault_all_df.columns.str.startswith('_')
].tolist()
cols_causal_l = ['AGE_GROUP','IS_DEFAULT'] +\
ccdefault_all_df.columns[
ccdefault_all_df.columns.str.startswith('_')
].tolist()
ccdefault_bias_df = ccdefault_bias_df[cols_bias_l]
ccdefault_causal_df = ccdefault_causal_df[cols_causal_l]

Also, it’s more important to quantify dataset bias on the training data because that is the data the model will learn from, so let’s go ahead and split the data into train and test X and y pairs. We do this after we have, of course, initialized the random seed to aim for some reproducibility. The code can be seen in the following snippet:

rand = 9
os.environ['PYTHONHASHSEED']=str(rand)
np.random.seed(rand)
y = ccdefault_bias_df['IS_DEFAULT']
X = ccdefault_bias_df.drop(['IS_DEFAULT'], axis=1).copy()
X_train, X_test, y_train, y_test = model_selection.train_test_split(
X, y, test_size=0.25, random_state=rand
)

Even though we will use the pandas data we just split for training and performance evaluation, the library we will use for this exercise, called AIF360, abstracts datasets into base classes. These classes include the data converted to a numpy array and store attributes related to fairness.

For regression, AIF360 has RegressionDataset, but for this binary classification example, we will use BinaryLabelDataset. You can initialize it with the pandas DataFrame with both features and labels (X_train.join(y_train)). Then, you specify the name of the label (label_names) and protected attributes (protected_attribute_names), and it is recommended that you enter a value for favorable_label and unfavorable_label, which tells AIF360 which label values are preferred so that it factors them into how it assesses fairness. As confusing as it may seem, positive and, in contrast, negative in binary classification only pertain to what we are trying to predict—the positive class—and not whether it is a favorable outcome. The code can be seen in the following snippet:

train_ds = BinaryLabelDataset(
df=X_train.join(y_train),
label_names=['IS_DEFAULT'],
protected_attribute_names=['AGE_GROUP', 'GENDER'],
favorable_label=0,
unfavorable_label=1
)
test_ds = BinaryLabelDataset(
df=X_test.join(y_test),
label_names=['IS_DEFAULT'],
protected_attribute_names=['AGE_GROUP', 'GENDER'],
favorable_label=0, unfavorable_label=1
)

Next, we create arrays for underprivileged groups and privileged_groups. Those in AGE_GROUP=1 have a lower probability of default, so they are privileged, and vice versa. Then, with these and the abstracted dataset for training (train_ds), we can initialize a metrics class via BinaryLabelDatasetMetric. This class has functions for computing several group fairness metrics, judging the data alone. We will output three of them and then explain what they mean. The code can be seen in the following snippet:

underprivileged_groups=[{'AGE_GROUP': 0}]
privileged_groups=[{'AGE_GROUP': 1}]
metrics_train_ds = BinaryLabelDatasetMetric(
train_ds,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)
print('Statistical Parity Difference (SPD): %.4f' %
metrics_train_ds.statistical_parity_difference())
print('Disparate Impact (DI): %.4f' %
metrics_train_ds.disparate_impact())
print('Smoothed Empirical Differential Fairness (SEDF): %.4f' %\
metrics_train_ds.smoothed_empirical_differential_fairness())

The preceding snippet generates the following output:

Statistical Parity Difference (SPD): -0.0437 Disparate Impact (DI): 0.9447 Smoothed Empirical Differential Fairness (SEDF): 0.3514

Now, let’s explain what each metric means, as follows:

  • Statistical Parity Difference (SPD): Also known as the mean difference, this is the difference between the mean probability of favorable outcomes between underprivileged and privileged groups. A negative number represents unfairness to the underprivileged group and a positive number is better, yet a number closer to zero represents a fair outcome with no significant difference between the privileged and underprivileged groups. It’s computed with the following formula, where f is the value for the favorable class, D is the group of the customer, and Y is whether the customer will default or not:

  • Disparate Impact (DI): DI is exactly like SPD except it’s the ratio, not the difference. And, as ratios go, the closer to one the better for the underprivileged group. In other words, one represents a fair outcome between groups with no difference, below one means unfavorable outcomes to the underprivileged group compared to the privileged group, and over one means favorable outcomes to the underprivileged group compared to the privileged group. The formula is shown here:

  • Smoothed Empirical Differential Fairness (SEDF): This fairness metric is one of the many newer ones from a paper called “An Intersectional Definition of Fairness.” Unlike the previous two metrics, it’s not restricted to the predetermined privileged and underprivileged groups, but it’s extended to include all the categories in the protected attributes—in this case, the four in Figure 11.3. The authors of the paper argue that fairness is particularly tricky when you have a crosstab of protected attributes. This occurs because of Simpson’s paradox, which is that one group can be advantaged or disadvantaged in aggregate but not when subdivided into crosstabs. We won’t get into the math, but their method accounts for this possibility while measuring a sensible level of fairness in intersectional scenarios. To interpret it, zero represents absolute fairness, and the farther from zero it is, the less fair it is.

Next, we will quantify group fairness metrics for a model.

Before we compute metrics, we will need to train a model. To that end, we will initialize a LightGBM classifier (LGBMClassifier) with optimal hyperparameters (lgb_params). These have already been hyperparameter-tuned for us (more details on how to do this in Chapter 12, Monotonic Constraints and Model Tuning for Interpretability).

Please note that these parameters include scale_pos_weight, which is for class weighting. Since this is an unbalanced classification task, this is an essential parameter to leverage so that the classifier is cost-sensitive-trained, penalizing one form of misclassification over another. Once the classifier is initialized, it is fit and evaluated with evaluate_class_mdl, which returns a dictionary with predictive performance metrics that we can store in a model dictionary (cls_mdls). The code can be seen in the following snippet:

cls_mdls = {}
lgb_params = {
'learning_rate': 0.4,
'reg_alpha': 21,
'reg_lambda': 1,
'scale_pos_weight': 1.8
}
lgb_base_mdl = lgb.LGBMClassifier(
random_seed=rand,
max_depth=6,
num_leaves=33,
**lgb_params
)
lgb_base_mdl.fit(X_train, y_train)
cls_mdls['lgb_0_base'] = mldatasets.evaluate_class_mdl(
lgb_base_mdl,
X_train,
X_test,
y_train,
y_test,
plot_roc=False,
plot_conf_matrix=True,
show_summary=True,
ret_eval_dict=True
)

The preceding snippet of code outputs Figure 11.4. The scale_pos_weight parameter ensures a healthier balance between false positives in the top-right corner and false negatives at the bottom left. As a result, precision and recall aren’t too far off from each other. We favor high precision for a problem such as this one because we want to maximize true positives, but, not at the great expense of recall, so a balance between both is critical. While hyperparameter tuning, the F1 score, and the Matthews correlation coefficient (MCC) are useful metrics to use to this end. The evaluation of the LightGBM base model is shown here:

Figure 11.4: Evaluation of the LightGBM base model

Next, let’s compute the fairness metrics for the model. To do this, we need to make a “deep” copy (deepcopy=True) of the AIF360 dataset, but we change the labels and scores to be those predicted by our model. The compute_aif_metrics function employs the ClassificationMetric class of AIF360 to do for the model what BinaryLabelDatasetMetric did for the dataset. However, it doesn’t engage with the model directly. It computes fairness using the original dataset (test_ds) and the modified one with the model’s predictions (test_pred_ds). The compute_aif_metrics function creates a dictionary with several precalculated metrics (metrics_test_dict) and the metric class (metrics_test_cls), which can be used to obtain metrics one by one. The code can be seen in the following snippet:

test_pred_ds = test_ds.copy(deepcopy=True)
test_pred_ds.labels =\
cls_mdls['lgb_0_base']['preds_test'].reshape(-1,1)
test_pred_ds.scores = \
cls_mdls['lgb_0_base']['probs_test'].reshape(-1,1)
metrics_test_dict, metrics_test_cls = \
mldatasets.compute_aif_metrics(
test_ds,
test_pred_ds,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)
cls_mdls['lgb_0_base'].update(metrics_test_dict)
print('Statistical Parity Difference (SPD): %.4f' %
metrics_test_cls.statistical_parity_difference())
print('Disparate Impact (DI): %.4f' %
metrics_test_cls.disparate_impact())
print('Average Odds Difference (AOD): %.4f' %
metrics_test_cls.average_odds_difference())
print('Equal Opportunity Difference (EOD): %.4f' %
metrics_test_cls.equal_opportunity_difference())
print('Differential Fairness Bias Amplification(DFBA): %.4f' % \
metrics_test_cls.differential_fairness_bias_amplification())

The preceding snippet generates the following output:

Statistical Parity Difference (SPD): -0.0679 Disparate Impact (DI): 0.9193 Average Odds Difference (AOD): -0.0550 Equal Opportunity Difference (EOD): -0.0265 Differential Fairness Bias Amplification (DFBA): 0.2328

Now, putting the metrics we already explained aside, let’s explain what the other ones mean, as follows:

  • Average Odds Difference (AOD): The difference between False-Positive Rates (FPR) averaged with the difference between False-Negative Rates (FNR) for both privileged and underprivileged groups. Negative means there’s a disadvantage for the underprivileged group, and the closer to zero, the better. The formula is shown here:

  • Equal Opportunity Difference (EOD): It’s only the True Positive Rate (TPR) differences of AOD, so it’s only useful to measure the opportunity for TPRs. As with AOD, negative confirms a disadvantage for the underprivileged group, and the closer the value is to zero means there is no significant difference between groups. The formula is shown here:

  • Differential Fairness Bias Amplification (DFBA): This metric was defined in the same paper as SEDF, and similarly has zero as the baseline of fairness and is also intersectional. However, it only measures the difference in unfairness in proportion between the model and the data in a phenomenon called bias amplification. In other words, the value represents how much more the model increases unfairness compared to the original data.

If you compare the model’s SPD and DI metrics to that of the data, they are indeed worse. No surprise there, because it’s to be expected since model-learned representations tend to amplify bias. You can confirm this with the DFBA metrics. As for AOD and EOD, they tend to be in the same neighborhood as the SPD metrics, but ideally, the EOD metric is substantially closer to zero than the AOD metric because we care more about TPRs in this example.

Next, we will go over methods to mitigate bias in the model.

We can mitigate bias at three different levels with methods that operate at these individual levels:

  • Preprocessing: These are interventions to detect and remove bias from the training data before training the model. Methods that leverage pre-processing have the advantage that they tackle bias at the source. On the other hand, any undetected bias could still be amplified by the model.
  • In-processing: These methods mitigate bias during the model training and are, therefore, highly dependent on the model and tend to not be model-agnostic like the pre-processing and post-processing methods. They also require hyperparameter tuning to calibrate fairness metrics.
  • Post-processing: These methods mitigate bias during model inference. In Chapter 6, Anchors and Counterfactual Explanations, we touched on the subject of using the What-If tool to choose the right thresholds (see Figure 6.13 in that chapter), and we manually adjusted them to achieve parity with false positives. Just as we did then, post-processing methods aim to detect and correct fairness directly in the outcomes, but what adjustments to make will depend on which metrics matter most to your problem. Post-processing methods have the advantage that they can tackle outcome unfairness where it can have the greatest impact, but since it’s disconnected from the rest of the model development, it can distort things.

Please note that bias mitigation methods can hurt predictive performance, so there’s often a trade-off. There can be opposing goals, especially in cases where the data is reflective of a biased truth. We can choose to aim for a better truth instead: a righteous one—the one we want, not the one we have.

This section will explain several methods for each level but will only implement and evaluate two for each. Also, we won’t do it in this chapter, but you can combine different kinds of methods to maximize mitigation—for instance, you could use a preprocessing method to de-bias the data, then train a model with it, and lastly, use a post-processing method to remove bias added by the model.

These are some of the most important preprocessing or data-specific bias mitigation methods:

  • Unawareness: Also known as suppression. The most straightforward way to remove bias is to exclude biased features from the dataset, but it’s a naïve approach because you assume that bias is strictly contained in those features.
  • Feature engineering: Sometimes, continuous features capture bias because there are so many sparse areas where the model can fill voids with assumptions or learn from outliers. It can do the same with interactions. Feature engineering can place guardrails. We will discuss this topic in Chapter 12, Monotonic Constraints and Model Tuning for Interpretability.
  • Balancing: Also known as resampling. On their own, representation problems are relatively easy to fix by balancing the dataset. The XAI library (https://github.com/EthicalML/xai) has a balance function that does this by random downsampling and upsampling of group representations. Downsampling, or under-sampling, is what we typically call sampling, which is just taking a certain percentage of the observations, whereas upsampling, or over-sampling, creates a certain percentage of random duplicates. Some strategies synthetically upsample rather than duplicate, such as the Synthetic Minority Oversampling TEchnique (SMOTE). However, we must caution that it’s always preferable to downsample than upsample if you have enough data. It’s best not to use only the balancing strategy if there are other possible bias problems.
  • Relabeling: Also known as massaging, this is having an algorithm change the labels for observations that appear to be most biased, resulting in massaged data by ranking them. Usually, this is performed with a Naïve-Bayes classifier, and to maintain class distribution, it not only promotes some observations but demotes an equal amount.
  • Reweighing: This method similarly ranks observations as relabeling does, but instead of flipping their labels it derives a weight for each one, which we can then implement in the learning process. Much like class weights are applied to each class, sample weights are applied to each observation or sample. Many regressors and classifiers, LGBMClassifier included, support sample weights. Even though, technically, reweighing doesn’t touch the data and solution applied to the model, it is a preprocessing method because we detected bias in the data.
  • Disparate impact remover: The authors of this method were very careful to abide by legal definitions of bias and preserve the integrity of the data without changing the labels or the protected attributes. It implements a repair process that attempts to remove bias in the remaining features. It’s an excellent process to use whenever we suspect that’s where most of the bias is located—that is, the features are highly correlated with the protected attributes, but it doesn’t address bias elsewhere. In any case, it’s a good baseline to use to understand how much of the bias is non-protected features.
  • Learning fair representations: This leverages an adversarial learning framework. There’s a generator (autoencoder) that creates representations of the data excluding the protected attribute, and a critic whose goal is that the learned representations within privileged and underprivileged groups are as close as possible.
  • Optimized preprocessing for discrimination prevention: This method produces transformations through mathematical optimization of the data in such a way that overall probability distributions are maintained. At the same time, the correlation between protected attributes and the target is nullified. The result of this process is data that is distorted slightly to de-bias it.

Given that there are so many pre-processing methods, we will only employ two of them in this chapter. Still, if you are interested in using the ones we won’t cover, they are available in the AIF360 library, and you can read about them in their documentation (https://aif360.res.ibm.com/).

The Reweighing method is fairly simple to implement. You initialize it by specifying the groups, then fit and transform the data as you would with any scikit-learn encoder or scaler. For those that aren’t familiar with fit, the algorithm learns how to transform the provided data, and transform uses what was learned to transform it. The code can be seen in the following snippet:

reweighter= Reweighing(
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)
reweighter.fit(train_ds)
train_rw_ds = reweighter.transform(train_ds)

The transformation derived from this process doesn’t change the data but creates weights for each observation. The AIF360 library is equipped to factor these weights into the calculations of fairness, so we can use BinaryLabelDatasetMetric, as we have before, to compute different metrics. The code can be seen in the following snippet:

metrics_train_rw_ds = BinaryLabelDatasetMetric(
train_rw_ds,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)
print('Statistical Parity Difference (SPD): %.4f' %
metrics_train_rw_ds.statistical_parity_difference())
print('Disparate Impact (DI): %.4f' %
metrics_train_rw_ds.disparate_impact())
print('Smoothed Empirical Differential Fairness(SEDF): %.4f'%
metrics_train_rw_ds.smoothed_empirical_differential_fairness())

The preceding code outputs the following:

Statistical Parity Difference (SPD): -0.0000 Disparate Impact (DI): 1.0000 Smoothed Empirical Differential Fairness (SEDF): 0.1942

The weights have a perfect effect on SPD and DI, making them absolutely fair from those metrics’ standpoints. However, note that SEDF is better than before, but not zero. This is because privileged and underprivileged groups only pertain to the AGE_GROUP protected attribute, but not GENDER. SEDF is a measure of intersectional fairness that reweighting does not address.

You would think that adding weights to observations would adversely impact predictive performance. However, this method was designed to maintain balance. In an unweighted dataset, all observations have a weight of one, and therefore the average of all the weights is one. While reweighting changes the weights for observations, the mean is still approximately one. You can check this is the case by taking the absolute difference in the mean of instance_weights between the original dataset and the reweighted one. It should be infinitesimal. The code can be seen in the following snippet:

np.abs(train_ds.instance_weights.mean() -
train_rw_ds.instance_weights.mean()) < 1e-6

So, how can you apply instance_weights?, you ask. Many model classes have a lesser-known attribute in the fit method, called sample_weight. You simply plug it in there, and while training, it will learn from observations in accordance with the respective weights. This method is shown in the following code snippet:

lgb_rw_mdl = lgb.LGBMClassifier(
random_seed=rand,
max_depth=6,
num_leaves=33,
**lgb_params
)
lgb_rw_mdl.fit(
X_train,
y_train,
sample_weight=train_rw_ds.instance_weights
)

We can evaluate this model as we have with the base model, with evaluate_class_mdl. However, when we calculate the fairness metrics with compute_aif_metrics, we will save them in the model dictionary. Instead of looking at each method’s outcomes one by one, we will compare them at the end of the section. Have a look at the following code snippet:

cls_mdls['lgb_1_rw'] = mldatasets.evaluate_class_mdl(
lgb_rw_mdl,
train_rw_ds.features,
X_test,
train_rw_ds.labels,
y_test,
plot_roc=False,
plot_conf_matrix=True,
show_summary=True,
ret_eval_dict=True
)
test_pred_rw_ds = test_ds.copy(deepcopy=True)
test_pred_rw_ds.labels = cls_mdls['lgb_1_rw']['preds_test'
].reshape(-1,1)
test_pred_rw_ds.scores = cls_mdls['lgb_1_rw']['probs_test'
].reshape(-1,1)
metrics_test_rw_dict, _ = mldatasets.compute_aif_metrics(
test_ds,
test_pred_rw_ds,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)

cls_mdls[‘lgb_1_rw’].update(metrics_test_rw_dict)

The preceding snippet outputs the confusion matrix and performance metrics, as shown in Figure 11.5:

![Chart, waterfall chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_05.png)

Figure 11.5: Evaluation of the LightGBM reweighted model

If you compare Figure 11.5 to Figure 11.4, you can conclude that there’s not much difference in predictive performance between the reweighted and the base model. This outcome was expected, but it’s still good to verify it. Some bias-mitigation methods can adversely impact predictive performance, but reweighing did not. Neither should Disparate Impact (DI) remover, for that matter, which we will discuss next!

This method focuses on bias not located in the protected attribute (AGE_GROUP), so we will have to delete this feature during the process. To that end, we will need its index—in other words, what position it has within the list of columns. We can save this position (protected_index) as a variable, like this:

protected_index = train_ds.feature_names.index('AGE_GROUP')

DI remover is parametric. It requires a repair level between zero and one, so we need to find the optimal one. To that end, we can iterate through an array with different values for repair level (levels), initialize DisparateImpactRemover with each level, and fit_transform the data, which will de-bias the data. However, we then train the model without the protected attribute and use BinaryLabelDatasetMetric to assess the disparate_impact. Remember that DI is a ratio, so it’s a metric that can be between over and under one, and an optimal DI is closest to one. Therefore, as we iterate across different repair levels, we will continuously save the model whose DI is closest to one. We will also append the DIs into an array for later use. Have a look at the following code snippet:

di = np.array([])
train_dir_ds = None
test_dir_ds = None
lgb_dir_mdl = None
X_train_dir = None
X_test_dir = None
levels = np.hstack(
[np.linspace(0., 0.1, 41), np.linspace(0.2, 1, 9)]
)
for level in tqdm(levels):
di_remover = DisparateImpactRemover(repair_level=level)
train_dir_ds_i = di_remover.fit_transform(train_ds)
test_dir_ds_i = di_remover.fit_transform(test_ds)
X_train_dir_i = np.delete(
train_dir_ds_i.features,
protected_index,
axis=1
)
X_test_dir_i = np.delete(
test_dir_ds_i.features,
protected_index,
axis=1
)
lgb_dir_mdl_i = lgb.LGBMClassifier(
random_seed=rand,
max_depth=5,
num_leaves=33,
**lgb_params
)
lgb_dir_mdl_i.fit(X_train_dir_i, train_dir_ds_i.labels)
test_dir_ds_pred_i = test_dir_ds_i.copy()
test_dir_ds_pred_i.labels = lgb_dir_mdl_i.predict(
X_test_dir_i
)
metrics_test_dir_ds = BinaryLabelDatasetMetric(
test_dir_ds_pred_i,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)
di_i = metrics_test_dir_ds.disparate_impact()
if (di.shape[0]==0) or (np.min(np.abs(di-1)) >= abs(di_i-1)):
print(abs(di_i-1))
train_dir_ds = train_dir_ds_i
test_dir_ds = test_dir_ds_i
X_train_dir = X_train_dir_i
X_test_dir = X_test_dir_i
lgb_dir_mdl = lgb_dir_mdl_i
di = np.append(np.array(di), di_i)

To observe the DI at different repair levels, we can use the following code, and if you want to zoom in on the area where the best DI is located, just uncomment the xlim line:

plt.plot(levels, di, marker='o')

The preceding code generates the following output. As you can tell by this, there’s an optimal repair level somewhere between 0 and 0.1 because that’s where it gets closest to one:

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_06.png)

Figure 11.6: DI at different DI remover repair levels

Now, let’s evaluate the best DI-repaired model with evaluate_class_mdl and compute the fairness metrics (compute_aif_metrics). We won’t even plot the confusion matrix this time, but we will save all results into the cls_mdls dictionary for later inspection. The code can be seen in the following snippet:

cls_mdls['lgb_1_dir'] = mldatasets.evaluate_class_mdl(
lgb_dir_mdl,
X_train_dir,
X_test_dir,
train_dir_ds.labels,
test_dir_ds.labels,
plot_roc=False,
plot_conf_matrix=False,
show_summary=False,
ret_eval_dict=True
)
test_pred_dir_ds = test_ds.copy(deepcopy=True)
test_pred_dir_ds.labels = cls_mdls['lgb_1_dir']['preds_test'
].reshape(-1,1)
metrics_test_dir_dict, _ = mldatasets.compute_aif_metrics(
test_ds,
test_pred_dir_ds,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)

cls_mdls[‘lgb_1_dir’].update(metrics_test_dir_dict)

The next link in the chain after data is the model, so even if we de-bias the data, the model introduces bias on its own, thus it makes sense to train models that are equipped to deal with it, which is what we will learn how to do next!

These are some of the most important in-processing or model-specific bias mitigation methods:

  • Cost-sensitive training: We are already incorporating this method into every LightGBM model trained in this chapter through the scale_pos_weight parameter. It’s typically used in imbalanced classification problems and is simply seen as a means to improve accuracy for minor classes. However, given that imbalances with classes tend to favor some groups over others, this method can also be used to mitigate bias, but there are no guarantees that it will. It can be incorporated as class weights or by creating a custom loss function. The implementation will vary according to the model class and what costs are associated with the bias. If they grow linearly with misclassifications, the class weighting will suffice, but otherwise, a custom loss function is recommended.
  • Constraints: Many model classes support monotonic and interaction constraints, and TensorFlow Lattice (TFL) offers more advanced custom shape constraints. These ensure that relationships between features and targets are restricted to a certain pattern, placing guardrails at the model level. There are many reasons you would want to employ them, but chief among them is to mitigate bias. We will discuss this topic in Chapter 12, Monotonic Constraints and Model Tuning for Interpretability.
  • Prejudice remover regularizer: This method defines prejudice as the statistical dependence between the sensitive and target variables. However, the aim of this method is to minimize indirect prejudice, which excludes the prejudice that can be avoided by simply removing the sensitive variable. Therefore, the method starts by quantifying it with a Prejudice Index (PI), which is the mutual information between the target and sensitive variable. Incidentally, we covered mutual information in Chapter 10, Feature Selection and Engineering for Interpretability. Then, along with L2, the PI is incorporated into a custom regularization term. In theory, any model classifier can regularize using the PI-based regularizer, but the only implementation, so far, uses logistic regression.
  • Gerry fair classifier: This is inspired by the concept of fairness gerrymandering, which has the appearance of fairness in one group but lacks fairness when subdivided into subgroups. The algorithm leverages a fictitious play game-theory-inspired approach in which you have a zero-sum game between a learner and an auditor. The learner minimizes the prediction error and aggregate fairness-based penalty term. The auditor takes it one step further by penalizing the learner based on the worst outcomes observed in the most unfairly treated subgroup.

The game’s objective is to achieve a Nash equilibrium, which is achieved when two non-cooperative players with possibly contradictory aims reach a solution that partially satisfies both. In this case, the learner gets a minimal prediction error and aggregate unfairness, and the auditor gets minimal subgroup unfairness. The implementation of this method is model-agnostic.

  • Adversarial debiasing: Similar to the gerry fair classifier, adversarial debiasing leverages two opposing actors, but this time it’s with two neural networks: a predictor and an adversary. We maximize the predictor’s ability to predict the target while minimizing the adversary’s ability to predict the protected feature, thus increasing the equality of odds between privileged and underprivileged groups.
  • Exponentiated gradient reduction: This method automates cost-sensitive optimization by reducing it to a sequence of such problems and using fairness constraints concerning protected attributes such as demographic parity or equalized odds. It is model-agnostic but limited only to scikit-learn-compatible binary classifiers.

Given that there are so many in-processing methods, we will only employ two of them in this chapter. Still, if you are interested in using ones we won’t cover, they are available in the AIF360 library and documentation.

The exponentiated gradient reduction method

Section titled “The exponentiated gradient reduction method”

The ExponentiatedGradientReduction method is an implementation of cost-sensitive training with constraints . We initialize it with a base estimator, the maximum number of iterations to perform (max_iter) and specify the disparity constraints to use. Then, we fit it. This method can be seen in the following code snippet:

lgb_egr_mdl = ExponentiatedGradientReduction(
estimator=lgb_base_mdl,
max_iter=50,
constraints='DemographicParity'
)
lgb_egr_mdl.fit(train_ds)

We can use the predict function to get the training and test predictions and then employ evaluate_class_metrics_mdl and compute_aif_metrics to obtain predictive performance and fairness metrics, respectively. We place both into the cls_mdls dictionary, as illustrated in the following code snippet:

train_pred_egr_ds = lgb_egr_mdl.predict(train_ds)
test_pred_egr_ds = lgb_egr_mdl.predict(test_ds)
cls_mdls['lgb_2_egr'] = mldatasets.evaluate_class_metrics_mdl(
lgb_egr_mdl,
train_pred_egr_ds.labels,
test_pred_egr_ds.scores,
test_pred_egr_ds.labels,
y_train,
y_test
)
metrics_test_egr_dict, _ = mldatasets.compute_aif_metrics(
test_ds,
test_pred_egr_ds,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)

cls_mdls[‘lgb_2_egr’].update(metrics_test_egr_dict)

Next, we will learn about a partially model-agnostic in-processing method that takes into account intersectionality.

The gerry fair classifier is partially model-agnostic. It only supports linear models, Support Vector Machines (SVMs), kernel regression, and decision trees. We initialize GerryFairClassifier by defining a regularization strength (C), a fairness approximation for early stopping (gamma), whether to be verbose (printflag), the maximum number of iterations (max_iters), the model (predictor), and the fairness notion to employ (fairness_def). We will use the fairness notion of false negatives ("FN") to compute the fairness violations’ weighted disparity. Once it’s been initialized, all we need to do is fit it and enable early_termination to stop if it hasn’t improved in five iterations. The code is shown in the following snippet:

dt_gf_mdl = GerryFairClassifier(
C=100,
gamma=.005,
max_iters=50,
fairness_def='FN',
printflag=True,
predictor=tree.DecisionTreeRegressor(max_depth=3)
)
dt_gf_mdl.fit(train_ds, early_termination=True)

We can use the predict function to get the training and test predictions and then employ evaluate_class_metrics_mdl and compute_aif_metrics to obtain predictive performance and fairness metrics, respectively. We place both into the cl_smdls dictionary, as illustrated in the following code snippet:

train_pred_gf_ds = dt_gf_mdl.predict(train_ds, threshold=False)
test_pred_gf_ds = dt_gf_mdl.predict(test_ds, threshold=False)
cls_mdls['dt_2_gf'] = mldatasets.evaluate_class_metrics_mdl(
dt_gf_mdl,
train_pred_gf_ds.labels,
None,
test_pred_gf_ds.labels,
y_train,
y_test
)
metrics_test_gf_dict, _ = mldatasets.compute_aif_metrics(
test_ds,
test_pred_gf_ds,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)

cls_mdls[‘dt_2_gf’].update(metrics_test_gf_dict)

The next and last link in the chain after the model is inference, so even if you de-bias the data and the model there might be some bias left, thus it makes sense to deal with it in this stage too, which is what we will learn how to do next!

These are some of the most important post-processing or inference-specific bias mitigation methods:

  • Prediction abstention: This has many potential benefits such as fairness, safety, and controlling costs, but which one applies will depend on your problem. Typically, a model will return all predictions, even low-confidence ones—that is, predictions that are close to the classification threshold or when the model returns confidence intervals that fall outside of a predetermined threshold. When fairness is involved, if we change predictions to I don’t know (IDK) in low-confidence regions, the model will likely become fairer as a side-effect when we assess fairness metrics only against predictions that were made. It is also possible to make prediction abstention an in-processing method. A paper called Predict Responsibly: Increasing Fairness by Learning to Defer discusses two approaches to do this, by training a model to either punt (learn to predict IDK) or defer (predict IDK when the odds of being correct are lower than an expert opinion). Another paper called The Utility of Abstaining in Binary Classification employs a reinforcement learning framework called Knows What It Knows (KWIK), which has self-awareness of its mistakes but allows for abstentions.
  • Equalized odds postprocessing: Also known as disparate mistreatment, this ensures that privileged and underprivileged groups have equal treatment for misclassifications, whether false-positive or false-negative. It finds optimal probability thresholds with which changing the labels equalizes the odds between groups.
  • Calibrated equalized odds postprocessing: Instead of changing the labels, this method modifies the probability estimates so that they are on average equal. It calls this calibration. However, this constraint cannot be satisfied for false positives and false negatives concurrently, so you are forced to prefer one over the other. Therefore, it is advantageous in cases where recall is far more important than precision or vice versa, and there are benefits to calibrating the estimated probabilities.
  • Reject option classification: This method leverages the intuition that predictions around the decision boundary tend to be the least fair. It then finds an optimal band around the decision boundary for which flipping the labels for underprivileged and privileged groups yields the most equitable outcomes.

We will only employ two of these post-processing methods in this chapter. Reject option classification is available in the AIF360 library and documentation.

The equalized odds post-processing method (EqOddsPostprocessing) is initialized with the groups we want to equalize odds for and the random seed. Then, we fit it. Note that fitting takes two datasets: the original one (test_ds) and then the dataset with predictions for our base model (test_pred_ds). What fit does is compute the optimal probability thresholds. Then, predict creates a new dataset where these thresholds have changed the labels. The code can be seen in the following snippet:

epp = EqOddsPostprocessing(
privileged_groups=privileged_groups,
unprivileged_groups=underprivileged_groups,
seed=rand
)
epp = epp.fit(test_ds, test_pred_ds)
test_pred_epp_ds = epp.predict(test_pred_ds)

We can employ evaluate_class_metrics_mdl and compute_aif_metrics to obtain predictive performance and fairness metrics for Equal-Proportion Probability (EPP), respectively. We place both into the cls_mdls dictionary. The code can be seen in the following snippet:

cls_mdls['lgb_3_epp'] = mldatasets.evaluate_class_metrics_mdl(
lgb_base_mdl,
cls_mdls['lgb_0_base']['preds_train'],
test_pred_epp_ds.scores,
test_pred_epp_ds.labels,
y_train,
y_test
)
metrics_test_epp_dict, _ = mldatasets.compute_aif_metrics(
test_ds,
test_pred_epp_ds,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)

cls_mdls[‘lgb_3_epp’].update(metrics_test_epp_dict)

Next, we will learn about another post-processing method. The main difference is that it calibrates the probability scores rather than only changing the predicted labels.

The calibrated equalized odds postprocessing method

Section titled “The calibrated equalized odds postprocessing method”

Calibrated equalized odds (CalibratedEqOddsPostprocessing) is implemented exactly like equalized odds, except it has one more crucial attribute (cost_constraint). This attribute defines which constraint to satisfy since it cannot make the scores fair for FPRs and FNRs simultaneously. We choose FPR and then fit, predict, and evaluate, as we did for equalized odds. The code can be seen in the following snippet:

cpp = CalibratedEqOddsPostprocessing(
privileged_groups=privileged_groups,
unprivileged_groups=underprivileged_groups,
cost_constraint="fpr",
seed=rand
)
cpp = cpp.fit(test_ds, test_pred_ds)
test_pred_cpp_ds = cpp.predict(test_pred_ds)
cls_mdls['lgb_3_cpp'] = mldatasets.evaluate_class_metrics_mdl(
lgb_base_mdl,
cls_mdls['lgb_0_base']['preds_train'],
test_pred_cpp_ds.scores,
test_pred_cpp_ds.labels,
y_train,
y_test
)
metrics_test_cpp_dict, _ = mldatasets.compute_aif_metrics(
test_ds,
test_pred_cpp_ds,
unprivileged_groups=underprivileged_groups,
privileged_groups=privileged_groups
)

cls_mdls[‘lgb_3_cpp’].update(metrics_test_cpp_dict)

Now that we have tried six bias mitigation methods, two at every level, we can compare them against each other and the base model!

To compare the metrics for all the methods, we can take the dictionary (cls_mdls) and place it in the DataFrame (cls_metrics_df). We are only interested in a few performance metrics and most of the fairness metrics recorded. Then, we output the DataFrame sorted by test accuracy and with all the fairness metrics color-coded. The code can be seen in the following snippet:

cls_metrics_df = pd.DataFrame.from_dict(cls_mdls, 'index')[
[
'accuracy_train',
'accuracy_test',
'f1_test',
'mcc_test',
'SPD',
'DI',
'AOD',
'EOD',
'DFBA'
]
]
metrics_fmt_dict = dict(
zip(cls_metrics_df.columns,['{:.1%}']*3+ ['{:.3f}']*6)
)
cls_metrics_df.sort_values(
by='accuracy_test',
ascending=False

).style.format(metrics_fmt_dict)

The preceding snippet outputs the following DataFrame:

Figure 11.7: Comparison of all bias mitigation methods with different fairness metrics

Figure 11.7 shows that most methods yielded models that are fairer than the base model for SPD, DI, AOD, and EOD. Calibrated equalized odds post-processing (lgb_3_cpp) was the exception, but it had one of the best DFBAs but it yielded a suboptimal DI because of the lopsided nature of the calibration. Note that this method is particularly good at achieving parity for FPR or FNR while calibrating scores, but none of these fairness metrics are useful for picking up on this. Instead, you could create a metric that’s the ratio between FPRs, as we did in Chapter 6, Anchors and Counterfactual Explanations. Incidentally, this would be the perfect use case for Calibrated Equalized Odds (CPP).

The method that obtained the best SPD, DI, AOD, and DFBA, and the second-best EOD was equalized odds post-processing (lgb_3_epp), so let’s visualize fairness for it using XAI’s plots. To this end, we first create a DataFrame with the test examples (test_df) and then use replace to make an AGE_GROUP categorical and obtain the list of categorical columns (cat_cols_l). Then, we can compare different metrics (metrics_plot) using the true labels (y_test), predicted probability scores for the EPP model, the DataFrame (test_df), the protected attribute (cross_cols), and categorical columns. We can do the same for the Receiver Operating Characteristic (ROC) plot (roc_plot) and the Precision-Recall (PR) plot (pr_plot). The code can be seen in the following snippet:

test_df = ccdefault_bias_df.loc[X_test.index]
test_df['AGE_GROUP'] = test_df.AGE_GROUP.replace(
{0:'underprivileged', 1:'privileged'}
)
cat_cols_l = ccdefault_bias_df.dtypes[lambda x: x==np.int8
].index.tolist()
_ = xai.metrics_plot(
y_test,cls_mdls['lgb_3_epp']['probs_test'],
df=test_df, cross_cols=['AGE_GROUP'],
categorical_cols=cat_cols_l
)
_ = xai.roc_plot(
y_test, cls_mdls['lgb_3_epp']['probs_test'],
df=test_df, cross_cols=['AGE_GROUP'],
categorical_cols=cat_cols_l
)
_ = xai.pr_plot(
y_test,
cls_mdls['lgb_3_epp']['probs_test'],
df=test_df, cross_cols=['AGE_GROUP'],
categorical_cols=cat_cols_l
)

The preceding snippet outputs the three plots in Figure 11.8. The first one shows that even the fairest model still has some disparities between both groups, especially between precision and recall and, by extension, F1 score, which is their average. However, the ROC curve shows how close both groups are from an FPR versus a TPR standpoint. The third plot is where the disparities in precision and recall become even more evident. This all demonstrates how hard it is to keep a fair balance on all fronts! Some methods are best for making one aspect perfect but nothing else, while others are pretty good on a handful of aspects but nothing else. Despite the shortcomings of the methods, most of them achieved a sizable improvement. Ultimately, choosing methods will depend on what you most care about, and combining them is also recommended for maximum effect! The output is shown here:

Figure 11.8: Plots demonstrating fairness for the fairest model

We’ve concluded the bias mitigation exercise and will move on to the causal inference exercise, where we will discuss how to ensure fair and robust policies.

Decision-making will often involve understanding cause and effect. If the effect is desirable, you can decide to replicate its cause, or otherwise avoid it. You can change something on purpose to observe how it changes outcomes, or trace an accidental effect back to its cause, or simulate which change will produce the most beneficial impact. Causal inference can help us do all this by creating causal graphs and models. These tie all variables together and estimate effects to make more principled decisions. However, to properly assess the impact of a cause, whether by design or accident, you’ll need to separate its effect from confounding variables.

The reason causal inference is relevant to this chapter is that the bank’s policy decisions have the power to impact cardholder livelihoods significantly and, given the rise in suicides, even life and death. Therefore, there’s a moral imperative to assess policy decisions with the utmost care.

The Taiwanese bank conducted a lending policy experiment for 6 months. The bank saw the writing on the wall and knew that the customers with the highest risk of default would somehow be written off their balance sheets in a way that diminished those customers’ financial obligations. Therefore, the experiment’s focus only involved what the bank considered salvageable, which were low-to-mid risk-of-default customers, and now that the experiment has ended, they want to understand how the following policies have impacted customer behavior:

  • Lower credit limit: Some customers had their credit limit reduced by 25%.
  • Payment plan: They were given 6 months to pay back their current credit card debt. In other words, the debt was split up into six parts, and every month they would have to pay one part.
  • Both measures: A reduction in credit limit and the payment plan.

Also, prevailing credit card interest rates in Taiwan were around 16-20% in 2005, but the bank caught wind that these would be capped at 4% by the Taiwanese Financial Supervisory Commission. Therefore, they ensured all customers in the experiment were automatically provided with interest rates at that level. Some bank executives thought this would only aggravate the indebtedness and create more “credit card slaves” in the process. These concerns prompted the proposal to conduct the experiment with a lower credit card limit as a countermeasure. On the other hand, the payment plan was devised to understand whether debt relief gave customers breathing room to use the card without fear.

On the business side, the rationale was that a healthy level of spending needed to be encouraged because with lower interest rates, the bulk of the profits would come from payment processing, cashback partnerships, and other sources tied to spending and, in turn, increased customer longevity. Yet, this would also be beneficial to customers because if they were more profitable as spenders than as debtors, it meant the incentives were in place to keep them from becoming the latter. All this justified the use of estimated lifetime value (_LTV) as a proxy metric for how the experiment’s outcome benefited both the bank and its customers. For years, the bank has been using a reasonably accurate calculation to estimate how much value a credit card holder will provide to the bank given their spending and payment history, and parameters such as limits and interest rates.

In the parlance of experimental design, the chosen policy is called a treatment, and along with the three treated groups, there’s a control group that wasn’t prescribed a treatment—that is, no change in policy at all, not even the lower interest rates. Before we move forward, let’s first initialize a list with the treatment names (treatment_names) and one that includes even the control group (all_treatment_names), as follows:

treatment_names = [
'Lower Credit Limit',
'Payment Plan',
'Payment Plan &Credit Limit'
]
all_treatment_names = np.array(["None"] + treatment_names)

Now, let’s examine the results of the experiment to help us design an optimal causal model.

Understanding the results of the experiment

Section titled “Understanding the results of the experiment”

A fairly intuitive way of assessing the effectiveness of a treatment is by comparing their outcomes. We want to know the answers to the following two simple questions:

  • Did the treatment decrease the default rate compared to the control group?
  • Were the spending behaviors conducive to an increase in lifetime value estimates?

We can visualize both in a single plot. To this end, we obtain a pandas series with the percentage for each group that defaulted (pct_s), then another one with the sum of lifetime values for each group (ltv_s) in thousands of NTD (K$). We put both series into a pandas DataFrame and plot it, as illustrated in the following code snippet:

pct_s = ccdefault_causal_df[
ccdefault_causal_df.IS_DEFAULT==1]
.groupby(['_TREATMENT'])
.size()
/ccdefault_causal_df.groupby(['_TREATMENT']).size()
ltv_s = ccdefault_causal_df.groupby(
['_TREATMENT'])['_LTV'].sum()/1000
plot_df = pd.DataFrame(
{'% Defaulted':pct_s,
'Total LTV, K$':ltv_s}
)
plot_df.index = all_treatment_names
ax = plot_df.plot(secondary_y=['Total LTV, K$'], figsize=(8,5))
ax.get_legend().set_bbox_to_anchor((0.7, 0.99))plt.grid(False)

The preceding snippet outputs the plot shown in Figure 11.9. It can be inferred that all treatments fare better than the control group. The lowering of the credit limit on its own decreases the default rate by over 12% and more than doubles the estimated LTV, while the payment plan only decreases the defaults by 3% and increases the LTV by about 85%. However, both policies combined quadrupled the control group’s LTV and reduced the default rate by nearly 15%! The output can be seen here:

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_09.png)

Figure 11.9: Outcomes for treatment experiment with different credit policies

Before bank executives rejoice that they have found the winning policy, we must examine how they distributed it among the credit cardholders in the experiment. We learned that they chose the treatment according to the risk factor, which is measured by the _risk_score variable. However, lifetime value is largely affected by the credit limit available (_CC_LIMIT), so we must take that into account. One way to understand the distribution is by plotting both variables against each other in a scatter plot color-coded by _TREATMENT. The code for this can be seen in the following snippet:

sns.scatterplot(
x=ccdefault_causal_df['_CC_LIMIT'].values,
y=ccdefault_causal_df['_risk_score'].values,
hue=all_treatment_names[ccdefault_causal_df['_TREATMENT'].values],
hue_order = all_treatment_names
)

The preceding code generated the plot in Figure 11.10. It shows that the three treatments correspond to different risk levels, while the control group (None) is spread out more vertically. The choice to assign treatments based on risk level also meant that they unevenly distributed the treatments based on _CC_LIMIT. We ought to ask ourselves if this experiment’s biased conditions make it even viable to interpret the outcomes. Have a look at the following output:

![Chart, scatter chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_10.png)

Figure 11.10: Risk factors versus original credit limit

The scatterplot in Figure 11.10 demonstrates the stratification of the treatments across risk factors. However, scatter plots can be challenging to interpret to understand distributions. For that, it’s best to use a K****ernel Density Estimate (KDE) plot. So, let’s see how _CC_LIMIT and lifetime value (_LTV) is distributed across all treatments with Seaborn’s displot. Have a look at the following code snippet:

sns.displot(
ccdefault_causal_df,
x="_CC_LIMIT",
hue="_TREATMENT",
kind="kde",
fill=True
)
sns.displot(
ccdefault_causal_df,
x="_LTV",
hue="_TREATMENT",
kind="kde", fill=True
)

The preceding snippet produced the two KDE plots in Figure 11.11. We can easily tell how far apart all four distributions are for both plots, mostly regarding treatment #3 (Payment Plan & Lower Credit Limit), which tends to be centered significantly more to the right and has a longer and fatter right tail. You can view the output here:

![Chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_11.png)

Figure 11.11: KDE distributions for _CC_LIMIT and _LTV by _TREATMENT

Ideally, when you design an experiment such as this, you should aim for equal distribution among all groups based on any pertinent factors that could alter the outcomes. However, this might not always be feasible, either because of logistical or strategic constraints. In this case, the outcome (_LTV) varies according to customer credit card limits (_CC_LIMIT), the heterogeneity feature—in other words, the varying feature that directly impacts the treatment effect, also known as the heterogeneous treatment effect modifier. We can create a causal model that includes both the _TREATMENT feature and the effect modifier (_CC_LIMIT).

The causal model we will build can be separated into four components, as follows:

  • Outcome (Y): The outcome variable(s) of the causal model.
  • Treatments (T): The treatment variable(s) that influences the outcome.
  • Effect modifiers (X): The variable(s) that influences the effect’s heterogeneity conditioning it. It sits in between the treatment and the outcome.
  • Controls (W): Also known as common causes or confounders. They are the features that influence both the outcome and the treatment.

We will start by identifying each one of these components in the data as separate pandas DataFrames, as follows:

W = ccdefault_causal_df[
[
'_spend','_tpm', '_ppm', '_RETAIL','_URBAN', '_RURAL',
'_PREMIUM'
]
]
X = ccdefault_causal_df[​['_CC_LIMIT']​]
T = ccdefault_causal_df[​['_TREATMENT']​]
Y = ccdefault_causal_df[​['_LTV']​]

We will use the Doubly Robust Learning (DRL) method to estimate the treatment effects. It’s called “doubly” because it leverages two models, as follows:

  • It predicts the outcome with a regression model, as illustrated here:

  • It predicts the treatment with a propensity model, as illustrated here:

It’s also robust because of the final stage, which combines both models while maintaining many desirable statistical properties such as confidence intervals and asymptotic normality. More formally, the estimation leverages regression model g and propensity model p conditional on treatment t, like this:

It also does this:

The goal is to derive the Conditional Average Treatment Effect (CATE) denoted as associated with each treatment t given heterogeneous effect X. First, the DRL method de-biases the regression model by applying the inverse propensity, like this:

How exactly to estimate coefficients from model will depend on the DRL variant employed. We will use a linear variant (LinearDRLearner) so that it returns coefficients and intercepts, which can be easily interpreted. It derives by running ordinary linear regression (OLS) for the outcome differences between a treatment t and the control on xt . This intuitively makes sense because the estimated effect of a treatment minus the estimated effect of the absence of a treatment (t = 0) is the net effect of said treatment.

Now, with all the theory out of the way, let’s dig in!

Initializing the linear doubly robust learner

Section titled “Initializing the linear doubly robust learner”

We can initialize a LinearDRLearner from the econml library, which we call drlearner, by specifying any scikit-learn-compatible regressor (model_regression) and classifier (model_propensity). We will use XGBoost for both, but note that the classifier has an objective=multi:softmax attribute. Remember that we have multiple treatments, so it’s a multiclass classification problem. The code can be seen in the following snippet:

drlearner = LinearDRLearner(
model_regression=xgb.XGBRegressor(learning_rate=0.1),
model_propensity=xgb.XGBClassifier(learning_rate=0.1,
max_depth=2,
objective="multi:softmax"),
random_state=rand
)

If you want to understand what both the regression and propensity model are doing, you can easily fit xgb.XGBRegressor().fit(W.join(X),Y) and xgb.XGBClassifier(objective="multi:softmax").fit(W.join(X), T) models. We won’t do this now but if you are curious, you could evaluate their performance and even run feature importance methods to understand what influences their predictions individually. The causal model brings them together with the DRL framework, leading to different conclusions.

We can use fit in the drlearner to fit the causal model leveraging the dowhy wrapper of econml. The first attributes are the Y, T, X, and Y components: pandas DataFrames. Optionally, you can provide variable names for each of these components: the column names of each of the pandas DataFrames. Lastly, we would like to estimate the treatment effects. Optionally, we can provide the effect modifiers (X) to do this with, and we will use half of this data to do so, as illustrated in the following code snippet:

causal_mdl = drlearner.dowhy.fit(
Y,
T,
X=X,
W=W,
outcome_names=Y.columns.to_list(),
treatment_names=T.columns.to_list(),
feature_names=X.columns.to_list(),
confounder_names=W.columns.to_list(),
target_units=X.iloc[:550].values
)

With the causal model initialized, we can visualize it. The pydot library with pygraphviz can do this for us. Please note that this library is difficult to configure in some environments, so it might not load and show you the much less attractive default graphic instead with view_model. Don’t worry if this happens. Have a look at the following code snippet:

try:
display(Image(to_pydot(causal_mdl._graph._graph).create_png()))
except:
causal_mdl.view_model()

The code in the preceding snippet outputs the model diagram shown here. With it, you can appreciate how all the variables connect:

![Diagram

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_12.png)

Figure 11.12: Causal model diagram

The causal model has already been fitted, so let’s examine and interpret the results, shall we?

Understanding heterogeneous treatment effects

Section titled “Understanding heterogeneous treatment effects”

Firstly, it’s important to note how the dowhy wrapper of econml has cut down on a few steps with the dowhy.fit method. Usually, when you build a CausalModel such as this one directly with dowhy, it has a method called identify_effect that derives the probability expression for the effect to be estimated (the identified estimand). In this case, this is called the Average Treatment Effect (ATE). Then, another method called estimate_effect takes this expression and the models it’s supposed to tie together (regression and propensity). With them, it computes both the ATE, , and CATE, , for every outcome i and treatment t. However, since we used the wrapper to fit the causal model, it automatically takes care of both the identification and estimation steps.

You can access the identified ATE with the identified_estimand_ property and the estimate results with the estimate_ property for the causal model. The code can be seen in the following snippet:

identified_ate = causal_mdl.identified_estimand_
print(identified_ate)
drlearner_estimate = causal_mdl.estimate_
print(drlearner_estimate)

The code shown in the preceding snippet outputs the estimand expression for identified_estimand_, which is a derivation of the expected value for , with some assumptions. Then, the causal-realized estimate_ returns the ATE for treatment #1, as illustrated in the following code snippet:

Estimand type: nonparametric-ate

Estimand name: backdoor1 (Default)

Estimand expression: d ─────────────(E[_LTV|_RETAIL,_URBAN,_PREMIUM,_RURAL,_CC_LIMIT, d[_TREATMENT]

])

Estimand assumption 1, Unconfoundedness: If U→{_TREATMENT} and U→_LTV then \ P(_LTV|_TREATMENT,_RETAIL,_URBAN,_PREMIUM,_RURAL,_CC_LIMIT,_spend,_ppm,_tpm,U) = \ P(_LTV|_TREATMENT,_RETAIL,_URBAN,_PREMIUM,_RURAL,_CC_LIMIT,_spend,_ppm,_tpm)

*** Causal Estimate ***

Estimand type: nonparametric-ate

b:_LTV ~ _TREATMENT + _RETAIL + _URBAN + _PREMIUM + _RURAL + \ _CC_LIMIT + _spend + _ppm + _tpm | _CC_LIMIT Target units:

Mean value: 7227.904763676559 Effect estimates: [6766.07978487 7337.39526574 7363.36013004 7224.20893104 7500.84310705 7221.40328496]

Next, we can iterate across all treatments in the causal model and return a summary for each treatment, like this:

for i in range(causal_mdl._d_t[0]):
print("Treatment: %s" % treatment_names[i])
display(econml_mdl.summary(T=i+1))

The preceding code outputs three linear regression summaries. The first one looks like this:

![Graphical user interface, table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_13.png)

Figure 11.13: Summary of one of the treatments

To get a better sense of the coefficients and intercepts, we can plot them with their respective confidence intervals. To do this, we first create an index of treatments (idxs). There are three treatments, so this is just an array of numbers between 0 and 2. Then, place all the coefficients (coef_) and intercepts (intercept_) into an array using list comprehension. However, it’s a bit more complicated for the 90% confidence intervals for both coefficients and intercepts because coef__interval and intercept__interval return the lower and upper bounds of these intervals. We need the length of the margin of error in both directions, not the bounds. We deduct the coefficient and intercepts from these bounds to obtain their respective margin of error, as illustrated in the following code snippet:

idxs = np.arange(0, causal_mdl._d_t[0])
coefs = np.hstack([causal_mdl.coef_(T=i+1) for i in idxs])
intercepts = np.hstack(
[causal_mdl.intercept_(T=i+1)for i in idxs]
)
coefs_err = np.hstack(
[causal_mdl.coef__interval(T=i+1) for i in idxs]
)
coefs_err[0, :] = coefs - coefs_err[0, :]
coefs_err[1, :] = coefs_err[1, :] - coefs
intercepts_err = np.vstack(
[causal_mdl.intercept__interval(T=i+1) for i in idxs]
).Tintercepts_err[0, :] = intercepts - intercepts_err[0, :]
intercepts_err[1, :] = intercepts_err[1, :] - intercepts

Next, we plot the coefficients for each treatment and respective errors using errorbar. We can do the same with the intercepts as another subplot, as illustrated in the following code snippet:

ax1 = plt.subplot(2, 1, 1)
plt.errorbar(idxs, coefs, coefs_err, fmt="o")
plt.xticks(idxs, treatment_names)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.title("Coefficients")
plt.subplot(2, 1, 2)
plt.errorbar(idxs, intercepts, intercepts_err, fmt="o")
plt.xticks(idxs, treatment_names)
plt.title("Intercepts")

The preceding snippet outputs the following:

![A picture containing chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_14.png)

Figure 11.14: Coefficients and intercepts for all treatments

With Figure 11.14, you can appreciate how relatively large the margin of error is for all intercepts and coefficients. Nonetheless, it’s pretty clear that from the coefficients alone, treatments keep getting marginally better when read from left to right. But before we conclude that Payment Plan & Lower Credit Limit is the best policy, we must consider the intercept, which is lower for this treatment than the first one. Essentially, this means that a customer with a minimal credit card limit is likely to improve lifetime value more with the first policy because the coefficients are multiplied by the limit, whereas the intercept is the starting point. Given that there’s no one best policy for all customers, let’s examine how to choose policies for each, using the causal model.

We can decide on a credit policy on a customer basis using the const_marginal_effect method, which takes the X effect modifier (_CC_LIMIT) and computes the counterfactual CATE, . In other words, it returns the estimated _LTV for all treatments for all observations in X.

However, they don’t all cost the same. Setting up a payment plan requires administrative and legal costs of about *NT∗1,000percontract,andaccordingtothebank’sactuarialdepartment,loweringthecreditlimitby25hasanopportunitycostestimatedat∗NT*1,000 per contract, and according to the bank’s actuarial department, lowering the credit limit by 25 has an opportunity cost estimated at *NT*72 per average payment per month (_ppm) over the lifetime of the customer. To factor these costs, we can set up a simple lambda function that takes the payment plan costs for all treatments and adds them to the variable credit limit costs, which, naturally, is multiplied by _ppm. Given an array with credit card limits of n length, the cost function returns an array of (n, 3) dimensions with a cost for each treatment. Then, we obtain the counterfactual CATE and deduct the costs (treatment_effect_minus_costs). Then, we expand the array to include a column of zeros representing the None treatment and use argmax to return each customer’s recommended treatment index (recommended_T), as illustrated in the following code snippet:

cost_fn = lambda X: np.repeat(
np.array([​[0, 1000, 1000]​]),
X.shape[0], axis=0) + (np.repeat(np.array([​[72, 0, 72]​]),
X.shape[0], axis=0)
*X._ppm.values.reshape(-1,1)
)
treatment_effect_minus_costs = causal_mdl.const_marginal_effect(
X=X.values) - cost_fn(ccdefault_causal_df)
treatment_effect_minus_costs = np.hstack(
[
np.zeros(X.shape),
treatment_effect_minus_costs
]
)
recommended_T = np.argmax(treatment_effect_minus_costs, axis=1)

We can use scatterplot _CC_LIMIT and _ppm, color-coded by the recommended treatment to observe the customer’s optimal credit policy, as follows:

sns.scatterplot(
x=ccdefault_causal_df['_CC_LIMIT'].values,
y=ccdefault_causal_df['_ppm'].values,
hue=all_treatment_names[recommended_T],
hue_order=all_treatment_names
)
plt.title("Optimal Credit Policy by Customer")
plt.xlabel("Original Credit Limit")
plt.ylabel("Payments/month")

The preceding snippet outputs the following scatterplot:

![Chart, scatter chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_11_15.png)

Figure 11.15: Optimal credit policy by customer depending on original credit limit and card usage

It’s evident in Figure 11.15 that “None” (no treatment) is never recommended for any customer. This fact holds even when costs aren’t deducted—you can remove cost_fn from treatment_effect_minus_costs and rerun the code that outputs the plot to verify that treatment is always prescribed regardless of the costs. You can deduce that all treatments are beneficial to customers, some more than others. And, of course, some treatments benefit the bank more than others, depending on the customer. There’s a thin line to tread here.

One of the biggest concerns is fairness to customers, especially those that the bank wronged the most: the underprivileged age group. Just because one policy is more costly to the bank than another, it should not preclude the opportunity to access other policies. One way to assess this would be with a percentage-stacked bar plot for all recommended policies. That way, we can observe how the recommended policy is split between privileged and underprivileged groups. Have a look at the following code snippet:

ccdefault_causal_df['recommended_T'] = recommended_T
plot_df = ccdefault_causal_df.groupby(
['recommended_T','AGE_GROUP']).size().reset_index()
plot_df['AGE_GROUP'] = plot_df.AGE_GROUP.replace(
{0:'underprivileged', 1:'privileged'}
)
plot_df = plot_df.pivot(
columns='AGE_GROUP',
index='recommended_T',
values=0
)
plot_df.index = treatment_names
plot_df = plot_df.apply(lambda r: r/r.sum()*100, axis=1)
plot_df.plot.bar(stacked=True, rot=0)
plt.xlabel('Optimal Policy')
plt.ylabel('%')

The code in the preceding snippet outputs the following:

Figure 11.16: Fairness of optimal policy distributions

Figure 11.16 shows how privileged groups are at a higher proportion assigned one of the policies with the Payment Plan. This disparity is primarily due to the bank’s costs being a factor, so if the bank were to absorb some of these costs, it could make it fairer. But what would be a fair solution? Choosing credit policies is an example of procedural fairness, and there are many possible answers, and any of the solutions would involve the bank absorbing some of the costs associated with implementing the policies. As for robustness, despite the flawed experiment, we can conclude that our estimates have a mediocre level of robustness, passing one robustness test but not the other. That being said, it all depends on what we consider robust enough to validate our findings. Ideally, we would ask the bank to start a new unbiased experiment but waiting another 6 months might not be feasible.

In data science, we often find ourselves working with flawed experiments and biased data and have to make the most of it. Causal inference provides a way to do so by disentangling cause and effect, complete with estimates and their respective confidence intervals. We can then offer findings with all the disclaimers so that decision-makers can make informed decisions. Biased decisions lead to biased outcomes, so the moral imperative of tackling bias can start by shaping decision-making.

The dowhy library comes with four methods to test the robustness of the estimated causal effect, outlined as follows:

  • Random common cause: Adding a randomly generated confounder. If the estimate is robust, the ATE should not change too much.
  • Placebo treatment refuter: Replacing treatments with random variables (placebos). If the estimate is robust, the ATE should be close to zero.
  • Data subset refuter: Removing a random subset of the data. If the estimator generalizes well, the ATE should not change too much.
  • Add unobserved common cause: Adding an unobserved confounder that is associated with both the treatment and outcome. The estimator assumes some level of unconfoundedness but adding more should bias the estimates. Depending on the strength of the confounder’s effect, it should have an equal impact on the ATE.

We will test robustness with the first two next.

This method is the easiest to implement by calling refute_estimate with method_name="random_common_cause". This will return a summary that you can print. Have a look at the following code snippet:

ref_random = causal_mdl.refute_estimate(
method_name="random_common_cause"
)
print(ref_random)

The code in the preceding snippet outputs the following:

Refute: Add a Random Common Cause Estimated effect:7227.904763676559 New effect:7241.433599647397

The preceding output tells us that a new common cause, or W variable, doesn’t have a sizable impact on the ATE.

Replacing the treatment variable with a random variable

Section titled “Replacing the treatment variable with a random variable”

With this method, we will replace the treatment variable with noise. If the treatment correlates robustly with the outcome, this should bring the average effect to zero. To implement it, we also call the refute_estimate function but with placebo_treatment_refuter for the method. We must also specify the placebo_type and the number of simulations (num_simulations). The placebo type we will use is permute, and the more simulations the better, but this will also take longer. The code can be seen in the following snippet:

ref_placebo = causal_mdl.refute_estimate(
method_name="placebo_treatment_refuter",
placebo_type="permute", num_simulations=20
)
print(ref_placebo)

The preceding code outputs the following:

Refute: Use a Placebo Treatment Estimated effect:7227.904763676559 New effect:381.05420029741083 p value:0.32491556283289624

As you can tell by the preceding output, the new effect is close to zero. However, given that the p-value is above 0.05, we cannot reject the null hypothesis that ascertains that the ATE is greater than zero. This tells us that the estimated causal effect is not very robust. We can likely improve it by adding relevant confounders or by using a different causal model, but also, the experimental design had flaws that we cannot fix, such as the biased way the bank prescribed the treatments according to the risk factor.

The mission of this chapter was twofold, as outlined here:

  • Create a fair predictive model to predict which customers are most likely to default.
  • Create a robust causal model to estimate which policies are most beneficial to customers and the bank.

Regarding the first goal, we have produced four models with bias mitigation methods that are objectively fairer than the base model, according to four fairness metrics (SPD, DI, AOD, EOD)—when comparing privileged and underprivileged age groups. However, only two of these models are intersectionally fairer using both age group and gender, according to DFBA (see Figure 11.7). We can still improve fairness significantly by combining methods, yet any one of the four models improves the base model.

As for the second goal, the causal inference framework determined that any of the policies tested is better than no policy for both parties. Hooray! However, it yielded estimates that didn’t establish a single winning one. Still, as expected, the recommended policy varies according to the customer’s credit limit—on the other hand, if we aim to maximize bank profitability, we must factor in the average use of credit cards. The question of profitability presents two goals that we must reconcile: prescribing the recommended policies that benefit either the customer or the bank the most.

For this reason, how to be procedurally fair is a complicated question with many possible answers, and any of the solutions would involve the bank absorbing some of the costs associated with implementing the policies. As for robustness, despite the flawed experiment, we can conclude that our estimates have a mediocre level of robustness, passing one robustness test but not the other. That being said, it all depends on what we consider robust enough to validate our findings. Ideally, we would ask the bank to start a new unbiased experiment but waiting another 6 months might not be feasible.

In data science, we often find ourselves working with flawed experiments and biased data and have to make the most of it. Causal inference provides a way to do so by disentangling cause and effect, complete with estimates and their respective confidence intervals. We can then offer findings with all the disclaimers so that decision-makers can make informed decisions. Biased decisions lead to biased outcomes, so the moral imperative of tackling bias can start by shaping decision-making.

After reading this chapter, you should understand how bias can be detected visually and with metrics, both in data and models, then mitigated through preprocessing, in-processing, and post-processing methods. We also learned about causal inference by estimating heterogeneous treatment effects, making fair policy decisions with them, and testing their robustness. In the next chapter, we also discuss bias but learn how to tune models to meet several objectives, including fairness.

Yeh, I. C., & Lien, C. H. (2009). The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients. Expert Systems with Applications, 36(2), 2473-2480: https://dl.acm.org/doi/abs/10.1016/j.eswa.2007.12.020

  • Chang, C., Chang, H.H., and Tien, J., 2017, A Study on the Coping Strategy of Financial Supervisory Organization under Information Asymmetry: Case Study of Taiwan’s Credit Card Market. Universal Journal of Management, 5, 429-436: http://doi.org/10.13189/ujm.2017.050903
  • Foulds, J., and Pan, S., 2020, An Intersectional Definition of Fairness. 2020 IEEE 36th International Conference on Data Engineering (ICDE), 1918-1921: https://arxiv.org/abs/1807.08362
  • Kamiran, F., and Calders, T., 2011, Data preprocessing techniques for classification without discrimination. Knowledge and Information Systems, 33, 1-33: https://link.springer.com/article/10.1007/s10115-011-0463-8
  • Feldman, M., Friedler, S., Moeller, J., Scheidegger, C., and Venkatasubramanian, S., 2015, Certifying and Removing DI. Proceedings of the 21st ACM SIGKDD International Conference on Knowledge Discovery and Data Mining: https://arxiv.org/abs/1412.3756
  • Kamishima, T., Akaho, S., Asoh, H., and Sakuma, J., 2012, Fairness-Aware Classifier with Prejudice Remover Regularizer. ECML/PKDD: https://dl.acm.org/doi/10.5555/3120007.3120011
  • A. Agarwal, A. Beygelzimer, M. Dudik, J. Langford, and H. Wallach, A Reductions Approach to Fair Classification, International Conference on Machine Learning, 2018. https://arxiv.org/pdf/1803.02453.pdf
  • Kearns, M., Neel, S., Roth, A., and Wu, Z., 2018, Preventing Fairness Gerrymandering: Auditing and Learning for Subgroup Fairness. ICML: https://arxiv.org/pdf/1711.05144.pdf
  • Pleiss, G., Raghavan, M., Wu, F., Kleinberg, J., and Weinberger, K.Q., 2017, On Fairness and Calibration. NIPS: https://arxiv.org/abs/1709.02012
  • Foster, D. and Syrgkanis, V., 2019, Orthogonal Statistical Learning. ICML: http://arxiv.org/abs/1901.09036