Privacy, Consent, Licensing, Retention and Access
Every source in this section can contain information about people, and most data comes with conditions attached. Getting these wrong is not a technical bug that a retrain fixes: it can mean fines, lawsuits, a model that must be withdrawn, and real harm to the people in the data. This lesson gives the working vocabulary and the habits that keep an ML project on the right side of the rules. It is not legal advice: laws differ by country and change, and real projects involve a data protection officer or lawyer.
Personal data
Personal data is any information about an identifiable person. That is much broader than names:
| Kind | Examples |
|---|---|
| direct identifiers | name, email, phone number, national ID, account number, face photo, voice recording |
| quasi-identifiers | birth date, postcode, gender, job title, rare diagnosis: harmless alone, identifying in combination |
| sensitive (special) categories | health, genetics, biometrics, religion, ethnicity, sexual orientation, political views, criminal records; stricter rules apply |
| indirect and derived | device ids, IP addresses, location traces, a model's inferences about a person |
The classic warning: a large share of people in the United States can be uniquely identified by just their 5-digit ZIP code, gender and full date of birth (Latanya Sweeney's study of the 1990 census). Removing names is not anonymisation.
The principles most laws share
The EU's GDPR, Vietnam's personal data protection rules (Decree 13/2023, followed by a Personal Data Protection Law from 2026), Brazil's LGPD, California's CCPA and sector laws such as HIPAA for US health data differ in detail, but share a core that you can design for:
| Principle | What it means for an ML dataset |
|---|---|
| lawful basis | you need a legal reason to process the data: consent, a contract, a legal obligation, legitimate interest… Record which one |
| purpose limitation | data collected to deliver orders cannot simply be reused to train a credit-scoring model |
| data minimisation | collect and keep only the fields the purpose needs; drop the rest early |
| accuracy | keep data correct; let people fix it |
| storage limitation (retention) | delete or anonymise data when it is no longer needed for its purpose |
| security and access control | protect the data; only people who need it can see it |
| rights of the person | access, correction, deletion, objection, and explanations of automated decisions in some cases |
Consent
When consent is the basis, it must be informed (the person knows what the data is used for), specific (to a purpose, not "any use"), freely given (not a condition for an unrelated service), recorded, and withdrawable at any time. For datasets this means storing consent as data, per person and per purpose, and filtering on it every time a training set is built:
import pandas as pd
people = pd.DataFrame({
"person": ["p1", "p2", "p3", "p4", "p5"],
"consent_research": [True, True, False, True, True],
"withdrawn_on": [None, "2026-05-02", None, None, None],
"collected_on": ["2023-02-10", "2025-01-15", "2025-03-01", "2020-11-30", "2026-01-20"],
})
build_date = pd.Timestamp("2026-06-01")
retention = pd.DateOffset(years=5)
people["collected_on"] = pd.to_datetime(people["collected_on"])
people["withdrawn_on"] = pd.to_datetime(people["withdrawn_on"])
reasons = pd.Series("", index=people.index)
reasons[~people["consent_research"]] = "no research consent"
reasons[people["withdrawn_on"] <= build_date] = "consent withdrawn"
reasons[people["collected_on"] + retention < build_date] = "past 5-year retention"
usable = people[reasons == ""]
print("usable for this training set:", usable["person"].tolist())
print(pd.DataFrame({"person": people["person"], "excluded because": reasons})[reasons != ""].to_string(index=False))usable for this training set: ['p1', 'p5']
person excluded because
p2 consent withdrawn
p3 no research consent
p4 past 5-year retention
The filter runs at build time, so a dataset built next month automatically drops anyone who withdraws in between. Datasets and models built earlier are a harder problem: retention policies must say what happens to them, and removing one person's influence from an already trained model ("machine unlearning") is still an open research area, which is why the safest designs keep personal data out of training sets that do not need it.
Pseudonymisation and anonymisation
Pseudonymisation replaces identifiers with codes, so that analysts work with a3f9… instead of an email. The mapping (or the secret key) is kept separately. Pseudonymised data is still personal data under most laws, because the link can be restored. A keyed hash (HMAC) is a good way to pseudonymise: the same email always gets the same code, so tables can still be joined, but without the key nobody can recompute codes from a list of known emails:
import hashlib
import hmac
SECRET = b"stored-in-a-secrets-manager-not-in-code" # placeholder for the example
def pseudonym(value):
return hmac.new(SECRET, value.strip().lower().encode(), hashlib.sha256).hexdigest()[:12]
for email in ["ana.le@example.com", "Ana.Le@example.com ", "ben@example.com"]:
print(f"{email!r:24} -> {pseudonym(email)}")
plain = hashlib.sha256(b"ben@example.com").hexdigest()[:12]
print("unkeyed SHA-256 of ben's email:", plain, "(anyone can recompute this)")'ana.le@example.com' -> 0f92fc4a32a9
'Ana.Le@example.com ' -> 0f92fc4a32a9
'ben@example.com' -> ad79e9233f95
unkeyed SHA-256 of ben's email: f871a76fb7b1 (anyone can recompute this)
Normalising first (trimming and lower-casing) makes the two spellings of Ana's email map to the same code. A plain, unkeyed hash is weak: anyone with a list of emails can hash them all and match.
Anonymisation goes further: it must be impossible, with reasonable effort, to re-identify anyone, also by combining quasi-identifiers. One classic measure is k-anonymity: every combination of quasi-identifier values must be shared by at least k people. Generalising values (exact age to an age band, full postcode to its first digits) raises k:
import pandas as pd
df = pd.DataFrame({
"age": [34, 36, 35, 51, 58, 52, 29, 27],
"zip": ["10115", "10117", "10119", "70173", "70176", "70174", "80331", "80333"],
"gender": ["F", "F", "F", "M", "M", "M", "F", "F"],
"diagnosis": ["flu", "asthma", "flu", "diabetes", "flu", "asthma", "flu", "migraine"],
})
qi = ["age", "zip", "gender"]
def k_anonymity(d):
return int(d.groupby(qi).size().min())
print("k with exact values:", k_anonymity(df))
gen = df.assign(age=(df["age"] // 10 * 10).astype(str) + "s", zip=df["zip"].str[:3] + "**")
print("k after generalising:", k_anonymity(gen))
print(gen.sort_values(qi).to_string(index=False))k with exact values: 1
k after generalising: 2
age zip gender diagnosis
20s 803** F flu
20s 803** F migraine
30s 101** F flu
30s 101** F asthma
30s 101** F flu
50s 701** M diabetes
50s 701** M flu
50s 701** M asthma
With exact values every person is unique (k = 1). After generalising, each combination covers at least two people. k-anonymity has known weaknesses (if everyone in a group has the same diagnosis, the group reveals it), and stronger methods such as differential privacy exist; the point here is that anonymisation is a property you must test, not a step you assume.
Licensing, again
The previous lesson introduced licences. Two habits connect them with the rest of this lesson:
- Record the licence and terms per source, in the metadata, next to consent and retention. A dataset built from several sources inherits every condition of every source; the most restrictive one wins.
- Check compatibility before combining. Mixing CC BY-SA data with data under incompatible terms, or adding non-commercial data to a commercial product's training set, can make the whole dataset unusable for its purpose.
Access permissions
Even lawful data should be visible only to those who need it. The usual controls:
| Control | Meaning |
|---|---|
| least privilege | each person and service gets the minimum access needed, for the minimum time |
| role-based access | permissions attach to roles (analyst, labeller, ML engineer), not to individuals |
| separation | identifiers in one store, pseudonymised features in another; few people can join them |
| audit logs | every access is recorded, so misuse can be detected and investigated |
| secure environments | sensitive data stays in a controlled environment; only aggregate results leave |
A role-to-column policy, enforced in code before data is handed out:
import pandas as pd
data = pd.DataFrame({
"email": ["ana.le@example.com", "ben@example.com"],
"pseudonym": ["0f92fc4a32a9", "ad79e9233f95"],
"age_band": ["30s", "50s"],
"diagnosis": ["flu", "diabetes"],
})
POLICY = {
"ml_engineer": ["pseudonym", "age_band", "diagnosis"],
"labeller": ["pseudonym", "diagnosis"],
"support_agent": ["email"],
}
def view_for(role):
allowed = POLICY.get(role)
if allowed is None:
raise PermissionError(f"role {role!r} has no access")
print(f"[audit] {role} read columns {allowed}")
return data[allowed]
print(view_for("labeller"))
try:
view_for("intern")
except PermissionError as e:
print("refused:", e)[audit] labeller read columns ['pseudonym', 'diagnosis']
pseudonym diagnosis
0 0f92fc4a32a9 flu
1 ad79e9233f95 diabetes
refused: role 'intern' has no access
The pseudonyms are the keyed hashes from the example above. In production this is done by the database, the data catalog or the cloud's access management, not by your own function, but the logic is the same.
A checklist before using a dataset
- What is the lawful basis for this purpose, and is it recorded?
- Does the data contain personal or sensitive data? Can the purpose be met with less (minimisation)?
- Is consent (where it is the basis) present, specific to this purpose and not withdrawn?
- What are the licence and contract terms of every source, and are they compatible?
- What is the retention period, and how will deletion reach derived datasets and models?
- Who has access, and is it logged?
- Has anyone assessed the risks to the people in the data (a data protection impact assessment, where required)?
Pitfalls
- "Anonymised" by deleting names: quasi-identifiers still identify people. Test, for example with k-anonymity.
- Purpose creep: reusing data collected for one purpose to train a model for another without a lawful basis.
- Keys and mappings next to the data: a pseudonymisation key stored with the data turns it back into plain personal data.
- Personal data in free text and media: names in support tickets, faces in the background of photos, metadata such as GPS in image files.
- Forgetting the copies: exports, notebooks, laptops and old dataset versions all count.
Practice
- A dataset contains
full_name,email,birth_date,zip,purchase_total. You need a model of purchase totals by age group and region. Which columns do you keep, and in what form?
Answer
Drop full_name and email (or replace them by a keyed pseudonym if rows must be linked to other tables). Keep an age band derived from birth_date instead of the date itself, and a coarse region (the first digits of zip) instead of the full code. Keep purchase_total. That is data minimisation plus generalisation.
- Person p4 in the consent example has research consent and has not withdrawn it. Why is p4 still excluded?
Answer
Their data was collected on 2020-11-30, and the 5-year retention period ended on 2025-11-30, before the build date of 2026-06-01. Retention limits apply even with consent.
Test yourself
Which of these is a quasi-identifier?
- A national ID number
- A full name
- A birth date
- A random row number
Is pseudonymised data (identifiers replaced by keyed hashes) still personal data?
- No, it is anonymous
- Yes, because whoever has the key or mapping can re-identify people
- Only if it contains health data
- Only in the EU
Data collected to ship orders is reused to train a credit-risk model without telling customers. Which principle is violated?
- Accuracy
- Purpose limitation
- Data minimisation only
- None
Every combination of (age band, zip prefix, gender) in a table is shared by at least 3 people. The table is…
- 1-anonymous
- 3-anonymous
- fully anonymous in all cases
- pseudonymised
What does 'least privilege' mean?
- Give everyone read access
- Give each person or service only the access it needs, for as long as it needs it
- Only administrators may train models
- Delete data after one day