DDecisions · fairness.assess
Fairness assessment of decisions across groups
Do a model's decisions treat groups differently — in who is selected and in the errors made?
Compares binary decisions (or scores at a threshold) across the groups of a sensitive attribute: selection rate, true- and false-positive rates, precision, accuracy and, with scores, calibration within groups. Reports demographic parity difference and ratio (the four-fifths rule), equal opportunity and equalized odds differences and predictive parity, with bootstrap intervals stratified by group from a shared seeded stream. Fairlearn's MetricFrame conventions.
A real result
Example “Decisions with scores”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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.
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.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Decisions with scoreso2_credit · group: group · outcome: repaid · prediction: approved · score: score
- Score threshold referenceo2_credit · group: age band · outcome: repaid · prediction: score
- Selection onlyo2_credit · group: group · prediction: approved
In the guides
Where it sits in the decision guides
- Constrained optimization (risk, fairness, cost) · DS & ML Decision Guide · Optimize / decide
What you need
- Group (sensitive attribute)categorical / boolean · 1 column · 2–50 levels
- The attribute whose groups are compared (e.g. sex, age band).
- Decision or scorenumeric / categorical / boolean · 1 column · 2–2 levels
- A yes/no decision, or a score in [0, 1] turned into decisions at the threshold.
- True outcomeboolean / categorical / numeric · 0–1 column · 2–2 levels
- Optional: the real outcome (needed for error rates). Numeric outcomes must be 0/1.
- Score (calibration)numeric · 0–1 column
- Optional: predicted probabilities for calibration within groups when the decision is yes/no.
Choices you make
options
- Decision threshold (numeric scores)default 0.5
A numeric score at or above the threshold counts as a positive decision.
- Positive decisiondefault —
The decision level counted as selected; default: the second level (true for yes/no).
- Positive outcomedefault —
The outcome level counted as positive; default: the second level.
- Reference groupdefault —
Optional: differences and ratios are also shown against this group.
statistics
- Bootstrap resamplesdefault 1000
Resampled within each group (0 = no intervals).
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
What it reports
- dp_diff
- Every group is selected at the same rate, whatever their outcomes.
- dp_ratio
- Every group is selected at the same rate, whatever their outcomes.
- n
- How many independent units the analysis used; it sets precision and power.
- selection
- Every group is selected at the same rate, whatever their outcomes.
Per group, level or term: dp_diff_ci_high, dp_diff_ci_low
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses numpy, pandas, codesplash; R uses stats, nanoparquet, codesplashr.
The exact script CodeSplash ran for example “Decisions with scores” · 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})],
})
The exact script CodeSplash ran for example “Decisions with scores” · 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)))
))
Sources
- Hardt, M., Price, E., & Srebro, N. (2016). Equality of opportunity in supervised learning. NeurIPS, 3315–3323.
- Barocas, S., Hardt, M., & Narayanan, A. (2023). Fairness and machine learning: Limitations and opportunities. MIT Press.
- Bird, S., et al. (2020). Fairlearn: A toolkit for assessing and improving fairness in AI. Microsoft Technical Report MSR-TR-2020-32.
- U.S. EEOC (1978). Uniform guidelines on employee selection procedures (four-fifths rule), 29 C.F.R. § 1607.4(D).
From the CodeSplash method registry · fairness.assess v1.0.1.