Fairness module in dalex

We live in a world that is getting more divided each day. In some parts of the world, the differences and inequalities between races, ethnicities, and sometimes sexes are aggravating. The data we use for modeling is in the major part a reflection of the world it derives from. And the world can be biased, so data and therefore model will likely reflect that. The introduction to this topic is well presented in Fairness and machine learning.

We propose a way in which ML engineers can easily check if their model is biased.

Fairness module is still work-in-progres and new features will be added over time.

In [1]:
import dalex as dx
import numpy as np
In [2]:

Case study - german credit data

To showcase the abilities of the module, we will be using the German Credit dataset to assign risk for each credit-seeker.

This simple task may require using an interpretable decision tree classifier.

In [3]:
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.tree import DecisionTreeClassifier

# credit data
data = dx.datasets.load_german()

# risk is the target
X = data.drop(columns='risk')
y = data.risk

categorical_features = ['sex', 'job', 'housing', 'saving_accounts', "checking_account", 'purpose']
numerical_features = ['age', 'duration', 'credit_amount']
categorical_transformer = Pipeline(steps=[
    ('onehot', OneHotEncoder(handle_unknown='ignore'))

preprocessor = ColumnTransformer(transformers=[
        ('cat', categorical_transformer, categorical_features),
        ('num', 'passthrough', numerical_features)

clf = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', DecisionTreeClassifier(max_depth=7, random_state=123))

clf.fit(X, y)
                                                  ['sex', 'job', 'housing',
                                                 ('num', 'passthrough',
                                                  ['age', 'duration',
                 DecisionTreeClassifier(max_depth=7, random_state=123))])

We create an Explainer object to proceed with dalex functionalities.

In [4]:
exp = dx.Explainer(clf, X, y)
Preparation of a new explainer is initiated

  -> data              : 1000 rows 9 cols
  -> target variable   : Parameter 'y' was a pandas.Series. Converted to a numpy.ndarray.
  -> target variable   : 1000 values
  -> model_class       : sklearn.tree._classes.DecisionTreeClassifier (default)
  -> label             : Not specified, model's class short name will be used. (default)
  -> predict function  : <function yhat_proba_default at 0x00000292C4D43700> will be used (default)
  -> predict function  : Accepts only pandas.DataFrame, numpy.ndarray causes problems.
  -> predicted values  : min = 0.0, mean = 0.7, max = 1.0
  -> model type        : classification will be used (default)
  -> residual function : difference between y and yhat (default)
  -> residuals         : min = -0.944, mean = 0.0, max = 0.9
  -> model_info        : package sklearn

A new explainer has been created!
In [5]:
recall precision f1 accuracy auc
DecisionTreeClassifier 0.96 0.84 0.896 0.844 0.914793

Let's say that performance is satisfying. To check if the model is biased, we will use the fairness module from dalex. Checking if the model is fair should be straightforward. Apart from the dx.Explainer, we will need 2 parameters:

  • protected - array-like with subgroup values that denote a sensitive attribute (protected variable) like sex, nationality etc. The fairness metrics will be calculated for each of those subgroups and compared.
  • privileged - a string representing one of the subgroups. It should be the one suspected of the most privilege.
In [6]:
# array with values like male_old, female_young, etc.
protected = data.sex + '_' + np.where(data.age < 25, 'young', 'old')

privileged = 'male_old'

Now it is time to check fairness!

We use a unified dalex interface to create a fairness explanation object. Use the model_fairness() method:

In [7]:
fobject = exp.model_fairness(protected = protected, privileged=privileged)

The idea here is that ratios between scores of privileged and unprivileged metrics should be close to 1. The closer the more fair the model is. But to relax this criterion a little bit, it can be written more thoughtfully:


Where the epsilon is a value between 0 and 1, it should be a minimum acceptable value of the ratio. On default, it is 0.8, which adheres to four-fifths rule (80% rule) often looked at in hiring, for example.

In [8]:
fobject.fairness_check(epsilon = 0.8) # default epsilon
No bias was detected!

Conclusion: your model is fair in terms of checked fairness criteria.

Ratios of metrics, based on 'male_old'. Parameter 'epsilon' was set to 0.8 and therefore metrics should be within (0.8, 1.25)
                   TPR       ACC       PPV       FPR       STP
female_old    1.018828  1.000000  0.971963  0.921525  0.964677
female_young  0.981172  0.938824  0.891355  0.872197  0.855055
male_young    1.019874  0.977647  0.929907  0.896861  0.918392

This model cannot be called fair! Generally, each metric should be between (epsilon, 1/epsilon). Metrics are calculated for each subgroup, and then their scores are divided by the score of the privileged subgroup. That is why we omit male_old in this method. When at least 2 metrics have scores ratio outside of the epsilon range, the model may be declared unfair. In our case it cannot be decided automatically but the bias is visible and FPR (False Positive Rate) is preety important in case of risk assigning, so let's call our model unfair.

Useful attributes

The result attribute is metric_scores where each row is divided by row indexed with privileged (in this case male_old).

In [9]:
# to see all scaled metric values you can run
female_old 1.018828 1.063177 0.971963 1.114495 0.590909 0.921525 1.166667 0.474860 1.000000 0.964677
female_young 0.981172 1.102888 0.891355 1.071864 1.409091 0.872197 1.645833 0.670391 0.938824 0.855055
male_old 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000
male_young 1.019874 1.083032 0.929907 1.142509 0.568182 0.896861 1.416667 0.346369 0.977647 0.918392
In [10]:
# or unscaled ones via
female_old 0.974 0.589 0.832 0.915 0.026 0.411 0.168 0.085 0.850 0.792
female_young 0.938 0.611 0.763 0.880 0.062 0.389 0.237 0.120 0.798 0.702
male_old 0.956 0.554 0.856 0.821 0.044 0.446 0.144 0.179 0.850 0.821
male_young 0.975 0.600 0.796 0.938 0.025 0.400 0.204 0.062 0.831 0.754

Bias Detection Plots

The fairness explanation object includes plots that allow bias visualization from different perspectives:

  1. fairness_check plot

  2. metric_scores plot

Fairness Check plot

This is a visualization of the fairness_check result.

In [11]:
Found NaN's or 0's for models: {'DecisionTreeClassifier'}
It is advisable to check 'metric_ratios'