TExcelTAD
Home › Machine Learning › Responsible ML

Responsible ML

Machine-learning models increasingly decide who gets a loan, which job applicants are interviewed, how patients are prioritised and what news people see. A model that is accurate on average can still be unfair to particular groups, impossible to explain, or harmful when the world changes. Responsible ML means checking for these problems deliberately — they don't show up in a single accuracy number.

Where bias comes from

Source Example
Historical bias past hiring decisions favoured one group; a model trained on them learns to repeat it
Representation bias a face data set with few dark-skinned faces → worse accuracy for those faces
Measurement bias using "arrests" as a proxy for "crime" when some areas are policed more heavily
Proxy features removing a protected attribute doesn't help if a postcode or first name encodes it
Feedback loops a model's decisions shape the data it will later be retrained on

Measuring outcomes per group

The first step is simply to break your metrics down by group. We simulate a loan data set where group B historically received fewer approvals for the same income, and train a model on those past decisions:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(0)
n = 2000
group = rng.choice(["A", "B"], size=n)
income = rng.normal(50, 12, n)
debt = rng.normal(20, 8, n)
# historical decisions: the same finances, but group B was approved less often
score = 0.12 * income - 0.15 * debt - 3.0 - 1.5 * (group == "B") + rng.normal(0, 0.5, n)
approved = (score > 0).astype(int)

df = pd.DataFrame({"income": income, "debt": debt, "is_b": (group == "B").astype(int),
                   "group": group, "approved": approved})
model = LogisticRegression(max_iter=1000).fit(df[["income", "debt", "is_b"]], df["approved"])
df["predicted"] = model.predict(df[["income", "debt", "is_b"]])

print(df.groupby("group")[["income", "approved", "predicted"]].mean().round(3))
print("coefficient for is_b:", model.coef_[0][2].round(2))
       income  approved  predicted
group
A      49.388     0.485      0.483
B      49.936     0.226      0.227
coefficient for is_b: -4.82

Both groups have the same income distribution, yet the model approves group B far less often — it faithfully learned the historical bias, as the large negative coefficient for is_b shows.

Dropping the attribute isn't enough

A common first idea is to remove the protected attribute. But if another feature is correlated with it — here a "district" code that mostly matches the group — the model rebuilds the bias through that proxy:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(0)
n = 2000
group = rng.choice(["A", "B"], size=n)
income = rng.normal(50, 12, n)
debt = rng.normal(20, 8, n)
score = 0.12 * income - 0.15 * debt - 3.0 - 1.5 * (group == "B") + rng.normal(0, 0.5, n)
approved = (score > 0).astype(int)

# district matches the group 85 % of the time
district_north = np.where(rng.random(n) < 0.85, group == "B", group == "A").astype(int)

for features, name in [(np.column_stack([income, debt]), "income, debt"),
                       (np.column_stack([income, debt, district_north]), "income, debt, district")]:
    pred = LogisticRegression(max_iter=1000).fit(features, approved).predict(features)
    rate_a, rate_b = pred[group == "A"].mean(), pred[group == "B"].mean()
    print(f"{name:24} approval A={rate_a:.3f}  B={rate_b:.3f}  ratio B/A={rate_b / rate_a:.2f}")
income, debt             approval A=0.324  B=0.340  ratio B/A=1.05
income, debt, district   approval A=0.409  B=0.279  ratio B/A=0.68

Without any group information, approval rates are almost equal. Add the innocent-looking district feature and a large part of the gap returns. The ratio of approval rates is called the disparate impact ratio; a common rule of thumb (the "four-fifths rule") flags ratios below 0.8.

Fairness metrics

There are several definitions of "fair", and they generally cannot all be satisfied at once:

Criterion Requires Compares
Demographic parity equal approval rates across groups `P(pred=1
Equal opportunity equal true-positive rates recall per group
Equalised odds equal TPR and FPR recall and false-alarm rate per group
Calibration a score of 0.7 means 70 % for every group predicted vs actual per group
python · try it yourself
import numpy as np
from sklearn.metrics import recall_score, confusion_matrix

# true outcomes and predictions for two groups of 10 applicants each
y_true = {"A": np.array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0]), "B": np.array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0])}
y_pred = {"A": np.array([1, 1, 1, 1, 0, 1, 0, 0, 0, 0]), "B": np.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0])}

for g in ["A", "B"]:
    tn, fp, fn, tp = confusion_matrix(y_true[g], y_pred[g]).ravel()
    print(f"group {g}: selection rate={y_pred[g].mean():.1f}  TPR={recall_score(y_true[g], y_pred[g]):.1f}  FPR={fp / (fp + tn):.1f}")
group A: selection rate=0.5  TPR=0.8  FPR=0.2
group B: selection rate=0.2  TPR=0.4  FPR=0.0

Here qualified applicants in group B are approved far less often (lower TPR) — a clear equal-opportunity violation. Libraries such as Fairlearn and AIF360 compute these metrics and offer mitigation methods.

Explainability

People affected by a decision deserve to know why. Prefer interpretable models (linear models, shallow trees) when stakes are high, and use explanation tools for complex ones: permutation importance (see Random Forests), partial dependence plots (sklearn.inspection.PartialDependenceDisplay), and per-prediction explanations such as SHAP values.

A practical checklist

  1. Purpose: should this decision be automated at all? Who could be harmed?
  2. Data: who is missing or under-represented? Which features could act as proxies?
  3. Evaluation: report metrics per group, not only overall.
  4. Transparency: document the model's intended use, data and limits (a "model card").
  5. Privacy: collect only what you need; models can memorise and leak training data.
  6. Human oversight: offer a way to contest decisions.
  7. Monitoring: data drifts after deployment — re-check performance and fairness regularly.

Go further: Governance: Model Cards, Audit Trails and Fairness Checks shows how these checks are documented and repeated once a model is in production.

Test yourself

Why might removing a protected attribute (like gender) from the features fail to remove bias?

  1. scikit-learn ignores removed columns
  2. Other features may act as proxies for it
  3. It always makes the model more biased
  4. Protected attributes can't be removed

Equal opportunity requires equal … across groups.

  1. accuracy
  2. true-positive rates (recall)
  3. group sizes
  4. feature means

A model approves 60 % of group A and 30 % of group B. What is the disparate impact ratio B/A?

  1. 0.3
  2. 0.5
  3. 2.0
  4. 0.9