Could be a function that takes a user and returns bool, or a string expression? For simplicity, let's use functions.
Segment:
name
rules: list of functions (all must be true? or any? Let's assume all for now, i.e., AND)
Eligibility:
Could be a single rule or a set of rules? Or maybe eligibility is determined by being in a particular segment?
We'll allow two ways: either by segment membership or by a separate rule. But for simplicity, let's say eligibility is a rule that may or may not be the same as segment.
Treatment assignment: We'll have a treatment (like a loan offer). We assign 1 if eligible, 0 otherwise.
FairnessAudit:
We'll compute:
Disparate impact: (P(treatment|protected=0) / P(treatment|protected=1)) [or vice versa, we want to see if one group is favored]
Equal opportunity: P(treatment|protected=0, positive outcome) vs P(treatment|protected=1, positive outcome) -- but we don't have an outcome?
Actually, for eligibility we might not have an outcome. We are just checking if the rule itself is fair?
However, note: In our simulation, we are only simulating the eligibility rule, not the outcome of the treatment. So we are checking if the rule leads to disparate treatment.
We can compute:
- Selection rate: the proportion of each protected group that is eligible.
If the selection rate for one group is significantly lower than another, that's a red flag.
We can also use statistical tests (like chi-squared) to see if the difference is significant.
Let's define:
FairnessAudit:
- population: list of users
- treatment_assignments: list of 0/1 for each user (same order)
- protected_attribute: string (the key in user.attributes to use)
- protected_value1, protected_value2: the two values to compare (or we can do one-vs-rest?)
We'll compute:
rate1 = (number of users with protected_attribute=value1 and treatment=1) / (number of users with protected_attribute=value1)
rate2 = similarly for value2.
Disparate impact ratio: min(rate1, rate2) / max(rate1, rate2) [if we want to see if one group is at least 80% of the other?]
We can also compute the difference: rate1 - rate2.
We'll also compute a p-value for the chi-squared test of independence between protected attribute and treatment.
Rule (as a function, but we can also have a way to compose rules? We'll keep it simple and assume a rule is a function that takes a user and returns bool)
Segment: just a name and a rule function (or list of rules? We can have a segment rule that is a function that takes a user and returns bool, and we can combine multiple rules with AND)
Eligibility: a rule function.
We'll generate a population of users with random attributes. We'll control the distribution to simulate real-world biases.
Example of generating population:
We want to have two protected groups (say, race: A and B). We'll set the proportion of group A to 0.6 and B to 0.4.
We'll also have other attributes that might be correlated with race (to simulate structural biases) but we can start simple.
Let's define:
Attributes:
- race: 'A' or 'B' (with probabilities 0.6 and 0.4)
- income: normal distribution, but with different means for the two races (to simulate income inequality)
- credit_score: normal, also with different means.
We can then define rules that use these attributes.
Example rule for a segment "high_income":
lambda user: user.attributes['income'] > 50000
Example eligibility rule for a loan:
lambda user: user.attributes['credit_score'] > 600
We can also have a rule that explicitly uses race, which would be discriminatory.
We'll simulate:
Step 1: Generate population.
Step 2: Define segments (if needed) and eligibility rule.
Step 3: Assign treatment: 1 if eligibility_rule(user) else 0.
Step 4: Run fairness audit on the treatment assignment with respect to race.
We'll then change the eligibility rule and see how the fairness metrics change.
We can also stress-test by having multiple segments and eligibility based on segment. For example, eligibility might be: user in segment1 or segment2.
Let's design:
We'll have:
class User:
def init(self, id, attributes):
self.id = id
self.attributes = attributes
code
class Segment:
def __init__(self, name, rule):
self.name = name
self.rule = rule # rule is a function: user -> bool
def is_member(self, user):
return self.rule(user)
We can also have a CompositeSegment that combines multiple segments with AND/OR? Not needed for now.
For eligibility, we can have:
EligibilityRule: a function that takes a user and returns bool.
But we might want to have eligibility based on being in a set of segments. So we can have:
EligibilityBySegment(segments):
rule = lambda user: any(segment.is_member(user) for segment in segments)
Or we can have a rule that is a combination of conditions.
We'll keep it flexible: eligibility_rule can be any function.
FairnessAudit:
code
class FairnessAudit:
def __init__(self, population, treatments, protected_attr, group1, group2):
self.population = population
self.treatments = treatments # list of 0/1, same length as population
self.protected_attr = protected_attr
self.group1 = group1
self.group2 = group2
def compute_metrics(self):
# Count for group1
n_group1 = sum(1 for user in self.population if user.attributes[self.protected_attr] == self.group1)
n_treated_group1 = sum(1 for i, user in enumerate(self.population)
if user.attributes[self.protected_attr] == self.group1 and self.treatments[i] == 1)
rate1 = n_treated_group1 / n_group1 if n_group1 > 0 else 0
# Similarly for group2
n_group2 = sum(1 for user in self.population if user.attributes[self.protected_attr] == self.group2)
n_treated_group2 = sum(1 for i, user in enumerate(self.population)
if user.attributes[self.protected_attr] == self.group2 and self.treatments[i] == 1)
rate2 = n_treated_group2 / n_group2 if n_group2 > 0 else 0
# Disparate impact ratio (using the 80% rule: the lower rate should be at least 80% of the higher rate)
# But we compute the ratio as min/max, and if it's below 0.8, it's a potential adverse impact.
ratio = min(rate1, rate2) / max(rate1, rate2) if max(rate1, rate2) > 0 else 1.0
# Chi-squared test for independence
# We have a 2x2 table:
# Treated NotTreated
# group1 a b
# group2 c d
a = n_treated_group1
b = n_group1 - n_treated_group1
c = n_treated_group2
d = n_group2 - n_treated_group2
total = a+b+c+d
if total == 0:
p_value = 1.0
else:
# Expected frequencies:
e_a = (a+c) * (a+b) / total
e_b = (a+b) * (b+d) / total
e_c = (a+c) * (c+d) / total
e_d = (b+d) * (c+d) / total
# Chi-square statistic:
chi2 = ((a - e_a)**2 / e_a if e_a > 0 else 0) + \
((b - e_b)**2 / e_b if e_b > 0 else 0) + \
((c - e_c)**2 / e_c if e_c > 0 else 0) + \
((d - e_d)**2 / e_d if e_d > 0 else 0)
# Degrees of freedom = 1
from scipy.stats import chi2_contingency
# We can use chi2_contingency on the 2x2 table
table = [[a, b], [c, d]]
chi2, p, dof, expected = chi2_contingency(table, correction=False)
p_value = p
return {
'rate_group1': rate1,
'rate_group2': rate2,
'disparate_impact_ratio': ratio,
'p_value': p_value
}
However, note: the chi-squared test requires that expected frequencies are not too low. We might use Fisher's exact test for small samples, but for simulation we can generate enough.
We'll use chi2_contingency from scipy.
But note: we are not required to have scipy in the environment? We can write a simple chi-squared for 2x2? Or we can skip if scipy is not available.
Alternatively, we can compute the p-value using the formula for 2x2 chi-squared with Yates correction? But we already have scipy in the typical data science environment.
Since this is a simulation lab, we assume we have scipy. If not, we can do:
code
if total > 0 and min(e_a, e_b, e_c, e_d) >= 5:
# use chi-squared
else:
# use Fisher's exact? But we don't want to implement that. We can just use chi-squared without correction and note that it's approximate.
Actually, chi2_contingency does the correction by default for 2x2? We set correction=False to not use Yates.
We'll use chi2_contingency without correction.
Now, let's create a simulation function:
code
def simulate(population, eligibility_rule, protected_attr, group1, group2):
treatments = [1 if eligibility_rule(user) else 0 for user in population]
audit = FairnessAudit(population, treatments, protected_attr, group1, group2)
return audit.compute_metrics()
We can then run multiple simulations with different rules.
Let's generate a population:
code
import numpy as np
def generate_population(n, protected_attr='race', group_probs={}, attr_generators=None):
"""
n: number of users
protected_attr: the attribute name for protected group
group_probs: dictionary of group: probability (must sum to 1)
attr_generators: dictionary of attribute: function that takes group (or nothing) and returns a value?
We'll design: for each user, we first sample the protected group, then for each attribute we generate.
But we might want the generation to depend on the group? So we can have a function for each attribute that takes the group and returns a value.
Alternatively, we can have a function that generates a user given the group? Let's do:
attr_generators: dict, key is attribute name, value is a function that takes the protected group (and maybe other things) and returns a value.
We'll also allow some attributes to be independent of the group? Then we can have a function that doesn't take group.
Let's design: for each attribute, the generator function must take the protected group as an argument? But what if we don't want to use the group? Then we ignore.
Alternatively, we can have a two-step: first generate group, then generate other attributes. For each attribute, we can have a conditional distribution given the group.
Example:
attr_generators = {
'income': lambda race: np.random.normal(loc=50000 if race=='A' else 40000, scale=10000),
'credit_score': lambda race: np.random.normal(loc=700 if race=='A' else 650, scale=50)
}
Then for each user:
group = np.random.choice(list(group_probs.keys()), p=list(group_probs.values()))
attributes = {protected_attr: group}
for attr, gen in attr_generators.items():
attributes[attr] = gen(group)
But what about attributes that are not conditional? We can have a gen that ignores the group.
Alternatively, we can have a global function for each attribute that doesn't depend on group? Then we can set:
attr_generators = {
'income': lambda race: ...,
'age': lambda race: np.random.randint(18, 80) # independent of race
}
So it's flexible.
We return a list of User objects.
"""
users = []
groups = np.random.choice(list(group_probs.keys()), size=n, p=list(group_probs.values()))
for i, group in enumerate(groups):
attrs = {protected_attr: group}
for attr, gen in attr_generators.items():
attrs[attr] = gen(group)
users.append(User(i, attrs))
return users
Now we can simulate:
code
population = generate_population(
n=10000,
protected_attr='race',
group_probs={'A': 0.6, 'B': 0.4},
attr_generators={
'income': lambda race: np.random.normal(50000 if race=='A' else 40000, 10000),
'credit_score': lambda race: np.random.normal(700 if race=='A' else 650, 50)
}
)
# Example eligibility rule that uses credit_score only (and no race)
eligibility_rule = lambda user: user.attributes['credit_score'] > 600
Then run the simulation.
But note: because we set different means for credit_score by race, even though the rule doesn't use race, we might see disparate impact because of the correlation.
We can also try to adjust the threshold to see if we can mitigate? But that's not the point.
The stress-testing is about trying different rules and seeing the fairness metrics.
We can also define segments:
code
segment1 = Segment('high_income', lambda user: user.attributes['income'] > 45000)
segment2 = Segment('high_credit', lambda user: user.attributes['credit_score'] > 650)
Then eligibility could be: in segment1 and segment2.
eligibility_rule = lambda user: segment1.is_member(user) and segment2.is_member(user)
But note: the segments themselves might be biased? Because income and credit_score are correlated with race.
So we can stress-test by:
code
- Generating different populations (with different levels of correlation between protected attribute and other attributes)
- Defining different rules (some using protected attribute, some not, some using proxies)
We'll create a function that runs a set of rules and reports the fairness metrics.
But note: we might also want to audit multiple protected attributes? We can extend the FairnessAudit to handle multiple, but for simplicity we do one at a time.
Let's code accordingly.
However, note: the FairnessAudit we designed only compares two groups. What if we have more than two? We can extend to multiple groups by doing pairwise? Or we can compute the maximum difference between any two? Or use a measure like Theil index?
For now, we stick to two groups.
We'll assume the protected attribute is binary for simplicity. We can extend by having a list of groups and then compare the highest and lowest rate? But then we lose which groups are being compared.
Let's keep it binary.
We can also allow the user to specify which two groups to compare.
Now, let's code accordingly.
We'll also want to run multiple simulations to get confidence intervals? But for stress-testing we might just run one with a large population.
Let's code the classes and then a few examples.
We'll also want to visualize? Not required, but we can print the results.
Let's code accordingly.
Steps:
Step 1: Define User, Segment, FairnessAudit, and the simulation function.
Step 2: Generate population.
Step 3: Define eligibility rule.
Step 4: Run simulation and print metrics.
Step 5: Try different rules and see how metrics change.
We'll also want to test with a rule that is fair (or as fair as possible) given the data.
But note: if there is a structural bias in the data (like income and credit_score differ by race), then even a rule that uses only those might still have disparate impact.
We can try to find a rule that minimizes disparate impact? That's a different problem.
For stress-testing, we want to see how sensitive the fairness metrics are to the rules.
Let's code.
We'll write the code in a way that we can easily change the population and rules.
We'll also want to run multiple simulations with different random seeds? Not required, but we can set a seed for reproducibility.
We'll do:
code
np.random.seed(42)
Let's code accordingly.
We'll also note: the eligibility rule might be complex. We can also compose rules with AND/OR. We can define helper functions:
code
def AND(*rules):
return lambda user: all(rule(user) for rule in rules)
def OR(*rules):
return lambda user: any(rule(user) for rule in rules)
Then we can do:
code
eligibility_rule = AND(rule1, rule2)
But for now, we'll just use lambdas.
Let's code.
I'll design a comprehensive Personalization Simulation Lab for stress-testing segmentation, eligibility rules, and fairness audits. This system will allow you to simulate various scenarios, introduce biases, and measure fairness impacts.
System Architecture
python
from dataclasses import dataclass, field
from typing import Dict, List, Callable, Any, Optional, Tuple
import pandas as pd
import numpy as np
from enum import Enum
import matplotlib.pyplot as plt
from scipy import stats