Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟣 ML + AI  ·  Lesson 37

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.

PrincipleQuestion to ask
FairnessDoes the system work equally well for different groups (gender, region, language)?
PrivacyDo we collect only needed data, with consent, and keep it safe?
TransparencyCan we explain why the system made a decision?
Safety & reliabilityWhat happens when it is wrong? Is a human checking important decisions?
AccountabilityWho 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.

Python – learned_bias.py
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))
approved predicted area city 0.60 0.61 village 0.38 0.37 weight on area_village: -1.57

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.

Python – fairness_metrics.py
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)
biased rule selection rate city 0.61 | village 0.10 | gap 0.51 top students OK city 1.00 | village 0.60 | gap 0.40 same cut-off for all selection rate city 0.30 | village 0.32 | gap -0.01 top students OK city 1.00 | village 1.00 | gap 0.00
MetricMeaning
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 accuracyIs the model equally correct for every group?
📝 Fairness needs human judgement

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.

Python – mask_personal_data.py
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"))
Parent Ramesh Kumar ([PHONE], [EMAIL]) says Aadhaar [AADHAAR] was submitted. Address: 14 Johari Bazaar, Jaipur [PIN]. Ramesh Kumar → P-bfaa65d6

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

Python – explain_model.py
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())
test accuracy: 0.944 features the model relies on most: worst area 0.0098 worst concave points 0.0091 mean concave points 0.0070 mean concavity 0.0070 worst texture 0.0063

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

RiskExampleWhat you can do
DeepfakesFake video of a leader or a fake voice call asking for moneyVerify through a second channel; report to cybercrime.gov.in or call 1930
MisinformationConfident but false answers or fake citationsCheck official sources before sharing
CopyrightGenerated text/images close to someone’s workUse original content; credit sources; follow licences
Academic honestySubmitting AI-written homework as your ownFollow your school’s rules; use AI to learn, not to copy
Over-relianceAccepting AI medical or legal advice without a professionalUse AI for understanding, professionals for decisions

A responsible-AI checklist for your project

  1. Purpose: what decision does it support, and who could be harmed if it is wrong?
  2. Data: where did it come from, do we have consent, which groups are missing or small?
  3. Testing: accuracy per group, fairness gaps, edge cases, adversarial inputs.
  4. Privacy: minimum data, masking, secure storage, deletion plan.
  5. Human oversight: who reviews important or uncertain cases?
  6. Transparency: tell users when AI is involved and how to appeal.
  7. Monitoring: re-check performance after launch, because data changes.

Practice tasks

  1. In learned_bias.py, drop the area column and retrain. Does the gap disappear? Why or why not?
  2. Add a pattern for PAN numbers (ABCDE1234F) to the masking function.
  3. Pick an AI app you use and fill the 7-point checklist for it.
  4. 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.

Frequently Asked Questions

Is there an AI law in India?
India does not yet have a single AI-specific law. Personal data is covered by the Digital Personal Data Protection Act 2023, and IT Act rules and advisories apply to online platforms and deepfakes. Rules are evolving, so check the latest official guidance for real projects.
Can AI ever be completely unbiased?
Probably not, because data and goals are chosen by people. The realistic aim is to measure bias, reduce it where it causes harm, be open about limits and let people challenge decisions.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicAI Project Ideas for Students Your progress: 37 / 66 (56%) · Lesson 38 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free