Phase 1: When AI Harms — Real-World Cases & the Responsible AI Landscape · 35 min · Python
The Concept
The three key tradeoffs
Tradeoff 1: Fairness vs. Accuracy
Chouldechova's theorem (2017) proves that when base rates differ across groups — and they always do in real data — you cannot simultaneously satisfy equalized odds and predictive parity. It's mathematically impossible. This means:
- If you optimize for equalized odds (equal false positive and false negative rates across groups), you will have different positive predictive values across groups
- If you optimize for predictive parity (equal positive predictive values across groups), you will have different error rates across groups
- There is no "fair" model — only a model that is fair by a chosen definition
The COMPAS case from Lesson 1 was exactly this debate. ProPublica measured equalized odds and found bias. Northpointe measured predictive parity and found fairness. Both were right.
Tradeoff 2: Privacy vs. Utility
Differential privacy adds noise to model training to prevent information leakage. The privacy budget ε (epsilon) controls the tradeoff:
- ε = 0.8: strong privacy, significant accuracy drop (~3-5% on MNIST)
- ε = 3.2: moderate privacy, small accuracy drop (~1-2%)
- ε = 12: weak privacy, minimal accuracy drop
There is no "correct" ε — it depends on the sensitivity of the data and the regulatory requirements. A medical diagnosis model needs stronger privacy than a movie recommender.
Tradeoff 3: Explainability vs. Performance
A linear regression is fully explainable but may underperform. A gradient-boosted ensemble may perform better but is a black box without SHAP/LIME. Deep neural networks may perform best but are the hardest to explain.
The EU AI Act creates a regulatory floor here: Article 13 requires transparency for high-risk systems, which means you must provide explainability regardless of the performance cost. The question is not "should we explain?" but "how much explanation is sufficient for this risk tier?"
You're building a credit scoring model. The business wants maximum accuracy. Legal says you need to satisfy equalized odds across racial groups (fairness). Privacy wants differential privacy with ε ≤ 2. Explainability requires SHAP values for every decision. What happens to accuracy when you apply all three constraints?
Every constraint has a cost. Fairness constraints (equalized odds) reduce the model's ability to optimize purely for accuracy by requiring equal error rates across groups. Differential privacy adds noise that degrades the signal. Explainability may force you away from the highest-performing model architecture. The combined effect is cumulative — you lose a few points to fairness, a few to privacy, a few to explainability. The result may still be good enough for the use case, but you need to measure it, not assume it. This is why the audit toolkit you're building in this course runs all three measurements and reports the combined tradeoff — so the decision is data-driven, not wishful.
Building a trustworthiness scoring rubric
Let's build a tool that evaluates an AI system against all 7 characteristics and produces a scored rubric.
"""
lesson_00_03_trustworthiness_rubric.py
Evaluates an AI system against NIST's 7 trustworthiness characteristics.
"""
from datetime import datetime
CHARACTERISTICS = {
"safe": {
"name": "Safe",
"description": "System does not cause physical, psychological, or societal harm",
"evaluation_criteria": [
"Failure mode analysis documented for all high-impact outputs",
"Harm severity assessment completed for each failure mode",
"Kill switch or human override available for high-stakes decisions",
"Incident response playbook tested with at least one simulation",
],
},
"secure": {
"name": "Secure",
"description": "System resists adversarial attacks and protects against unauthorized access",
"evaluation_criteria": [
"Adversarial robustness testing completed (OWASP LLM Top 10 if applicable)",
"Input validation and sanitization implemented",
"Access controls and authentication for model endpoints",
"Penetration testing completed within last 12 months",
],
},
"explainable": {
"name": "Explainable",
"description": "System outputs can be understood by relevant stakeholders",
"evaluation_criteria": [
"Global feature importance available (SHAP or equivalent)",
"Local explanations available for individual predictions (SHAP/LIME)",
"Model card published and accessible to stakeholders",
"Explanation quality validated with target user group",
],
},
"privacy_enhanced": {
"name": "Privacy-Enhanced",
"description": "System protects training data and user information from leakage",
"evaluation_criteria": [
"Privacy impact assessment completed (GDPR Art. 35 / EU AI Act Art. 10)",
"Membership inference attack resistance tested",
"PII detection and masking implemented for inputs/outputs",
"Data minimization principles applied to training data",
],
},
"valid_reliable": {
"name": "Valid & Reliable",
"description": "System performs as intended across its operational domain",
"evaluation_criteria": [
"Accuracy measured on held-out test set with confidence intervals",
"Robustness tested against out-of-distribution inputs",
"Performance drift monitoring implemented",
"Error rates documented per subgroup and use case",
],
},
"fair": {
"name": "Fair",
"description": "System produces equitable outcomes across demographic groups",
"evaluation_criteria": [
"Bias audit completed with Fairlearn or AIF360",
"Disparate impact ratio ≥ 0.80 (EEOC 80% rule)",
"Equalized odds measured across all protected groups",
"Fairness metric conflicts documented and resolved with justification",
],
},
"accountable": {
"name": "Accountable",
"description": "System has clear ownership, audit trails, and governance",
"evaluation_criteria": [
"Model owner identified and documented",
"Audit trail logging implemented for all decisions",
"Risk register maintained with current status",
"Governance review cycle defined (at least annual)",
],
},
}
def score_system(system_description, scores):
"""
Score an AI system against all 7 trustworthiness characteristics.
Args:
system_description: Dict with system metadata (name, use_case, risk_tier)
scores: Dict mapping characteristic_id to list of booleans (one per criterion)
Returns:
Dict with scoring results and overall assessment
"""
results = []
for char_id, char_data in CHARACTERISTICS.items():
criteria_scores = scores.get(char_id, [False] * len(char_data["evaluation_criteria"]))
met_count = sum(criteria_scores)
total = len(char_data["evaluation_criteria"])
percentage = (met_count / total) * 100
if percentage >= 75:
rating = "Strong"
elif percentage >= 50:
rating = "Adequate"
elif percentage >= 25:
rating = "Weak"
else:
rating = "Critical Gap"
results.append({
"characteristic": char_data["name"],
"description": char_data["description"],
"criteria_met": f"{met_count}/{total}",
"percentage": round(percentage, 1),
"rating": rating,
"unmet_criteria": [
crit for crit, met in zip(char_data["evaluation_criteria"], criteria_scores) if not met
],
})
overall = sum(r["percentage"] for r in results) / len(results)
weakest = min(results, key=lambda r: r["percentage"])
strongest = max(results, key=lambda r: r["percentage"])
return {
"system": system_description,
"results": results,
"overall_score": round(overall, 1),
"weakest_characteristic": weakest["characteristic"],
"strongest_characteristic": strongest["characteristic"],
"assessment_date": datetime.now().isoformat(),
}
def generate_report(assessment):
"""Generate a Markdown trustworthiness assessment report."""
lines = []
lines.append("# Trustworthiness Assessment Report")
lines.append(f"\n**System:** {assessment['system'].get('name', 'Unknown')}")
lines.append(f"**Use case:** {assessment['system'].get('use_case', 'Not specified')}")
lines.append(f"**Risk tier:** {assessment['system'].get('risk_tier', 'Not classified')}")
lines.append(f"**Assessment date:** {assessment['assessment_date']}")
lines.append(f"**Overall score:** {assessment['overall_score']}/100\n")
lines.append("## Characteristic Scores\n")
lines.append("| Characteristic | Criteria Met | Score | Rating |")
lines.append("|---|---|---|---|")
for r in assessment["results"]:
lines.append(f"| {r['characteristic']} | {r['criteria_met']} | {r['percentage']}% | {r['rating']} |")
lines.append(f"\n**Strongest:** {assessment['strongest_characteristic']}")
lines.append(f"**Weakest:** {assessment['weakest_characteristic']}\n")
lines.append("## Gaps to Address\n")
for r in assessment["results"]:
if r["unmet_criteria"]:
lines.append(f"### {r['characteristic']} ({r['rating']})\n")
for crit in r["unmet_criteria"]:
lines.append(f"- [ ] {crit}")
lines.append("")
lines.append("## Tradeoff Analysis")
lines.append("\nDocument any tradeoffs made between characteristics:")
lines.append("- Fairness vs. Accuracy: [describe tradeoff and justification]")
lines.append("- Privacy vs. Utility: [describe tradeoff and justification]")
lines.append("- Explainability vs. Performance: [describe tradeoff and justification]")
return "\n".join(lines)
if __name__ == "__main__":
# Example: Score a loan approval system
system = {
"name": "LoanApproval-v2.1",
"use_case": "Automated loan approval for consumer credit",
"risk_tier": "High (EU AI Act Annex III — essential services)",
}
# Scores: True = criterion met, False = not met
example_scores = {
"safe": [True, True, True, False],
"secure": [True, True, True, False],
"explainable": [True, True, False, False],
"privacy_enhanced": [True, False, True, True],
"valid_reliable": [True, True, True, True],
"fair": [True, False, True, True],
"accountable": [True, True, False, True],
}
assessment = score_system(system, example_scores)
report = generate_report(assessment)
with open("trustworthiness_assessment.md", "w") as f:
f.write(report)
print(f"Overall score: {assessment['overall_score']}/100")
print(f"Strongest: {assessment['strongest_characteristic']}")
print(f"Weakest: {assessment['weakest_characteristic']}")
print("Report saved to trustworthiness_assessment.md")