Skip to content

Audit decisions for fairness

Compare selection and error rates across groups, see why the definitions of fairness conflict, and weigh what a constraint costs.

Applied ~14 min11 steps

What runs in CodeSplash

You will be able to

  • Compute and tell apart demographic parity, equal opportunity and equalized odds
  • Explain why fairness definitions conflict when base rates differ
  • Read the cost of fair thresholds, and say who should decide
01

Who gets approved?

Read

A lender's model approves or declines credit. You have the decisions for 888 applicants in 3 groups, with who really repaid.

Three common questions:

  • Demographic parityDemographic parityEvery group is selected at the same rate, whatever their outcomes.: are groups approved at the same rate?
  • Equal opportunityEqual opportunityAmong people who truly qualify, every group is selected at the same rate.: among people who would repay, are groups approved at the same rate?
  • Equalized oddsEqualized oddsTrue positive and false positive rates both match across groups.: are both true- and false-positive rates equal?

They sound similar. They aren't.

02

Run the audit

In the app
Fairness assessmentRecorded · Python and R agreeRecorded 2026-11-17 · 55 values compared
R

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

Rates by groupDo a model's decisions or error rates differ across groups, and by how much?
View data
groupUpperLowerMetricRate
A0.61970.5346Selection rate0.5756
A0.78110.6841True-positive rate0.7336
A0.42800.2951False-positive rate0.3614
A0.78700.6762Precision (PPV)0.7336
B0.42800.3139Selection rate0.3720
B0.60010.4192True-positive rate0.5161
B0.30370.1541False-positive rate0.2302
B0.78180.5859Precision (PPV)0.6882
C0.73460.5864Selection rate0.6605
C0.86770.7147True-positive rate0.8000
C0.54820.2992False-positive rate0.4355
C0.82670.6714Precision (PPV)0.7477

Metrics by group

groupnShareSelection rateBase rateTrue-positive rateFalse-positive ratePrecision (PPV)AccuracyMean scoreCalibration gapBrier score
A47653.6%57.6%57.6%73.4%36.1%73.4%69.3%0.5368−0.03880.2005
B25028.2%37.2%49.6%51.6%23.0%68.8%64.4%0.4053−0.09070.2246
C16218.2%66.0%61.7%80.0%43.5%74.8%71.0%0.6081−0.00920.1916

Disparities across groups

MetricValue95% CI low95% CI high
Demographic parity difference0.28850.19650.3746
Demographic parity ratio0.56320.46910.6818
Equal opportunity difference (TPR)0.28390.18120.3944
False-positive rate difference0.20530.07450.3328
Equalized odds difference0.28390.20190.3997
Predictive parity difference (PPV)0.05950.01470.1918
Accuracy difference0.06590.01210.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)))
))
Python

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

groupnShareSelection rateBase rateTrue-positive rateFalse-positive ratePrecision (PPV)AccuracyMean scoreCalibration gapBrier score
A47653.6%57.6%57.6%73.4%36.1%73.4%69.3%0.5368−0.03880.2005
B25028.2%37.2%49.6%51.6%23.0%68.8%64.4%0.4053−0.09070.2246
C16218.2%66.0%61.7%80.0%43.5%74.8%71.0%0.6081−0.00920.1916

Disparities across groups

MetricValue95% CI low95% CI high
Demographic parity difference0.28850.19650.3746
Demographic parity ratio0.56320.46910.6818
Equal opportunity difference (TPR)0.28390.18120.3944
False-positive rate difference0.20530.07450.3328
Equalized odds difference0.28390.20190.3997
Predictive parity difference (PPV)0.05950.01470.1918
Accuracy difference0.06590.01210.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})],
})

Selection rates differ by up to 0.288, with an interval from 0.196 to 0.375. Among people who repaid, approval differs by up to 0.284.

The lowest selection rate is 0.56 of the highest. The four-fifths rule asks for at least 0.8. It's a screening rule from US employment guidance, and it isn't a legal or moral verdict.

03

Compute a ratio

Checkpoint

Check yourself

Group B's approval rate is 0.372, and group C's is 0.6605. What's the disparate impact ratio? Give three decimals.

Show the answer

Answer: 0.563214953271028

/ = , which is below the four-fifths threshold.

04

Can you have it all?

Predict

Predict first

In these data, groups repay at different rates. Can a model be equally calibrated across groups, and have equal true- and false-positive rates?

Yes, with a good enough modelNot when base rates differ, unless the model is perfect
Reveal

Not when base rates differ, unless it's perfect. Calibration means a score of 0.70.7 means 70% in every group. Together with different base rates, that forces different error rates. So you have to choose which fairness matters here.

05

Base rates drive it

Explore

The same arithmetic shows up in diagnostic testing. Keep the test's accuracy fixed, and change the prevalence.

HExplorable · What a positive test means

If a good test comes back positive, how likely is the disease?

A person tests positive. What is the chance they have the disease?

0.50
How sure?
0.950
0.950
0.020
  • Disease, test +: 19
  • No disease, test + (false positive): 49
  • Disease, test − (missed): 1
  • No disease, test −: 931

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Watch the positive predictive value move, while sensitivity and specificity don't. Now imagine two groups with different prevalence and one model. Which metric can match across them, and which can't?

06

What does a constraint cost?

Predict

Predict first

Group-specific thresholds can equalize selection rates. Compared with a single 0.5 threshold for everyone, how will the error rate change?

More errors than one shared thresholdFewer errors than one shared thresholdExactly the same
Reveal

Here it's lower: 0.303 against 0.318. That shared threshold wasn't the best for anyone. The fairer comparison is each group's own best thresholds, at 0.291. The difference, 0.012 per decision, is the price of fairnessPrice of fairnessHow much decision cost rises when you add a fairness constraint, compared with the best unconstrained thresholds. on this data.

07

Different constraints, different results

In the app
Fair decision thresholdsRecorded · Python and R agreeRecorded 2026-11-17 · 24 values compared
R

Under equalized odds, the best group thresholds give an expected errors of 0.312 per decision, against 0.291 when each group gets its own best threshold and 0.318 for one threshold of 0.5. Selection rates after: A 58.9%, B 56.0%, C 60.4%.

Expected errors per decision (fair)
0.3120
Each group's own best
0.2905
One threshold (0.5)
0.3176

Plots

Rates by group: one threshold vs fair thresholdsDo a model's decisions or error rates differ across groups, and by how much?
View data
groupMetricRate
ASelection (one threshold)0.5756
ASelection (fair)0.5887
ATPR (one threshold)0.7336
ATPR (fair)0.7419
BSelection (one threshold)0.3720
BSelection (fair)0.5600
BTPR (one threshold)0.5161
BTPR (fair)0.7419
CSelection (one threshold)0.6605
CSelection (fair)0.6038
CTPR (one threshold)0.8000
CTPR (fair)0.7419

Decision rule per group

groupnRuleSelection rateTPRFPRAccuracySelection at 0.5TPR at 0.5
A476randomized mixture of score ≥ 0.593 (weight 0.348), score ≥ 0.495 (weight 0.154), score ≥ 0.423 (weight 0.498)58.9%74.2%38.1%69.0%57.6%73.4%
B250score ≥ 0.3256.0%74.2%38.1%68.0%37.2%51.6%
C162randomized mixture of score ≥ 0.761 (weight 0.108), score ≥ 0.601 (weight 0.510), score ≥ 0.422 (weight 0.382)60.4%74.2%38.1%69.5%66.0%80.0%

Disparities before and after

MetricOne threshold (0.5)Fair thresholds
Demographic parity difference0.28850.0438
Equal opportunity difference (TPR)0.28391.110e-16
False-positive rate difference0.20535.551e-17
  • 12 of 900 rows were left out because a value was missing.
  • Cost per decision = (1 × false negatives + 1 × false positives) / n, expected over the randomization. Solved as a linear program (HiGHS).
  • Group-specific thresholds use the group attribute at decision time; check that this is lawful and acceptable for your decision before using them.
The exact R script · R R version 4.5.1 (2025-06-13)
# Fair decision thresholds (post-processing)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method fairness.threshold 1.0.1 · spec d3b93d3000eb5767
# 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_thresholds(): twin of codesplash.decide.fairness (exact hull search; HiGHS LP via the highs package)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/o2_credit.parquet", col_select = c("group", "repaid", "score")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("A", "B", "C"))  # stored level order
df[["repaid"]] <- factor(df[["repaid"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("group", "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", "repaid", "score"))  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
g_col <- "group"
y_col <- "repaid"
s_col <- "score"
constraint <- "equalized_odds"
tolerance <- 0
cost_fp <- 1
cost_fn <- 1
capacity <- NULL # NULL = no limit
baseline <- 0.5
group_levels <- levels(df[[g_col]])
group <- as.character(df[[g_col]])
score <- as.numeric(df[[s_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).", y_col))
}
n <- length(y)

# %% Thresholds
fair <- cs_fair_thresholds(group, y, score, group_levels, constraint, cost_fp = cost_fp, cost_fn = cost_fn, capacity = capacity, tolerance = tolerance)
free <- cs_fair_thresholds(group, y, score, group_levels, "none", cost_fp = cost_fp, cost_fn = cost_fn)
lv_all <- fair$levels
# A single shared threshold for comparison.
pred0 <- as.numeric(score >= baseline)
cost_baseline <- sum(cost_fn * (pred0 == 0 & y == 1) + cost_fp * (pred0 == 1 & y == 0)) / n
base <- cs_fair_group_metrics(group, pred0, y, NULL, lv_all, boot = 0)
after_disp <- cs_fair_disparities(lapply(stats::setNames(lv_all, lv_all), function(lv) {
  a <- fair$groups[[lv]]
  list(selection = a$selection, tpr = a$tpr, fpr = a$fpr, accuracy = a$accuracy, ppv = NaN)
}))

rule <- function(mixture) {
  pts <- Filter(function(p) p[2] > 0, mixture)
  if (length(pts) == 1) {
    t <- pts[[1]][1]
    return(if (is.infinite(t)) "nobody selected" else sprintf("score ≥ %s", format(t)))
  }
  if (length(pts) == 2) {
    o <- pts[order(-vapply(pts, function(p) p[1], numeric(1)))]
    t_hi <- o[[1]][1]
    t_lo <- o[[2]][1]
    w_lo <- o[[2]][2]
    if (is.infinite(t_hi)) return(sprintf("score ≥ %s selected with probability %.3f", format(t_lo), w_lo))
    return(sprintf("score ≥ %s; %s ≤ score < %s selected with probability %.3f", format(t_hi), format(t_lo), format(t_hi), w_lo))
  }
  paste("randomized mixture of", paste(vapply(pts, function(p) sprintf("score ≥ %s (weight %.3f)", format(p[1]), p[2]), ""), collapse = ", "))
}

# %% Result
labels <- c(demographic_parity = "demographic parity", equal_opportunity = "equal opportunity", equalized_odds = "equalized odds", none = "no constraint")
unit <- if (cost_fp == 1 && cost_fn == 1) "errors" else "cost"
summary <- paste0(
  "Under ", labels[[constraint]], if (tolerance > 0) sprintf(" (± %s)", format(tolerance)) else "",
  if (!is.null(capacity)) sprintf(" with at most %.0f%% selected", 100 * capacity) else "",
  sprintf(", the best group thresholds give an expected %s of %.3f per decision, against %.3f when each group gets its own best threshold and %.3f for one threshold of %s. Selection rates after: ",
          unit, fair$cost, free$cost, cost_baseline, format(baseline)),
  paste(vapply(lv_all, function(lv) sprintf("%s %.1f%%", lv, 100 * fair$groups[[lv]]$selection), ""), collapse = ", "), "."
)
values <- list(cost = fair$cost, cost_unconstrained = free$cost, cost_baseline = cost_baseline, price_of_fairness = fair$cost - free$cost,
               solver = fair$solver, n = n)
rows <- do.call(rbind, lapply(lv_all, function(lv) {
  a <- fair$groups[[lv]]
  b <- base$groups[[lv]]
  data.frame(group = lv, n = a$n, rule = rule(a$mixture), selection = a$selection, tpr = a$tpr, fpr = a$fpr, accuracy = a$accuracy,
             selection_before = b$selection, tpr_before = b$tpr)
}))
for (lv in lv_all) for (k in c("selection", "tpr", "fpr", "accuracy")) values[[sprintf("%s[%s]", k, lv)]] <- fair$groups[[lv]][[k]]
for (k in c("dp_diff", "eop_diff", "fpr_diff")) {
  values[[paste0(k, "_after")]] <- after_disp[[k]]
  values[[paste0(k, "_before")]] <- base$disparities[[k]]
}
metric_names <- c("Selection (one threshold)", "Selection (fair)", "TPR (one threshold)", "TPR (fair)")
cs_publish(list(
  method = "fairness.threshold",
  methodVersion = "1.0.1",
  title = "Fair decision thresholds",
  engine = cs_engine_info("stats", "highs", "codesplashr"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "cost", label = sprintf("Expected %s per decision (fair)", unit), value = fair$cost),
    list(key = "cost_unconstrained", label = "Each group's own best", value = free$cost),
    list(key = "cost_baseline", label = sprintf("One threshold (%s)", format(baseline)), value = cost_baseline)
  ),
  tables = list(
    list(key = "thresholds", title = "Decision rule per group",
         columns = list(list(key = "group", label = g_col, type = "string"), list(key = "n", label = "n", type = "integer"),
                        list(key = "rule", label = "Rule", type = "string"), list(key = "selection", label = "Selection rate", type = "percent"),
                        list(key = "tpr", label = "TPR", type = "percent"), list(key = "fpr", label = "FPR", type = "percent"),
                        list(key = "accuracy", label = "Accuracy", type = "percent"),
                        list(key = "selection_before", label = sprintf("Selection at %s", format(baseline)), type = "percent"),
                        list(key = "tpr_before", label = sprintf("TPR at %s", format(baseline)), type = "percent")),
         rows = rows),
    list(key = "disparities", title = "Disparities before and after",
         columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "before", label = sprintf("One threshold (%s)", format(baseline)), type = "number"),
                        list(key = "after", label = "Fair thresholds", type = "number")),
         rows = data.frame(metric = c("Demographic parity difference", "Equal opportunity difference (TPR)", "False-positive rate difference"),
                           before = c(base$disparities$dp_diff, base$disparities$eop_diff, base$disparities$fpr_diff),
                           after = c(after_disp$dp_diff, after_disp$eop_diff, after_disp$fpr_diff)))
  ),
  warnings = warnings,
  notes = list(
    paste0(sprintf("Cost per decision = (%s × false negatives + %s × false positives) / n, expected over the randomization. ", format(cost_fn), format(cost_fp)),
           if (fair$solver == "exact") "Solved exactly over the lower convex hull of each group's operating points." else "Solved as a linear program (HiGHS)."),
    "Group-specific thresholds use the group attribute at decision time; check that this is lawful and acceptable for your decision before using them."
  ),
  values = values,
  charts = list(cs_chart("rates", "group-metrics", sprintf("Rates by %s: one threshold vs fair thresholds", g_col), list(
    group = cs_col(g_col, rep(lv_all, each = 4), levels = lv_all),
    metric = cs_col("Metric", rep(metric_names, times = length(lv_all)), levels = metric_names),
    value = cs_col("Rate", unlist(lapply(lv_all, function(lv) c(base$groups[[lv]]$selection, fair$groups[[lv]]$selection,
                                                                   base$groups[[lv]]$tpr, fair$groups[[lv]]$tpr))))
  ), controls = list(reference = NA, band_low = 0, band_high = 0)))
))
Python

Under equalized odds, the best group thresholds give an expected errors of 0.312 per decision, against 0.291 when each group gets its own best threshold and 0.318 for one threshold of 0.5. Selection rates after: A 58.9%, B 56.0%, C 60.4%.

Expected errors per decision (fair)
0.3120
Each group's own best
0.2905
One threshold (0.5)
0.3176

To keep this page light, the plots are shown once, under the R tab.

Decision rule per group

groupnRuleSelection rateTPRFPRAccuracySelection at 0.5TPR at 0.5
A476randomized mixture of score ≥ 0.593 (weight 0.348), score ≥ 0.495 (weight 0.154), score ≥ 0.423 (weight 0.498)58.9%74.2%38.1%69.0%57.6%73.4%
B250score ≥ 0.3256.0%74.2%38.1%68.0%37.2%51.6%
C162randomized mixture of score ≥ 0.761 (weight 0.108), score ≥ 0.601 (weight 0.510), score ≥ 0.422 (weight 0.382)60.4%74.2%38.1%69.5%66.0%80.0%

Disparities before and after

MetricOne threshold (0.5)Fair thresholds
Demographic parity difference0.28850.0438
Equal opportunity difference (TPR)0.28391.110e-16
False-positive rate difference0.20535.551e-17
  • 12 of 900 rows were left out because a value was missing.
  • Cost per decision = (1 × false negatives + 1 × false positives) / n, expected over the randomization. Solved as a linear program (HiGHS).
  • Group-specific thresholds use the group attribute at decision time; check that this is lawful and acceptable for your decision before using them.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Fair decision thresholds (post-processing)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method fairness.threshold 1.0.1 · spec d3b93d3000eb5767
# 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_thresholds (exact hull search; HiGHS LP)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/o2_credit.parquet", columns=["group", "repaid", "score"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["A", "B", "C"])  # stored level order
df["repaid"] = pd.Categorical(df["repaid"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["group", "repaid", "score"])  # listwise deletion over the analysis columns
df["group"] = df["group"].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", "repaid", "score"])  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
g_col, y_col, s_col = "group", "repaid", "score"
constraint = "equalized_odds"
tolerance = 0
cost_fp, cost_fn = 1, 1
capacity = None  # None = no limit
baseline = 0.5
group_levels = [str(x) for x in df[g_col].cat.categories]
group = df[g_col].astype(str).to_numpy()
score = df[s_col].to_numpy(dtype=float)
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).")
n = len(y)

# %% Thresholds
fair = fairness.thresholds(group, y, score, group_levels, constraint, cost_fp=cost_fp, cost_fn=cost_fn, capacity=capacity, tolerance=tolerance)
free = fairness.thresholds(group, y, score, group_levels, "none", cost_fp=cost_fp, cost_fn=cost_fn)
levels = fair["levels"]
# A single shared threshold for comparison.
pred0 = (score >= baseline).astype(float)
cost_baseline = float((cost_fn * ((pred0 == 0) & (y == 1)) + cost_fp * ((pred0 == 1) & (y == 0))).sum() / n)
base = fairness.group_metrics(group, pred0, y, None, levels, boot=0)
after_disp = fairness.disparities({lv: {k: fair["groups"][lv][k] for k in ("selection", "tpr", "fpr", "accuracy")} | {"ppv": float("nan")} for lv in levels})


def rule(mixture):
    pts = [(t, w) for t, w in mixture if w > 0]
    if len(pts) == 1:
        t = pts[0][0]
        return "nobody selected" if np.isinf(t) else f"score ≥ {t:g}"
    if len(pts) == 2:
        (t_hi, _), (t_lo, w_lo) = sorted(pts, key=lambda p: -p[0])
        hi_text = "nobody for sure" if np.isinf(t_hi) else f"score ≥ {t_hi:g}"
        return f"{hi_text}; {t_lo:g} ≤ score < {t_hi:g} selected with probability {w_lo:.3f}" if not np.isinf(t_hi) else f"score ≥ {t_lo:g} selected with probability {w_lo:.3f}"
    return "randomized mixture of " + ", ".join(f"score ≥ {t:g} (weight {w:.3f})" for t, w in pts)


# %% Result
labels = {"demographic_parity": "demographic parity", "equal_opportunity": "equal opportunity", "equalized_odds": "equalized odds", "none": "no constraint"}
unit = "errors" if cost_fp == cost_fn == 1 else "cost"
summary = (
    f"Under {labels[constraint]}" + (f" (± {tolerance:g})" if tolerance else "") + (f" with at most {capacity:.0%} selected" if capacity is not None else "")
    + f", the best group thresholds give an expected {unit} of {fair['cost']:.3f} per decision, against {free['cost']:.3f} when each group gets its own best "
    f"threshold and {cost_baseline:.3f} for one threshold of {baseline:g}. Selection rates after: "
    + ", ".join(f"{lv} {fair['groups'][lv]['selection']:.1%}" for lv in levels) + "."
)
rows = []
values = {"cost": fair["cost"], "cost_unconstrained": free["cost"], "cost_baseline": cost_baseline, "price_of_fairness": fair["cost"] - free["cost"],
          "solver": fair["solver"], "n": n}
for lv in levels:
    a, b = fair["groups"][lv], base["groups"][lv]
    rows.append({"group": lv, "n": a["n"], "rule": rule(a["mixture"]), "selection": a["selection"], "tpr": a["tpr"], "fpr": a["fpr"],
                 "accuracy": a["accuracy"], "selection_before": b["selection"], "tpr_before": b["tpr"]})
    for k in ("selection", "tpr", "fpr", "accuracy"):
        values[f"{k}[{lv}]"] = a[k]
for k in ("dp_diff", "eop_diff", "fpr_diff"):
    values[f"{k}_after"] = after_disp[k]
    values[f"{k}_before"] = base["disparities"][k]
cs.publish({
    "method": "fairness.threshold",
    "methodVersion": "1.0.1",
    "title": "Fair decision thresholds",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "cost", "label": f"Expected {unit} per decision (fair)", "value": fair["cost"]},
        {"key": "cost_unconstrained", "label": "Each group's own best", "value": free["cost"]},
        {"key": "cost_baseline", "label": f"One threshold ({baseline:g})", "value": cost_baseline},
    ],
    "tables": [
        {"key": "thresholds", "title": "Decision rule per group",
         "columns": [{"key": "group", "label": g_col, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                     {"key": "rule", "label": "Rule", "type": "string"}, {"key": "selection", "label": "Selection rate", "type": "percent"},
                     {"key": "tpr", "label": "TPR", "type": "percent"}, {"key": "fpr", "label": "FPR", "type": "percent"},
                     {"key": "accuracy", "label": "Accuracy", "type": "percent"}, {"key": "selection_before", "label": f"Selection at {baseline:g}", "type": "percent"},
                     {"key": "tpr_before", "label": f"TPR at {baseline:g}", "type": "percent"}],
         "rows": rows},
        {"key": "disparities", "title": "Disparities before and after",
         "columns": [{"key": "metric", "label": "Metric", "type": "string"}, {"key": "before", "label": f"One threshold ({baseline:g})", "type": "number"},
                     {"key": "after", "label": "Fair thresholds", "type": "number"}],
         "rows": [{"metric": "Demographic parity difference", "before": base["disparities"]["dp_diff"], "after": after_disp["dp_diff"]},
                  {"metric": "Equal opportunity difference (TPR)", "before": base["disparities"]["eop_diff"], "after": after_disp["eop_diff"]},
                  {"metric": "False-positive rate difference", "before": base["disparities"]["fpr_diff"], "after": after_disp["fpr_diff"]}]},
    ],
    "warnings": warnings,
    "notes": [
        f"Cost per decision = ({cost_fn:g} × false negatives + {cost_fp:g} × false positives) / n, expected over the randomization. "
        + ("Solved exactly over the lower convex hull of each group's operating points." if fair["solver"] == "exact" else "Solved as a linear program (HiGHS)."),
        "Group-specific thresholds use the group attribute at decision time; check that this is lawful and acceptable for your decision before using them.",
    ],
    "values": values,
    "charts": [
        cs.chart("rates", "group-metrics", f"Rates by {g_col}: one threshold vs fair thresholds", {
            "group": cs.col(g_col, [lv for lv in levels for _ in range(4)], levels=levels),
            "metric": cs.col("Metric", [m for _ in levels for m in ("Selection (one threshold)", "Selection (fair)", "TPR (one threshold)", "TPR (fair)")],
                             levels=["Selection (one threshold)", "Selection (fair)", "TPR (one threshold)", "TPR (fair)"]),
            "value": cs.col("Rate", [v for lv in levels for v in (base["groups"][lv]["selection"], fair["groups"][lv]["selection"],
                                                                  base["groups"][lv]["tpr"], fair["groups"][lv]["tpr"])]),
        }, controls={"reference": None, "band_low": 0, "band_high": 0}),
    ],
})

Under equalized odds, the true- and false-positive rates match, and the price is 0.021. Selection rates still differ by 0.044, down from 0.288: satisfying one definition doesn't satisfy another.

With limited places, a capacity limit adds another constraint, and the price rises to 0.057. Post-processing like this may need the group at decision time, and using it can be restricted where you work.

08

Who decides?

Reflect

The app can show you the trade-off. It can't choose. In lending, is it worse to refuse someone who would repay, or to approve someone who can't? Who bears each error?

Choosing a definition is a decision for people, including those it affects. Write down what you chose, and why. Report the other metrics alongside it.

09

Check your understanding

Checkpoint

Check yourself

A hiring tool should not overlook qualified people in any group. Which measure fits that goal?

Show the answer

Answer: b

Equal opportunity compares true-positive rates: among people who are qualified, is each group selected equally often?

Check yourself

You remove the group column from the model's features. Does that make it fair?

Show the answer

Answer: b

Postcode, job history and many other features can carry the same information. You need the group column to audit, even if the model doesn't use it.

Check yourself

A small group shows a large gap in true-positive rate, with a wide interval. How do you read it?

Show the answer

Answer: b

Small groups vary a lot by chance, and they're often the ones most at risk. Report the interval, and don't treat a wide one as clearance.

10

Do the audit

In the app

This tour uses the same credit decisions in Decisions & fairness, comparing {{decision}} across {{group}}, from the rates by group through to fair thresholds.

Python
import pandas as pd

df = pd.read_csv("credit.csv").dropna(subset=["group", "approved", "repaid", "score"])
df[["approved", "repaid"]] = df[["approved", "repaid"]].astype(bool)
repaid = df[df["repaid"]]

selection = df.groupby("group")["approved"].mean()
tpr = repaid.groupby("group")["approved"].mean()

print("parity gap", round(selection.max() - selection.min(), 3))
print("ratio", round(selection.min() / selection.max(), 3))
print("opportunity gap", round(tpr.max() - tpr.min(), 3))
R
df <- read.csv("credit.csv", check.names = FALSE)
df$approved <- as.logical(df$approved)
df$repaid <- as.logical(df$repaid)
df <- na.omit(df[, c("group", "approved", "repaid", "score")])

selection <- tapply(df$approved, df$group, mean)
tpr <- with(df[df$repaid, ], tapply(approved, group, mean))

round(c(parity_gap = max(selection) - min(selection),
        ratio = min(selection) / max(selection),
        opportunity_gap = max(tpr) - min(tpr)), 3)
11

Recap

Recap
  • Selection rates and error rates are different questions, and both need intervals.
  • When base rates differ, fairness definitions conflict, so you have to choose.
  • Fair thresholds have a price, and it's worth measuring.
  • People decide which fairness matters, and they should say so.

Concepts in this lesson