ML Engineering
ML Ethics — Building Fair, Transparent, and Accountable Systems
In this module, you'll explore the ethical considerations in machine learning, including fairness, bias detection, and responsible AI practices. Learn how to build systems that are transparent, accountable, and compliant with regulations.
- Fairness and Bias Detection — Understanding and mitigating algorithmic bias
- Interpretability and Transparency — Making model decisions explainable
- Responsible AI Practices — Ensuring ethical deployment and compliance
"Ethics is not an afterthought — it's a core requirement for trustworthy AI."
ML Ethics — Responsible AI
AI systems must be fair, transparent, and accountable. Ethics is not optional — it's a legal requirement in many jurisdictions.
Fairness
- Demographic parity: Equal positive rates across groups
- Equal opportunity: Equal true positive rates
- Equalized odds: Equal TPR and FPR
- Individual fairness: Similar individuals treated similarly
Types of Algorithmic Bias
Fairness Metrics
Fairness Metrics Comparison
Measuring Fairness on Scored Predictions
Fairness is not a property of an algorithm in the abstract — it is measured on the scores a deployed model hands back for real people. Work through one concrete example before touching any formula. A bank scores 1,000 applications: 500 arrive from region group A and 500 from region group B. The model approves 300 applicants in group A and 180 in group B. Approval rates are therefore 60% and 36%, a demographic parity difference of 0.24 and a parity ratio of 0.60. Most review policies treat a gap above 0.10 or a ratio below 0.80 as a trigger for human sign-off.
Conditioning on ground truth changes the verdict. Of those 1,000 applicants, 350 in group A and 250 in group B were actually creditworthy. The model approved 270 creditworthy applicants in group A (true positive rate 77%) and 150 in group B (true positive rate 60%), an equal opportunity difference of 0.17. Among applicants who should have been declined, it approved 30 of 150 in group A (false positive rate 20%) and 30 of 250 in group B (false positive rate 12%). One prediction table now yields three verdicts: mild unfairness on equal opportunity, strong unfairness on parity, mild unfairness on equalized odds. Which number reaches the board deck is a product decision, not a neutral measurement.
| Metric | Equalizes | Review trigger | What it cannot see |
|---|---|---|---|
| Demographic parity | Positive rate per group | Difference above 0.10 | Whether predictions are correct |
| Equal opportunity | True positive rate | Difference above 0.05 | False alarm burden |
| Equalized odds | TPR and FPR together | Either gap above 0.05 | Calibration inside each group |
| Predictive parity | Precision per group | Difference above 0.05 | Who absorbs the false negatives |
| Individual fairness | Distance between similar people | Monotonicity violations | Group-level disparities |
The audit query below is the artifact an auditor actually asks for: rates per group, computed from the stored decisions rather than from a dashboard screenshot.
-- Fairness audit: approval and error rates by protected group
WITH scored AS (
SELECT applicant_id,
region_group,
approved,
actually_creditworthy
FROM loan_decisions
WHERE decision_date >= '2025-01-01'
)
SELECT region_group,
COUNT(*) AS n,
ROUND(AVG(approved), 3) AS approval_rate,
ROUND(AVG(actually_creditworthy), 3) AS base_rate,
ROUND(AVG(CASE WHEN actually_creditworthy = 1 THEN approved END), 3) AS tpr,
ROUND(AVG(CASE WHEN actually_creditworthy = 0 THEN approved END), 3) AS fpr,
ROUND(AVG(CASE WHEN approved = 1 THEN actually_creditworthy END), 3) AS precision
FROM scored
GROUP BY region_group
ORDER BY region_group;
Run that query every week on the scored population, not just at launch. Drift in the inputs moves these rates even when the model weights are frozen, and a fairness regression that shows up three quarters later is far more expensive to explain than one caught in the first week.
Closing a Fairness Gap Without Retraining
Post-processing is the cheapest intervention: adjust the decision threshold per group so error rates line up, leaving the model untouched. The function below finds, for each group, the highest-recall threshold whose false positive rate stays inside a ceiling you set.
import numpy as np
from sklearn.metrics import roc_curve
def group_thresholds(y_true, y_score, group, max_fpr=0.10):
"""Pick one decision threshold per group so every group respects max_fpr."""
thresholds = {}
for g in np.unique(group):
mask = group == g
fpr, tpr, thr = roc_curve(y_true[mask], y_score[mask])
ok = np.flatnonzero(fpr <= max_fpr)
best = ok[np.argmax(tpr[ok])]
thresholds[g] = float(thr[best])
return thresholds
thr = group_thresholds(y_true, y_score, group_col, max_fpr=0.10)
preds = np.where(y_score >= group_col.map(thr).to_numpy(), 1, 0)
print({g: round(t, 3) for g, t in thr.items()})
Three practical cautions. First, per-group thresholds are illegal in some jurisdictions for credit and hiring, so confirm the policy before shipping them. Second, they shift precision as well as parity — re-check overall approval volume, because a bank that suddenly approves 12% fewer loans has a business problem even if its fairness numbers look clean. Third, document the threshold choice in the model card; a reviewer who finds undocumented per-group logic will treat the whole system as untrustworthy.
Why Perfect Fairness Is Impossible
Chouldechova (2017) and Kleinberg et al. (2016) proved that when base rates differ across groups, no classifier can be simultaneously calibrated, have equal false positive rates, and have equal false negative rates — unless the model is perfect or the groups have identical base rates. In the worked example the base rates are 70% for group A and 50% for group B, so the three properties trade off by construction.
The practical consequence is a deliberate choice rather than a tuning exercise. If the harm falls on people wrongly rejected — a qualified candidate never screened, a creditworthy applicant declined — optimize equal opportunity. If the harm falls on people wrongly accepted into a risky path, equal false positive rates matter more. If the decision must be justifiable per person, calibration within each group is the defensible property. Record which property you picked, which you gave up, and who signed off, because that trade-off memo is the evidence that ethics was handled deliberately.
Privacy, Data Minimization and Consent
Model ethics extends to the data inside the model. Differential privacy gives a formal guarantee: training with clipped gradients of norm C and calibrated Gaussian noise bounds how much any single record can change the output, summarized by a privacy budget epsilon. A budget of epsilon at or below 8 is a common production target for aggregate model release; budgets in the hundreds mean the guarantee is decorative. Membership inference attacks test the same property empirically — an attacker who can tell whether a record was in the training set has leaked something, and unmitigated deep networks often fail this test.
Beyond the budget, the boring controls decide outcomes. Collect only the fields the model actually uses, since a retained but unused address is pure liability. Check consent covers model training, not just storage. Budget for deletion: removing one person from a fine-tuned model usually means retraining, so keep the data provenance needed to replay the training run. Federated learning keeps raw records on-device and ships only weight updates, which reduces exposure but does not remove it — updates still need clipping and noise before they leave the phone.
Documentation That Survives an Audit
Regulators read documents, not architectures. Three artifacts cover most obligations. A model card states intended use, out-of-scope use, evaluated populations, and the fairness metrics with their before and after numbers. A datasheet for the dataset records provenance, collection window, consent basis, and known gaps. An evaluation log ties each model version to the data snapshot and thresholds that produced it, so any prediction can be traced back to a specific build.
These map directly onto the EU AI Act risk tiers. Prohibited practices such as social scoring carry fines up to 7% of global annual turnover or 35 million euros, whichever is higher. High-risk systems — credit scoring, employment screening, essential services — require risk management, technical documentation, logging, human oversight, and conformity assessment before market placement. Limited-risk tools need transparency disclosure, and minimal-risk tools carry essentially no obligations. The NIST AI RMF organizes the same work into four functions: Govern, Map, Measure, Manage. Pick one framework and follow it consistently; half-adopting two is what produces audit failures.
Ethical AI Framework
Ethical AI Framework Diagram
Key Takeaways
What to Learn Next
-> Model Interpretability — SHAP, LIME and Explainable AI Learn about model interpretability — shap, lime and explainable ai.
-> Causal Inference — Moving Beyond Correlation Learn about causal inference — moving beyond correlation.
-> A/B Testing for ML — Experiment Design and Statistical Rigor Learn about a/b testing for ml — experiment design and statistical rigor.
-> ML System Design — Architecture and Production Patterns Learn about ml system design — architecture and production patterns.
-> Model Deployment — APIs, Containers and Production ML Learn about model deployment — apis, containers and production ml.
-> Model Evaluation — Metrics, Cross-Validation and Selection Learn about model evaluation — metrics, cross-validation and selection.