Auditing decisions for fairness
A decision rule can look fair on who it selects, and unfair on who it wrongly refuses. Measure both on simulated credit decisions, and learn what the numbers can't tell you.
What runs in CodeSplash
- Fairness assessment of decisions across groups Verified in Python and R
You will be able to
- Compute selection rates, error rates and calibration across groups
- Interpret demographic parity, equal opportunity and equalized odds
- Say what the four-fifths rule does and doesn't show
- Find what an audit of this kind can't see
Read first
A gap in approvals
PredictPredict first
A credit rule approves one group far less often than another. Is the rule unfair?
Reveal
You can't tell yet, and "no, if that group repays less often" is too quick. Approval rates are one question. You also need to know who gets wrongly refused, and whether the score means the same thing in each group. Different definitions of fair can give different answers on the same data.
Five questions
Read| Question | What you compare | Name |
|---|---|---|
| Who gets selected? | Selection rate | Demographic parityDemographic parityEvery group is selected at the same rate, whatever their outcomes. |
| Among those who'd succeed, who gets selected? | True-positive rate | Equal opportunityEqual opportunityAmong people who truly qualify, every group is selected at the same rate. |
| Among those who wouldn't, who gets selected? | False-positive rate | With the row above, equalized oddsEqualized oddsTrue positive and false positive rates both match across groups. |
| When selected, how often is it right? | Precision | Predictive parityPredictive parityAmong people selected, the share who truly qualify is the same in every group. |
| Does a score mean the same thing? | Score against outcome | CalibrationCalibrationWhether predicted probabilities match observed frequencies — of cases given 30%, about 30% should be positive. within groups |
The group you compare on is the sensitive attributeSensitive attributeA characteristic such as sex, race or age band, across which you check how decisions and errors differ..
Measure it
In the appThese are simulated credit decisions: 888 applicants with scores, in 3 groups, approved at a score of 0.5.
Selection rates (approved = true) range from 37.2% in B to 66.0% in C: a demographic parity difference of 0.288 and a ratio of 0.56. True-positive rates differ by up to 0.284 (equal opportunity) and false-positive rates by up to 0.205; equalized odds difference 0.284.
- Demographic parity difference
- 0.2885
- Selection rate ratio (min / max)
- 0.5632
- Equalized odds difference
- 0.2839
Plots
View data
| group | Upper | Lower | Metric | Rate |
|---|---|---|---|---|
| A | 0.6197 | 0.5346 | Selection rate | 0.5756 |
| A | 0.7811 | 0.6841 | True-positive rate | 0.7336 |
| A | 0.4280 | 0.2951 | False-positive rate | 0.3614 |
| A | 0.7870 | 0.6762 | Precision (PPV) | 0.7336 |
| B | 0.4280 | 0.3139 | Selection rate | 0.3720 |
| B | 0.6001 | 0.4192 | True-positive rate | 0.5161 |
| B | 0.3037 | 0.1541 | False-positive rate | 0.2302 |
| B | 0.7818 | 0.5859 | Precision (PPV) | 0.6882 |
| C | 0.7346 | 0.5864 | Selection rate | 0.6605 |
| C | 0.8677 | 0.7147 | True-positive rate | 0.8000 |
| C | 0.5482 | 0.2992 | False-positive rate | 0.4355 |
| C | 0.8267 | 0.6714 | Precision (PPV) | 0.7477 |
Metrics by group
| group | n | Share | Selection rate | Base rate | True-positive rate | False-positive rate | Precision (PPV) | Accuracy | Mean score | Calibration gap | Brier score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| A | 476 | 53.6% | 57.6% | 57.6% | 73.4% | 36.1% | 73.4% | 69.3% | 0.5368 | −0.0388 | 0.2005 |
| B | 250 | 28.2% | 37.2% | 49.6% | 51.6% | 23.0% | 68.8% | 64.4% | 0.4053 | −0.0907 | 0.2246 |
| C | 162 | 18.2% | 66.0% | 61.7% | 80.0% | 43.5% | 74.8% | 71.0% | 0.6081 | −0.0092 | 0.1916 |
Disparities across groups
| Metric | Value | 95% CI low | 95% CI high |
|---|---|---|---|
| Demographic parity difference | 0.2885 | 0.1965 | 0.3746 |
| Demographic parity ratio | 0.5632 | 0.4691 | 0.6818 |
| Equal opportunity difference (TPR) | 0.2839 | 0.1812 | 0.3944 |
| False-positive rate difference | 0.2053 | 0.0745 | 0.3328 |
| Equalized odds difference | 0.2839 | 0.2019 | 0.3997 |
| Predictive parity difference (PPV) | 0.0595 | 0.0147 | 0.1918 |
| Accuracy difference | 0.0659 | 0.0121 | 0.1752 |
- 12 of 900 rows were left out because a value was missing.
- The lowest selection rate is 0.56 of the highest — below the four-fifths (0.8) rule of thumb for adverse impact.
- Decision: approved = true; groups: group; outcome: repaid; 300 bootstrap resamples within groups (seed 42).
- Differences are max − min across groups; equalized odds difference = max of the TPR and FPR differences (Fairlearn). Which criterion matters depends on the decision: they generally cannot all hold at once when base rates differ.
The exact R script · R R version 4.5.1 (2025-06-13)
# Fairness assessment of decisions across groups
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method fairness.assess 1.0.1 · spec af014cfb29041db2
# Dataset: o2_credit (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_fair_group_metrics(): twin of codesplash.decide.fairness (Fairlearn MetricFrame conventions)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/o2_credit.parquet", col_select = c("group", "approved", "repaid", "score")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("A", "B", "C")) # stored level order
df[["approved"]] <- factor(df[["approved"]], levels = c("false", "true")) # stored level order
df[["repaid"]] <- factor(df[["repaid"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("group", "approved", "repaid", "score")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("group", "approved", "repaid", "score")) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
g_col <- "group"
d_col <- "approved"
y_col <- "repaid"
s_col <- "score"
threshold <- 0.5
n_boot <- as.integer(300)
conf <- 0.95
seed <- 42
reference <- NULL
group_levels <- levels(df[[g_col]])
group <- as.character(df[[g_col]])
if (is.factor(df[[d_col]])) {
cats <- levels(df[[d_col]])
positive <- cats[length(cats)] # default: the second stored level ("true" for yes/no)
pred <- as.numeric(as.character(df[[d_col]]) == positive)
decision_text <- sprintf("%s = %s", d_col, positive)
score <- NULL
} else {
raw <- as.numeric(df[[d_col]])
pred <- as.numeric(raw >= threshold)
decision_text <- sprintf("%s ≥ %s", d_col, format(threshold))
score <- if (min(raw) >= 0 && max(raw) <= 1) raw else NULL
}
if (!is.null(s_col)) score <- as.numeric(df[[s_col]])
y <- NULL
if (!is.null(y_col)) {
if (is.factor(df[[y_col]])) {
ycats <- levels(df[[y_col]])
y_pos <- ycats[length(ycats)] # default: the second stored level
y <- as.numeric(as.character(df[[y_col]]) == y_pos)
} else {
y <- as.numeric(df[[y_col]])
if (!all(y %in% c(0, 1))) stop(sprintf("%s must be 0/1 (or yes/no) to compute error rates.", y_col))
}
}
if (!is.null(score) && is.null(y)) score <- NULL # calibration needs outcomes
# %% Metrics
res <- cs_fair_group_metrics(group, pred, y, score, group_levels, boot = n_boot, conf = conf, seed = seed)
lv_all <- res$levels
per <- res$groups
disp <- res$disparities
ci <- res$ci_disparities
n <- length(pred)
for (lv in lv_all) {
if (per[[lv]]$n < 30) warnings <- c(warnings, sprintf("Group %s has only %d rows; its rates are unstable.", lv, as.integer(per[[lv]]$n)))
if (!is.null(y) && is.nan(per[[lv]]$tpr)) warnings <- c(warnings, sprintf("Group %s has no positive outcomes, so its true-positive rate is undefined.", lv))
}
if (!is.nan(disp$dp_ratio) && disp$dp_ratio < 0.8) {
warnings <- c(warnings, sprintf("The lowest selection rate is %.2f of the highest — below the four-fifths (0.8) rule of thumb for adverse impact.", disp$dp_ratio))
}
# %% Result
lab <- cs_fair_labels()
pct <- sprintf("%.0f%%", conf * 100)
sel <- vapply(lv_all, function(lv) per[[lv]]$selection, numeric(1))
hi <- lv_all[which.max(sel)]
lo <- lv_all[which.min(sel)]
summary <- sprintf("Selection rates (%s) range from %.1f%% in %s to %.1f%% in %s: a demographic parity difference of %.3f and a ratio of %.2f.",
decision_text, 100 * sel[[lo]], lo, 100 * sel[[hi]], hi, disp$dp_diff, disp$dp_ratio)
if (!is.null(y) && !is.nan(disp$eo_diff)) {
summary <- paste(summary, sprintf("True-positive rates differ by up to %.3f (equal opportunity) and false-positive rates by up to %.3f; equalized odds difference %.3f.",
disp$eop_diff, disp$fpr_diff, disp$eo_diff))
}
metric_keys <- c("selection", if (!is.null(y)) c("base_rate", "tpr", "fpr", "ppv", "accuracy"), if (!is.null(score)) c("mean_score", "calibration_gap", "brier"))
group_rows <- do.call(rbind, lapply(lv_all, function(lv) {
r <- data.frame(group = lv, n = per[[lv]]$n, share = per[[lv]]$n / n)
for (k in metric_keys) r[[k]] <- per[[lv]][[k]]
r
}))
disp_labels <- c(dp_diff = "Demographic parity difference", dp_ratio = "Demographic parity ratio", eop_diff = "Equal opportunity difference (TPR)",
fpr_diff = "False-positive rate difference", eo_diff = "Equalized odds difference", ppv_diff = "Predictive parity difference (PPV)",
acc_diff = "Accuracy difference")
dkeys <- intersect(names(disp_labels), names(disp))
disp_rows <- data.frame(metric = unname(disp_labels[dkeys]), value = unlist(disp[dkeys]),
low = vapply(dkeys, function(k) if (!is.null(ci[[k]])) ci[[k]][1] else NA_real_, numeric(1)),
high = vapply(dkeys, function(k) if (!is.null(ci[[k]])) ci[[k]][2] else NA_real_, numeric(1)))
values <- list(n = n, selection = res$overall$selection, groups = length(lv_all))
if (!is.null(y)) values$accuracy <- res$overall$accuracy
for (k in dkeys) {
values[[k]] <- disp[[k]]
if (!is.null(ci[[k]])) {
values[[paste0(k, "_ci_low")]] <- ci[[k]][1]
values[[paste0(k, "_ci_high")]] <- ci[[k]][2]
}
}
for (lv in lv_all) {
values[[sprintf("n[%s]", lv)]] <- per[[lv]]$n
for (k in metric_keys) values[[sprintf("%s[%s]", k, lv)]] <- per[[lv]][[k]]
}
pct_type <- function(k) if (k %in% c("calibration_gap", "brier", "mean_score")) "number" else "percent"
tables <- list(
list(key = "groups", title = "Metrics by group",
columns = c(list(list(key = "group", label = g_col, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "share", label = "Share", type = "percent")),
lapply(metric_keys, function(k) list(key = k, label = lab[[k]], type = pct_type(k)))),
rows = group_rows),
list(key = "disparities", title = "Disparities across groups",
columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "low", label = paste(pct, "CI low"), type = "number"), list(key = "high", label = paste(pct, "CI high"), type = "number")),
rows = disp_rows)
)
if (!is.null(reference) && reference %in% lv_all) {
ref <- per[[reference]]
ref_rows <- do.call(rbind, lapply(lv_all, function(lv) {
r <- data.frame(group = lv, sel_diff = per[[lv]]$selection - ref$selection,
sel_ratio = if (ref$selection > 0) per[[lv]]$selection / ref$selection else NA_real_)
if (!is.null(y)) {
r$tpr_diff <- per[[lv]]$tpr - ref$tpr
r$fpr_diff <- per[[lv]]$fpr - ref$fpr
}
r
}))
for (i in seq_along(lv_all)) values[[sprintf("ratio_ref[%s]", lv_all[i])]] <- ref_rows$sel_ratio[i]
tables[[3]] <- list(key = "reference", title = sprintf("Against the reference group %s", reference),
columns = c(list(list(key = "group", label = g_col, type = "string"), list(key = "sel_diff", label = "Selection rate difference", type = "number"),
list(key = "sel_ratio", label = "Selection rate ratio", type = "number")),
if (!is.null(y)) list(list(key = "tpr_diff", label = "TPR difference", type = "number"),
list(key = "fpr_diff", label = "FPR difference", type = "number"))),
rows = ref_rows)
}
chart_metrics <- c("selection", if (!is.null(y)) c("tpr", "fpr", "ppv"))
cd <- do.call(rbind, lapply(lv_all, function(lv) do.call(rbind, lapply(chart_metrics, function(k) {
b <- res$ci_groups[[lv]][[k]]
data.frame(g = lv, m = lab[[k]], v = per[[lv]][[k]], l = if (is.null(b)) NA_real_ else b[1], h = if (is.null(b)) NA_real_ else b[2])
}))))
roles <- list(group = cs_col(g_col, cd$g, levels = lv_all), metric = cs_col("Metric", cd$m, levels = unname(lab[chart_metrics])), value = cs_col("Rate", cd$v))
if (n_boot > 0) roles <- c(roles, list(low = cs_col("Lower", cd$l), high = cs_col("Upper", cd$h)))
cs_publish(list(
method = "fairness.assess",
methodVersion = "1.0.1",
title = "Fairness assessment",
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = summary,
statistics = c(list(
list(key = "dp_diff", label = "Demographic parity difference", value = disp$dp_diff),
list(key = "dp_ratio", label = "Selection rate ratio (min / max)", value = disp$dp_ratio)
), if (!is.null(y)) list(list(key = "eo_diff", label = "Equalized odds difference", value = disp$eo_diff))),
tables = tables,
warnings = warnings,
notes = list(
paste0("Decision: ", decision_text, "; groups: ", g_col, if (!is.null(y_col)) paste0("; outcome: ", y_col) else "; no outcome (selection rates only)",
if (n_boot > 0) sprintf("; %d bootstrap resamples within groups (seed %s).", n_boot, seed) else "."),
"Differences are max − min across groups; equalized odds difference = max of the TPR and FPR differences (Fairlearn). Which criterion matters depends on the decision: they generally cannot all hold at once when base rates differ."
),
values = values,
charts = list(cs_chart("groups", "group-metrics", sprintf("Rates by %s", g_col), roles, controls = list(reference = NA, band_low = 0, band_high = 0)))
))
Selection rates (approved = true) range from 37.2% in B to 66.0% in C: a demographic parity difference of 0.288 and a ratio of 0.56. True-positive rates differ by up to 0.284 (equal opportunity) and false-positive rates by up to 0.205; equalized odds difference 0.284.
- Demographic parity difference
- 0.2885
- Selection rate ratio (min / max)
- 0.5632
- Equalized odds difference
- 0.2839
To keep this page light, the plots are shown once, under the R tab.
Metrics by group
| group | n | Share | Selection rate | Base rate | True-positive rate | False-positive rate | Precision (PPV) | Accuracy | Mean score | Calibration gap | Brier score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| A | 476 | 53.6% | 57.6% | 57.6% | 73.4% | 36.1% | 73.4% | 69.3% | 0.5368 | −0.0388 | 0.2005 |
| B | 250 | 28.2% | 37.2% | 49.6% | 51.6% | 23.0% | 68.8% | 64.4% | 0.4053 | −0.0907 | 0.2246 |
| C | 162 | 18.2% | 66.0% | 61.7% | 80.0% | 43.5% | 74.8% | 71.0% | 0.6081 | −0.0092 | 0.1916 |
Disparities across groups
| Metric | Value | 95% CI low | 95% CI high |
|---|---|---|---|
| Demographic parity difference | 0.2885 | 0.1965 | 0.3746 |
| Demographic parity ratio | 0.5632 | 0.4691 | 0.6818 |
| Equal opportunity difference (TPR) | 0.2839 | 0.1812 | 0.3944 |
| False-positive rate difference | 0.2053 | 0.0745 | 0.3328 |
| Equalized odds difference | 0.2839 | 0.2019 | 0.3997 |
| Predictive parity difference (PPV) | 0.0595 | 0.0147 | 0.1918 |
| Accuracy difference | 0.0659 | 0.0121 | 0.1752 |
- 12 of 900 rows were left out because a value was missing.
- The lowest selection rate is 0.56 of the highest — below the four-fifths (0.8) rule of thumb for adverse impact.
- Decision: approved = true; groups: group; outcome: repaid; 300 bootstrap resamples within groups (seed 42).
- Differences are max − min across groups; equalized odds difference = max of the TPR and FPR differences (Fairlearn). Which criterion matters depends on the decision: they generally cannot all hold at once when base rates differ.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Fairness assessment of decisions across groups
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method fairness.assess 1.0.1 · spec af014cfb29041db2
# Dataset: o2_credit (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.decide import fairness # twin of codesplashr::cs_fair_group_metrics (Fairlearn MetricFrame conventions)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/o2_credit.parquet", columns=["group", "approved", "repaid", "score"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["A", "B", "C"]) # stored level order
df["approved"] = pd.Categorical(df["approved"], categories=["false", "true"]) # stored level order
df["repaid"] = pd.Categorical(df["repaid"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["group", "approved", "repaid", "score"]) # listwise deletion over the analysis columns
df["group"] = df["group"].cat.remove_unused_categories()
df["approved"] = df["approved"].cat.remove_unused_categories()
df["repaid"] = df["repaid"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["group", "approved", "repaid", "score"]) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
g_col, d_col = "group", "approved"
y_col, s_col = "repaid", "score"
threshold = 0.5
n_boot = int(300)
conf = 0.95
seed = 42
reference = None
group_levels = [str(x) for x in df[g_col].cat.categories]
group = df[g_col].astype(str).to_numpy()
if isinstance(df[d_col].dtype, pd.CategoricalDtype):
cats = [str(x) for x in df[d_col].cat.categories]
positive = cats[-1] # default: the second stored level ("true" for yes/no)
pred = (df[d_col].astype(str) == positive).to_numpy(dtype=float)
decision_text = f"{d_col} = {positive}"
score = None
else:
raw = df[d_col].to_numpy(dtype=float)
pred = (raw >= threshold).astype(float)
decision_text = f"{d_col} ≥ {threshold:g}"
score = raw if (raw.min() >= 0 and raw.max() <= 1) else None
if s_col is not None:
score = df[s_col].to_numpy(dtype=float)
y = None
if y_col is not None:
if isinstance(df[y_col].dtype, pd.CategoricalDtype):
ycats = [str(x) for x in df[y_col].cat.categories]
y_pos = ycats[-1] # default: the second stored level
y = (df[y_col].astype(str) == y_pos).to_numpy(dtype=float)
else:
y = df[y_col].to_numpy(dtype=float)
if not np.isin(y, [0.0, 1.0]).all():
raise ValueError(f"{y_col} must be 0/1 (or yes/no) to compute error rates.")
if score is not None and y is None:
score = None # calibration needs outcomes
# %% Metrics
res = fairness.group_metrics(group, pred, y, score, group_levels, boot=n_boot, conf=conf, seed=seed)
levels = res["levels"]
per, disp, ci = res["groups"], res["disparities"], res["ci_disparities"]
n = len(pred)
for lv in levels:
if per[lv]["n"] < 30:
warnings.append(f"Group {lv} has only {per[lv]['n']:.0f} rows; its rates are unstable.")
if y is not None and np.isnan(per[lv]["tpr"]):
warnings.append(f"Group {lv} has no positive outcomes, so its true-positive rate is undefined.")
if not np.isnan(disp["dp_ratio"]) and disp["dp_ratio"] < 0.8:
warnings.append(f"The lowest selection rate is {disp['dp_ratio']:.2f} of the highest — below the four-fifths (0.8) rule of thumb for adverse impact.")
# %% Result
lab = fairness.LABELS
pct = f"{conf:.0%}"
sel = {lv: per[lv]["selection"] for lv in levels}
hi, lo = max(levels, key=lambda lv: sel[lv]), min(levels, key=lambda lv: sel[lv])
summary = (
f"Selection rates ({decision_text}) range from {sel[lo]:.1%} in {lo} to {sel[hi]:.1%} in {hi}: a demographic parity difference of "
f"{disp['dp_diff']:.3f} and a ratio of {disp['dp_ratio']:.2f}."
)
if y is not None and not np.isnan(disp.get("eo_diff", np.nan)):
summary += (f" True-positive rates differ by up to {disp['eop_diff']:.3f} (equal opportunity) and false-positive rates by up to "
f"{disp['fpr_diff']:.3f}; equalized odds difference {disp['eo_diff']:.3f}.")
metric_keys = ["selection"] + (["base_rate", "tpr", "fpr", "ppv", "accuracy"] if y is not None else []) + (["mean_score", "calibration_gap", "brier"] if score is not None else [])
group_rows = [{"group": lv, "n": per[lv]["n"], "share": per[lv]["n"] / n, **{k: per[lv][k] for k in metric_keys}} for lv in levels]
disp_labels = {"dp_diff": "Demographic parity difference", "dp_ratio": "Demographic parity ratio", "eop_diff": "Equal opportunity difference (TPR)",
"fpr_diff": "False-positive rate difference", "eo_diff": "Equalized odds difference", "ppv_diff": "Predictive parity difference (PPV)",
"acc_diff": "Accuracy difference"}
disp_rows = [{"metric": disp_labels[k], "value": disp[k], "low": ci.get(k, (None, None))[0], "high": ci.get(k, (None, None))[1]} for k in fairness.DISPARITIES if k in disp]
values = {"n": n, "selection": res["overall"]["selection"], "groups": len(levels)}
if y is not None:
values["accuracy"] = res["overall"]["accuracy"]
for k in fairness.DISPARITIES:
if k in disp:
values[k] = disp[k]
if k in ci:
values[f"{k}_ci_low"], values[f"{k}_ci_high"] = ci[k]
for lv in levels:
values[f"n[{lv}]"] = per[lv]["n"]
for k in metric_keys:
values[f"{k}[{lv}]"] = per[lv][k]
tables = [
{"key": "groups", "title": "Metrics by group",
"columns": [{"key": "group", "label": g_col, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "share", "label": "Share", "type": "percent"}]
+ [{"key": k, "label": lab[k], "type": "number" if k in ("calibration_gap", "brier", "mean_score") else "percent"} for k in metric_keys],
"rows": group_rows},
{"key": "disparities", "title": "Disparities across groups",
"columns": [{"key": "metric", "label": "Metric", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"}],
"rows": disp_rows},
]
if reference is not None and reference in per:
ref = per[reference]
ref_rows = []
for lv in levels:
row = {"group": lv, "sel_diff": per[lv]["selection"] - ref["selection"],
"sel_ratio": per[lv]["selection"] / ref["selection"] if ref["selection"] > 0 else None}
if y is not None:
row["tpr_diff"] = per[lv]["tpr"] - ref["tpr"]
row["fpr_diff"] = per[lv]["fpr"] - ref["fpr"]
ref_rows.append(row)
values[f"ratio_ref[{lv}]"] = row["sel_ratio"]
tables.append({"key": "reference", "title": f"Against the reference group {reference}",
"columns": [{"key": "group", "label": g_col, "type": "string"}, {"key": "sel_diff", "label": "Selection rate difference", "type": "number"},
{"key": "sel_ratio", "label": "Selection rate ratio", "type": "number"}]
+ ([{"key": "tpr_diff", "label": "TPR difference", "type": "number"}, {"key": "fpr_diff", "label": "FPR difference", "type": "number"}] if y is not None else []),
"rows": ref_rows})
chart_metrics = ["selection"] + (["tpr", "fpr", "ppv"] if y is not None else [])
cg, cm, cv, cl, ch = [], [], [], [], []
for lv in levels:
for k in chart_metrics:
cg.append(lv)
cm.append(lab[k])
cv.append(per[lv][k])
lo_hi = res["ci_groups"].get(lv, {}).get(k, (None, None))
cl.append(lo_hi[0])
ch.append(lo_hi[1])
roles = {"group": cs.col(g_col, cg, levels=levels), "metric": cs.col("Metric", cm, levels=[lab[k] for k in chart_metrics]), "value": cs.col("Rate", cv)}
if n_boot > 0:
roles.update({"low": cs.col("Lower", cl), "high": cs.col("Upper", ch)})
cs.publish({
"method": "fairness.assess",
"methodVersion": "1.0.1",
"title": "Fairness assessment",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [
{"key": "dp_diff", "label": "Demographic parity difference", "value": disp["dp_diff"]},
{"key": "dp_ratio", "label": "Selection rate ratio (min / max)", "value": disp["dp_ratio"]},
] + ([{"key": "eo_diff", "label": "Equalized odds difference", "value": disp["eo_diff"]}] if y is not None else []),
"tables": tables,
"warnings": warnings,
"notes": [
f"Decision: {decision_text}; groups: {g_col}" + (f"; outcome: {y_col}" if y_col else "; no outcome (selection rates only)")
+ (f"; {n_boot} bootstrap resamples within groups (seed {seed})." if n_boot else "."),
"Differences are max − min across groups; equalized odds difference = max of the TPR and FPR differences (Fairlearn). "
"Which criterion matters depends on the decision: they generally cannot all hold at once when base rates differ.",
],
"values": values,
"charts": [cs.chart("groups", "group-metrics", f"Rates by {g_col}", roles, controls={"reference": None, "band_low": 0, "band_high": 0})],
})
In Metrics by group, find the group approved least. Now compare Base rate, the share who really repaid, for the same groups. Is the gap in approvals bigger than the gap in repayment?
The four-fifths rule
PredictPredict first
The rule of thumb says to flag a selection rate below four-fifths (0.8) of the highest rate. Divide the lowest Selection rate on the card by the highest. What is the ratio?
Make your guess between 0 and 1 ratio, then reveal.
Reveal
0.56, with a 95% interval from 0.47 to 0.68. That's well below 0.8. The gap is 0.288 in rate. The rule comes from US employment guidance, and it's a screening flag. It isn't a test of fairness, or a legal finding, in either direction.
Read the errors
ReadThe next two lines are about mistakes. Among people who really repaid, approval rates differ by up to 0.284: that's the equal opportunity difference. Among people who didn't, they differ by up to 0.205.
Each has an interval, because a small group's rates vary a lot by chance alone. Then read Calibration gap, the mean score minus the base rate. Group B's sits furthest from zero, and it's negative: the score understates how often group B repays.
This simulation was built with that flaw. In real data, a gap like this is where your next question starts.
Check your understanding
CheckpointCheck yourself
Selection rates are 57.6%, 37.2% and 66.0%, in three groups. What is the demographic parity difference, as a proportion? Use three decimals.
Show the answer
Answer: 0.288493827160494
Highest minus lowest. The unrounded rates give the recorded value, close to .
Check yourself
Among applicants who would really repay, group B is approved far less often than group C. Which measure shows this?
Show the answer
Answer: b
Equal opportunity compares true-positive rates: selection among people who would succeed.
Check yourself
One group has 40 people, and its false-positive rate is 12 points above the rest. What should you do first?
Show the answer
Answer: c
Small groups vary a lot, so report the interval. Dropping them would remove the people an audit most needs to see.
What the numbers can't see
ReflectAn audit measures what's in the table. Ask three questions about what isn't:
- Is the outcome trustworthy? You only learn whether people repaid if they were approved, so refused applicants have no outcome. That's selective labelsSelective labelsYou only observe the outcome for people who were selected, so error rates are unknown for those refused..
- Who chose the groups? Intersections, such as age within sex, can hide gaps that each attribute shows no sign of.
- Who is missing? People who never applied aren't in the data at all.
For a decision you know about, write down one answer to each.
Run an audit
In the appOpen Decisions & fairness in Studios, and choose Audit decisions for fairness. Set the group, the decision, the true outcome and the score: {{group}}, {{decision}}, {{outcome}} and {{score}} in the walkthrough. The walkthrough below does this on the same practice data.
A binary model in Predict has a Fairness tab too, and the column you compare on doesn't need to be one of the model's features.
import pandas as pd
df = pd.read_csv("credit.csv").dropna(subset=["score"])
rates = df.groupby("group").apply(
lambda g: pd.Series({
"selection": g["approved"].mean(),
"base_rate": g["repaid"].mean(),
"tpr": g.loc[g["repaid"], "approved"].mean(),
"fpr": g.loc[~g["repaid"], "approved"].mean(),
}),
include_groups=False,
)
print(rates)
print("parity difference:", rates["selection"].max() - rates["selection"].min())
print("parity ratio:", rates["selection"].min() / rates["selection"].max())df <- read.csv("credit.csv")
df <- df[!is.na(df$score), ]
df$approved <- as.logical(df$approved)
df$repaid <- as.logical(df$repaid)
rates <- sapply(split(df, df$group), function(g) c(
selection = mean(g$approved),
base_rate = mean(g$repaid),
tpr = mean(g$approved[g$repaid]),
fpr = mean(g$approved[!g$repaid])
))
rates
diff(range(rates["selection", ]))
min(rates["selection", ]) / max(rates["selection", ])Recap
Recap- Compare selection, error rates and calibration, because each asks a different question about fairness.
- Report intervals. The four-fifths ratio is a flag, not a verdict.
- An audit can only see what's in the table, so ask how the outcome was measured and who's missing.
Concepts in this lesson