← All posts

Ethical AI: Identifying and Mitigating Algorithmic Bias

A model can pass its test set and still treat groups of people differently, and a single accuracy number will not show it. Finding the gap takes a per-group check. Closing it takes a decision about which definition of fair applies, and that decision has a cost you can measure.

In short

  • On Adult, averaged over five splits, a baseline logistic regression had an equalised odds difference of 0.098; the threshold optimiser and exponentiated gradient cut it to 0.021 and 0.025, at a cost of 0.011 to 0.017 in overall accuracy.
  • Bias enters at seven points in the life cycle, and the main fairness criteria cannot all hold when base rates differ between groups, so the choice of criterion is a judgement about harm, and you should record it.
  • Results move between splits: which method did better on sex changed, and with race as the group the baseline gap ranged from 0.145 to 0.547, so report the spread and group sizes before relying on a small gap.
  • For any model that decides something about people, the checklist below covers running and documenting an audit.

Two documented failures

Buolamwini and Gebru audited three commercial gender classifiers on a new benchmark balanced by gender and skin type. They report that darker-skinned females were the most misclassified group, with error rates of up to 34.7%, against a maximum error rate of 0.8% for lighter-skinned males. They also found that two widely used face benchmarks, IJB-A and Adience, were 79.6% and 86.2% lighter-skinned subjects. The audit exposed a representation problem in the benchmarks and a performance gap in the products, and only per-subgroup reporting showed either (Gender Shades, 2018).

The second case concerns metrics rather than data. ProPublica analysed COMPAS recidivism scores for defendants in Broward County, Florida, scored in 2013 and 2014, with recidivism defined for most of the analysis as a new arrest within two years (methodology). Their article reports that 44.9% of African American defendants who did not re-offend were labelled higher risk, against 23.5% of white defendants (ProPublica, 2016). That is a gap in false positive rates. Chouldechova later showed that predictive parity, a criterion taken from educational and psychological testing, can produce this kind of disparate impact when recidivism rates differ between groups (arXiv:1610.07524). Northpointe, the vendor, disputed the analysis in a response titled "COMPAS Risk Scales: Demonstrating Accuracy Equity and Predictive Parity" (Dieterich, Mendoza and Brennan, 2016; see ProPublica's reply to it). The two sides used different criteria, and Chouldechova's result shows why both findings can hold.

Where bias comes from

"The data is biased" is too coarse to act on. Suresh and Guttag name seven sources of harm across the life cycle, each needing a different fix (arXiv:1901.10002):

SourceWhat goes wrongFirst thing to check
HistoricalThe world the data describes is already unequal, even if sampling and measurement are perfectWhether the target reproduces a past decision
RepresentationThe development sample under-represents part of the populationGroup counts against the deployment population
MeasurementFeatures or labels are chosen, collected or computed in a way that differs across groupsWhether the label is a proxy for the thing you care about
AggregationOne model is used where groups behave differentlyPer-group fit and calibration
LearningModelling choices amplify performance gapsThe objective and regularisation, per-group error
EvaluationThe benchmark does not represent the use population, or aggregate metrics hide gapsBenchmark composition, disaggregated metrics
DeploymentThe system is used differently from how it was built or testedActual use against intended use

Removing the sensitive attribute from the features does little about most of these, since other features can stand in for it, and you still need it to measure the gap.

Metrics, defined

Let Y be the true label, Ŷ the prediction, A the sensitive attribute and S a score. Fairlearn documents demographic parity and equalised odds, and describes equal opportunity as the relaxation of equalised odds to the positive class (Fairlearn user guide).

CriterionCondition, for all groups a and bWhen it fits
Demographic parityP(Ŷ = 1 | A = a) = P(Ŷ = 1 | A = b)Allocation of a benefit where the label is itself suspect
Equal opportunityP(Ŷ = 1 | Y = 1, A = a) = P(Ŷ = 1 | Y = 1, A = b)Missing a qualified person is the main harm
Equalised oddsEqual opportunity, and P(Ŷ = 1 | Y = 0, A = a) = P(Ŷ = 1 | Y = 0, A = b)Both kinds of error cause harm and labels are trustworthy
Predictive parityP(Y = 1 | Ŷ = 1, A = a) = P(Y = 1 | Ŷ = 1, A = b)Decision makers act on a positive prediction and need it to mean the same in each group
CalibrationP(Y = 1 | S = s, A = a) = s for each groupScores are read as probabilities

Demographic parity ignores the label, so a useless model can meet it. Equalised odds and equal opportunity use the label, so they inherit its flaws: if the label records past arrests rather than past offending, the metric treats that record as ground truth.

Why you cannot have all of them

Kleinberg, Mullainathan and Raghavan formalise three fairness conditions for probabilistic classification and prove that, except in highly constrained special cases, no method can satisfy all three at once; meeting them even approximately requires the data to lie close to one of those cases (arXiv:1609.05807).

In practice, if base rates differ between groups, a score that is equally calibrated will generally have unequal error rates. Which criterion to prioritise is a value judgement about which error is worse and for whom.

The four-fifths rule

US employment guidance gives a screening threshold: a selection rate below four-fifths (80%) of the rate for the group with the highest rate is generally regarded as evidence of adverse impact. The same section says smaller differences may still be adverse impact where significant in statistical and practical terms, and greater ones may not be, for example on small numbers (29 CFR 1607.4(D)). Fairlearn's guide says that applying this threshold to demographic_parity_ratio is wrong in many scenarios and that the rule is generally used only in US federal employment regulation. Treat it as a legal screening rule, not a general fairness test.

Mitigation: three stages

Three stages at which bias mitigation can act: training data, model training and predictions, each with example methods Training data Model training Predictions Pre-processing In-processing Post-processing Reweighing Kamiran and Calders Exponentiated gradient Adversarial debiasing Threshold optimisation Hardt et al.
Figure 1. Mitigation can change the data before training, the training objective, or the decision rule applied to predictions.
  • Pre-processing: reweighing. Each (group, label) combination gets its own example weight before a classifier is trained (AIF360 docs, citing Kamiran and Calders). It leaves the model alone but does nothing about proxies in the features.
  • In-processing: exponentiated gradient. Agarwal et al. reduce fair classification to cost-sensitive classification problems, giving a randomised classifier with the lowest empirical error that meets the constraints (arXiv:1803.02453). Predictions can vary between calls, which is a problem if a decision must be reproducible.
  • In-processing: adversarial debiasing. A predictor for Y is trained against an adversary that tries to predict the protected variable. Zhang et al. report, on UCI Adult, a model that loses little accuracy and comes very close to equality of odds (arXiv:1801.07593).
  • Post-processing: threshold optimisation. Hardt, Price and Srebro adjust an already-trained predictor to meet an equalised-odds-style criterion using only the predictor, the target and group membership (arXiv:1610.02413). It needs the sensitive attribute at prediction time, which may be unlawful or unavailable.

A runnable example with Fairlearn

Written against Fairlearn 0.15.0 (the latest release as of December 2026, uploaded 12 October 2026), scikit-learn 1.9.1, pandas 3.1.2 and Python 3.14.5; other versions may give slightly different numbers. A rerun of the code and the five-split loops in these versions on 1 December 2026 reproduced every figure in the three tables below. The example uses two of Fairlearn's mitigation methods. ThresholdOptimizer.predict takes sensitive_features as a required keyword, and random_state makes its randomised output reproducible (API reference). The first fetch_adult call needs a network connection.

from fairlearn.datasets import fetch_adult
from fairlearn.metrics import (
    MetricFrame, selection_rate, true_positive_rate, false_positive_rate,
    demographic_parity_difference, equalized_odds_difference)
from fairlearn.postprocessing import ThresholdOptimizer
from fairlearn.reductions import ExponentiatedGradient, EqualizedOdds
from sklearn.compose import make_column_transformer, make_column_selector
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

data = fetch_adult(as_frame=True)
# Sensitive columns out of the features
X = data.data.drop(columns=["sex", "race"])
y = (data.target == ">50K").astype(int)
A = data.data["sex"]
Xtr, Xte, ytr, yte, Atr, Ate = train_test_split(
    X, y, A, test_size=0.3, random_state=0, stratify=y)

prep = make_column_transformer(
    (OneHotEncoder(handle_unknown="ignore", sparse_output=False),
     make_column_selector(dtype_include=["category", "object"])),
    (StandardScaler(), make_column_selector(dtype_include="number")))
base = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(Xtr, ytr)

def report(name, pred):
    mf = MetricFrame(
        metrics={"accuracy": accuracy_score,
                 "selection_rate": selection_rate,
                 "tpr": true_positive_rate,
                 "fpr": false_positive_rate},
        y_true=yte, y_pred=pred, sensitive_features=Ate)
    print(name); print(mf.by_group.round(3))
    dp = demographic_parity_difference(yte, pred, sensitive_features=Ate)
    eo = equalized_odds_difference(yte, pred, sensitive_features=Ate)
    print(f"accuracy {accuracy_score(yte, pred):.3f}  DP diff {dp:.3f}  EO diff {eo:.3f}")

report("baseline", base.predict(Xte))

# Post-processing: needs the sensitive feature again at prediction time
to = ThresholdOptimizer(estimator=base, constraints="equalized_odds",
                        objective="accuracy_score", prefit=True,
                        predict_method="predict_proba")
to.fit(Xtr, ytr, sensitive_features=Atr)
pred_to = to.predict(Xte, sensitive_features=Ate, random_state=0)
report("threshold optimiser", pred_to)

# In-processing: reductions need a dense numeric matrix
Xtr_t, Xte_t = prep.fit_transform(Xtr), prep.transform(Xte)
eg = ExponentiatedGradient(LogisticRegression(max_iter=1000),
                           constraints=EqualizedOdds(), eps=0.01)
eg.fit(Xtr_t, ytr, sensitive_features=Atr)
report("exponentiated gradient", eg.predict(Xte_t, random_state=0))

Output on a 30% stratified test split (seed 0). The two difference columns are the largest gap between the two groups.

ModelOverall accuracySelection rate, female / maleDemographic parity differenceEqualised odds difference
Logistic regression0.8530.076 / 0.2530.1780.112
Threshold optimiser0.8380.111 / 0.2030.0920.030
Exponentiated gradient0.8420.109 / 0.2180.1090.017

Both methods were asked for equalised odds and both reduced that gap, at a cost of 0.011 to 0.015 in overall accuracy on this split (the five-split means below give 0.011 to 0.017). Demographic parity improved as a side effect, though it was not the target and a gap remains. Baseline per-group accuracy shows why accuracy alone misleads: female accuracy was 0.925 against 0.817 for male, largely because fewer women in the data earn above USD 50,000 (10.9% against 30.4% of the full dataset), so a model that predicts "no" more often is right more often.

One split can mislead, so I re-ran the code on five stratified 70/30 splits (random_state 0 to 4 in train_test_split, the mitigations' own seeds fixed at 0):

ModelAccuracy, mean (range)DP difference, mean (range)EO difference, mean (range)
Logistic regression0.852 (0.849 to 0.855)0.176 (0.167 to 0.187)0.098 (0.072 to 0.120)
Threshold optimiser0.835 (0.832 to 0.838)0.086 (0.072 to 0.096)0.021 (0.011 to 0.030)
Exponentiated gradient0.841 (0.839 to 0.844)0.103 (0.095 to 0.111)0.025 (0.012 to 0.058)

Both methods cut the equalised odds gap on every split, but their order did not hold. On seed 0 exponentiated gradient looked better (0.017 against 0.030); over five splits the threshold optimiser averaged 0.021 against 0.025, and exponentiated gradient ranged from 0.012 to 0.058. Five splits are too few for an interval, so treat differences of a few thousandths as noise.

The code drops race as well as sex from the features. Repeating the five-split run with A = data.data["race"] (five groups; in each test split White has about 12,500 rows, Black about 1,400, Asian-Pac-Islander 433 to 466, Amer-Indian-Eskimo 121 to 160 and Other 107 to 125) shows what small groups do to these metrics:

Model (race as the group)Accuracy, mean (range)DP difference, mean (range)EO difference, mean (range)
Logistic regression0.852 (0.849 to 0.855)0.175 (0.156 to 0.234)0.294 (0.145 to 0.547)
Threshold optimiser0.847 (0.843 to 0.852)0.087 (0.065 to 0.137)0.206 (0.093 to 0.497)
Exponentiated gradient0.836 (0.826 to 0.843)0.111 (0.087 to 0.174)0.240 (0.122 to 0.507)

The baseline's equalised odds difference ranges from 0.145 to 0.547 across splits, and the mitigations only partly reduce it. It is set by groups with few positive cases: in the two smallest groups the baseline's true positive rate moves between 0.182 and 0.545, and between 0.267 and 0.571, from split to split. With groups this small, report the group sizes beside the gap and treat a single-split figure as noise.

Limits of this dataset

Adult has 48,842 samples and 14 features, and the target is whether a person earns more than USD 50,000 a year (Fairlearn dataset page). The references on that page date from 1996, so it reflects an old population, and its sex column has only two values. Income is also a proxy for the decisions people care about in lending or hiring, and the label carries historical bias. It suits teaching and is a poor basis for conclusions about a real system.

AIF360

IBM's AI Fairness 360 is an Apache-2.0 toolkit of fairness metrics and mitigation algorithms. Its repository lists 15 mitigation entries (repository). The two libraries overlap, so pick the API that fits your pipeline.

Documentation and regulation

Mitchell et al. propose model cards: short documents that report benchmarked performance across demographic, cultural, phenotypic and intersectional groups relevant to the intended application, with the intended use and evaluation procedure (arXiv:1810.03993). Gebru et al. propose datasheets for datasets, covering motivation, composition, collection and recommended uses (arXiv:1803.09010).

For systems in the EU, Article 10 of the AI Act sets data governance duties for high-risk systems. Its paragraph 2 lists practices that include examination of the data for biases likely to affect health and safety, negatively affect fundamental rights or lead to prohibited discrimination, and appropriate measures to detect, prevent and mitigate those biases. The exact wording is in the Official Journal text of Regulation (EU) 2024/1689. As of December 2026 that text has been amended: according to secondary commentary, Regulation (EU) 2026/1744 (the digital omnibus on AI, in force since 27 July 2026) moves the application of the high-risk requirements for Annex III systems to 2 December 2027 and for Annex I product systems to 2 August 2028, deletes Article 10(5), and adds an Article 4a that gives a legal basis for processing special-category personal data for bias detection and correction under conditions, without creating a duty to do so. The Official Journal text of the amending act was not checked for this post, so confirm dates and conditions there. This post is not legal advice.

Fairness audit checklist

Nine steps. Keep the answers in the model card.

  1. Define the decision and the harm. State what the model decides, about whom, and which error hurts most.
  2. Choose the groups and check their sizes. Compare group counts with the deployment population, and keep the sensitive attribute for measurement even if it is not a feature.
  3. Pick a criterion and record why. The criteria cannot all hold when base rates differ, so write down the alternatives you rejected.
  4. Check the label. A proxy label is not repaired by any metric.
  5. Measure per group, with intervals. Report accuracy, selection rate and error rates for each group across several splits, with the spread.
  6. Try a mitigation. Reweighing, exponentiated gradient or threshold optimisation. Note whether it needs the sensitive attribute at prediction time or randomises predictions.
  7. Record the accuracy cost. Keep the before and after numbers.
  8. Document it. Write the model card and the dataset datasheet.
  9. Monitor after launch. Bias returns as the population or pipeline changes. Track per-group metrics next to accuracy, with group sizes, since small groups give noisy rates.

Sources