AI Ethics and Responsible AI
In this lesson: Key AI ethics issues — bias, privacy, transparency, misuse — and how to build responsible AI. Simple explanations.
What is responsible AI?
AI systems now help decide who gets a loan, which CV is shortlisted, what news we see and even which students need extra support. Responsible AI means building and using these systems so they are fair, safe, private, transparent and accountable. It is not only a topic for philosophers – most problems start with ordinary technical choices about data and testing.
| Principle | Question to ask |
|---|---|
| Fairness | Does the system work equally well for different groups (gender, region, language)? |
| Privacy | Do we collect only needed data, with consent, and keep it safe? |
| Transparency | Can we explain why the system made a decision? |
| Safety & reliability | What happens when it is wrong? Is a human checking important decisions? |
| Accountability | Who is responsible and how can people complain or appeal? |
Bias: how a model learns unfairness
A model learns patterns from past data. If past decisions were unfair, or one group is under-represented, the model repeats the unfairness at scale. Below is a synthetic scholarship dataset (made up for teaching) in which past committees favoured city applicants even when marks were similar.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(0)
n = 2000
area = rng.choice(["city", "village"], size=n, p=[0.6, 0.4])
marks = rng.normal(75, 10, n).clip(35, 100)
income = rng.normal(4, 1.5, n).clip(0.5, 12) # lakh per year
# historical (biased) decisions: same marks, but villages approved less often
logit = 0.25 * (marks - 75) - 0.4 * (income - 4) + np.where(area == "city", 0.8, -0.8)
approved = rng.random(n) < 1 / (1 + np.exp(-logit))
df = pd.DataFrame({"area": area, "marks": marks.round(), "income": income.round(1), "approved": approved})
X = pd.get_dummies(df[["marks", "income", "area"]], drop_first=True) # area_village column
model = LogisticRegression(max_iter=1000).fit(X, df["approved"])
df["predicted"] = model.predict(X)
rates = df.groupby("area")[["approved", "predicted"]].mean().round(2)
print(rates)
print("weight on area_village:", round(model.coef_[0][list(X.columns).index("area_village")], 2))The model learned a strong negative weight for “village” and approves far fewer village applicants – it copied the old committees’ bias.
Measuring fairness
Simply deleting the area column often does not fix bias, because other columns (school name, PIN code, language) can act as hidden proxies. First measure how outcomes differ between groups, for equally qualified people.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 2000
area = rng.choice(["city", "village"], size=n, p=[0.6, 0.4])
marks = rng.normal(75, 10, n).clip(35, 100)
def report(name, predicted):
df = pd.DataFrame({"area": area, "top": marks >= 85, "pred": predicted})
sel = df.groupby("area")["pred"].mean()
tpr = df[df["top"]].groupby("area")["pred"].mean() # among strong students
print(f"{name}")
print(f" selection rate city {sel['city']:.2f} | village {sel['village']:.2f} | gap {sel['city'] - sel['village']:.2f}")
print(f" top students OK city {tpr['city']:.2f} | village {tpr['village']:.2f} | gap {tpr['city'] - tpr['village']:.2f}")
biased = (marks + np.where(area == "city", 8, -8)) >= 80 # a rule that adds points for city
fair = marks >= 80 # the same cut-off for everyone
report("biased rule", biased)
report("same cut-off for all", fair)| Metric | Meaning |
|---|---|
| Selection-rate gap (demographic parity) | Difference in the share of each group selected |
| True-positive-rate gap (equal opportunity) | Among people who deserve “yes”, how often each group gets it |
| Per-group accuracy | Is the model equally correct for every group? |
Different fairness metrics can conflict, and the right choice depends on the situation and the law. Metrics show the problem; people with domain knowledge and the affected community must decide the remedy.
Privacy: collect less, protect more
India’s Digital Personal Data Protection Act, 2023 requires a lawful purpose and consent for personal data, and gives people rights over their data. Good engineering habits: collect only what you need, mask or remove identifiers before analysis or sending text to AI services, and delete data you no longer need.
import hashlib
import re
note = ("Parent Ramesh Kumar (9829012345, ramesh.k@gmail.com) says Aadhaar 2345 6789 0123 "
"was submitted. Address: 14 Johari Bazaar, Jaipur 302003.")
PATTERNS = {
"PHONE": r"\b[6-9]\d{9}\b",
"EMAIL": r"\b[\w.+-]+@[\w-]+\.[\w.]+\b",
"AADHAAR": r"\b\d{4}\s?\d{4}\s?\d{4}\b",
"PIN": r"\b[1-9]\d{5}\b",
}
def mask(text):
for label, pattern in PATTERNS.items():
text = re.sub(pattern, f"[{label}]", text)
return text
def pseudonym(name, salt="school-2026"):
return "P-" + hashlib.sha256((salt + name).encode()).hexdigest()[:8]
print(mask(note))
print("Ramesh Kumar →", pseudonym("Ramesh Kumar"))Regex masking catches common formats but not everything (names, house numbers). For sensitive projects combine it with access control and human review – and never put real Aadhaar numbers in test files.
Transparency: explain decisions
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
data = load_breast_cancer(as_frame=True)
X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, random_state=0, stratify=data.target)
model = RandomForestClassifier(n_estimators=200, random_state=0).fit(X_tr, y_tr)
imp = permutation_importance(model, X_te, y_te, n_repeats=10, random_state=0)
top = pd.Series(imp.importances_mean, index=X_te.columns).sort_values(ascending=False).head(5)
print("test accuracy:", round(model.score(X_te, y_te), 3))
print("features the model relies on most:")
print(top.round(4).to_string())Permutation importance shuffles one column at a time and measures how much accuracy drops. If a model relied mostly on something irrelevant (an ID number, a hospital name), that is a warning sign. Tools like SHAP give per-person explanations.
Generative AI risks
| Risk | Example | What you can do |
|---|---|---|
| Deepfakes | Fake video of a leader or a fake voice call asking for money | Verify through a second channel; report to cybercrime.gov.in or call 1930 |
| Misinformation | Confident but false answers or fake citations | Check official sources before sharing |
| Copyright | Generated text/images close to someone’s work | Use original content; credit sources; follow licences |
| Academic honesty | Submitting AI-written homework as your own | Follow your school’s rules; use AI to learn, not to copy |
| Over-reliance | Accepting AI medical or legal advice without a professional | Use AI for understanding, professionals for decisions |
A responsible-AI checklist for your project
- Purpose: what decision does it support, and who could be harmed if it is wrong?
- Data: where did it come from, do we have consent, which groups are missing or small?
- Testing: accuracy per group, fairness gaps, edge cases, adversarial inputs.
- Privacy: minimum data, masking, secure storage, deletion plan.
- Human oversight: who reviews important or uncertain cases?
- Transparency: tell users when AI is involved and how to appeal.
- Monitoring: re-check performance after launch, because data changes.
Practice tasks
- In
learned_bias.py, drop the area column and retrain. Does the gap disappear? Why or why not? - Add a pattern for PAN numbers (
ABCDE1234F) to the masking function. - Pick an AI app you use and fill the 7-point checklist for it.
- Write a one-page “model card” for any model in this course: purpose, data, accuracy, limits.
Summary
- Models copy patterns – including unfair ones – from past data.
- Measure fairness per group; removing one column is rarely enough.
- Collect less personal data, mask identifiers and follow the DPDP Act.
- Explain models (permutation importance, SHAP) and keep humans in charge of important decisions.
- Verify AI output, label AI content and report deepfake fraud.
