Pulse Data Hub

The Dark Side of Big Data: Privacy and Bias Risks, Tested in Python

Big data helps companies forecast demand, catch fraud and recommend products. The same data can also expose people, sort them unfairly and follow them around. That is the dark side of big data, and most of it does not come from hackers or bad intentions. It comes from ordinary datasets doing things nobody planned.

This guide explains the main risks in plain language, then tests two of them in Python on real census data: how easily people in an “anonymous” dataset can be singled out, and how a model keeps treating men and women differently after you delete the sex column. Every number below comes straight from the code in this article.

The dark side of big data: six risks

RiskWhat happensA real example
Re-identificationData with names removed still points to specific people when a few details are combined.In 2006 AOL published search logs for about 650,000 users with names replaced by numbers. Reporters identified individual users from their searches within days.
Data breachesLarge stores of personal data are stolen, and people cannot change their birth date or ID number afterwards.The 2017 Equifax breach exposed records of about 147 million people.
ProfilingBehaviour data is used to infer things people never shared: health, money problems, beliefs.In the Cambridge Analytica case, data from up to 87 million Facebook profiles was collected for political targeting.
DiscriminationModels learn patterns from past decisions and repeat them at scale.Amazon stopped using an experimental hiring model after it learned to mark down CVs that mentioned the word “women’s”, as Reuters reported in 2018.
SurveillanceLocation, camera and device data make it possible to track people continuously.Location data sold by apps has repeatedly been matched to individual homes and workplaces.
Weak consentPeople agree to long policies they do not read, and data is reused for purposes they never expected.Data collected for one service is sold to data brokers and combined with other sources.
Six ways large datasets can harm the people in them.

Two parts of the dark side of big data are easy to measure yourself: re-identification and discrimination. That is what the project below does. If the difference between large and small datasets is new to you, start with big data vs small data.

Python project: test privacy and bias on real census data

The data is the Adult dataset from the UCI Machine Learning Repository: 48,842 records taken from the 1994 US census, each with a person’s age, work, education, family situation and whether they earned more than 50,000 dollars a year. It has no names or addresses and researchers have used it openly for decades, which makes it a good, safe place to see how these problems work.

pip install pandas scikit-learn matplotlib

1. Load the data

import pandas as pd

URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/adult-all.csv"
cols = ["age", "workclass", "fnlwgt", "education", "education_num", "marital_status",
        "occupation", "relationship", "race", "sex", "capital_gain", "capital_loss",
        "hours_per_week", "native_country", "income"]
df = pd.read_csv(URL, names=cols, skipinitialspace=True)

print(df.shape)
print(df[["age", "sex", "race", "marital_status", "occupation", "native_country", "income"]].head(3).to_string())
print(f"Earning over 50K: {(df['income'] == '>50K').mean():.1%}")

Output:

(48842, 15)
   age   sex   race      marital_status         occupation native_country income
0   39  Male  White       Never-married       Adm-clerical  United-States  <=50K
1   50  Male  White  Married-civ-spouse    Exec-managerial  United-States  <=50K
2   38  Male  White            Divorced  Handlers-cleaners  United-States  <=50K
Earning over 50K: 23.9%

There is nothing here that looks like identity: no name, no address, no ID number. About 24% of the people earn over 50K. Treat that income column as the sensitive fact, the thing a person would not want a stranger to look up.

2. Count how many people stand out

Now imagine someone who knows a few ordinary things about a person in this data: a colleague, a neighbour, or a company holding another dataset. The question is how many records match what they know. If only one record matches, that person has been found, name or no name. The function below groups the data by a set of columns and measures how small the groups are:

def risk(columns):
    size = df.groupby(columns, observed=True)[columns[0]].transform("size")
    return {"columns": len(columns),
            "unique": f"{(size == 1).mean():.1%}",
            "in a group under 5": f"{(size < 5).mean():.1%}",
            "median group": int(size.median())}

known = ["age", "sex", "race", "marital_status", "occupation", "education", "native_country"]
rows = [risk(known[:n]) for n in range(2, len(known) + 1)]
table = pd.DataFrame(rows, index=["+ " + c for c in known[1:]])
print(table.to_string())

Output:

                  columns unique in a group under 5  median group
+ sex                   2   0.0%               0.0%           586
+ race                  3   0.1%               0.7%           444
+ marital_status        4   1.2%               4.2%           218
+ occupation            5   8.7%              22.3%            19
+ education             6  26.3%              51.6%             4
+ native_country        7  32.0%              55.4%             3

Age and sex alone are harmless: the typical person shares them with 586 others. But every added detail cuts the groups down. With seven everyday details, 32.0% of the records are one of a kind and 55.4% sit in a group of fewer than five. None of the seven is private on its own. Most of them are on a typical professional profile page.

import matplotlib.pyplot as plt

share = [(df.groupby(known[:n])["age"].transform("size") < 5).mean() * 100
         for n in range(2, len(known) + 1)]
labels = ["age + sex"] + ["+ " + c.replace("_", " ") for c in known[2:]]

fig, ax = plt.subplots(figsize=(8, 4.2))
bars = ax.barh(labels[::-1], share[::-1], color="#c3cad3")
bars[0].set_color("#c8242c")
ax.bar_label(bars, fmt="%.0f%%", padding=4)
ax.set_xlim(0, 100)
ax.set_xlabel("Records in a group of fewer than 5 people (%)")
ax.set_title("Each extra detail makes people easier to single out")
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("reidentification.png", dpi=150, bbox_inches="tight")
plt.show()
Bar chart showing the share of census records in groups of fewer than 5 people rising from 0% to 55% as details are added
Share of records that share their details with fewer than four other people.

This is not a quirk of this dataset. In a well-known study, Latanya Sweeney estimated that 87% of people in the United States could be uniquely identified by just three facts: ZIP code, date of birth and sex. One caution for our numbers: these records are a sample, so being unique here does not prove a person is unique in the whole country. The risk is highest when the attacker knows the person is in the data, which is exactly the situation with a customer list, a patient file or a staff survey.

3. Check what a match reveals

Finding the record matters because of what comes with it. There is a second, less obvious leak: a person can hide in a group and still lose their secret, if everyone in the group has the same answer.

groups = df.groupby(known)["income"]
size = groups.transform("size")
same_income = groups.transform("nunique") == 1

print(f"Records that are unique on the 7 details: {(size == 1).mean():.1%}")
print(f"Records whose income band is revealed:    {same_income.mean():.1%}")
print(f"  of which hidden in a group of 2 or more: {(same_income & (size > 1)).mean():.1%}")

Output:

Records that are unique on the 7 details: 32.0%
Records whose income band is revealed:    66.1%
  of which hidden in a group of 2 or more: 34.1%

For 66.1% of the records, knowing the seven details is enough to learn the income band with certainty. About half of those are the unique records. The other 34.1% are people who share their details with others, but every one of them is in the same income band, so the group protects nobody. Counting unique rows alone would have missed half the problem.

4. Reduce the risk by making the data coarser

The standard defence is generalisation: replace exact values with broader ones, so more people share each combination. Here, exact age becomes an age band, 41 countries become two groups, 16 education levels become four and seven marital statuses become three:

safe = df.copy()
safe["age"] = pd.cut(df["age"], [16, 29, 39, 49, 59, 90],
                     labels=["17-29", "30-39", "40-49", "50-59", "60+"])
safe["native_country"] = df["native_country"].where(df["native_country"] == "United-States", "Other")
safe["education"] = pd.cut(df["education_num"], [0, 8, 9, 12, 16],
                           labels=["No diploma", "High school", "Some college", "Degree"])
safe["marital_status"] = df["marital_status"].replace(
    {"Married-civ-spouse": "Married", "Married-AF-spouse": "Married",
     "Married-spouse-absent": "Married", "Divorced": "Previously married",
     "Separated": "Previously married", "Widowed": "Previously married"})

g = safe.groupby(known, observed=True)["income"]
size, same_income = g.transform("size"), g.transform("nunique") == 1
print(f"Unique records:           {(size == 1).mean():.1%}")
print(f"In a group under 5:       {(size < 5).mean():.1%}")
print(f"Income band revealed:     {same_income.mean():.1%}")

released = safe[size >= 5]
print(f"Rows kept when groups under 5 are removed: {len(released):,} of {len(safe):,} ({len(released) / len(safe):.1%})")

Output:

Unique records:           3.6%
In a group under 5:       11.1%
Income band revealed:     29.5%
Rows kept when groups under 5 are removed: 43,417 of 48,842 (88.9%)

Unique records fall from 32.0% to 3.6%, and removing the groups that are still smaller than five costs 11.1% of the rows. What remains has a property called k-anonymity with k = 5: everyone shares their details with at least four other people. It is not a complete fix. In the generalised data, 29.5% of records still sit in groups where everyone has the same income band, so some leakage remains even with larger groups.

5. Check what the protection costs

Coarser data is less useful, in theory. To measure it, train the same model on both versions to predict who earns over 50K:

from sklearn.model_selection import train_test_split
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score

features = ["age", "workclass", "education", "marital_status", "occupation", "relationship",
            "race", "sex", "capital_gain", "capital_loss", "hours_per_week", "native_country"]
y = (df["income"] == ">50K").astype(int)

def prepare(data):
    X = data[features].copy()
    for c in X.columns:
        if not pd.api.types.is_numeric_dtype(X[c]):
            X[c] = X[c].astype(str).astype("category")
    return X

def fit(X):
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.3, stratify=y, random_state=42)
    model = HistGradientBoostingClassifier(categorical_features="from_dtype", random_state=42)
    model.fit(X_train, y_train)
    return model, X_test, y_test

for name, data in [("Original data", df), ("Generalised data", safe)]:
    model, X_test, y_test = fit(prepare(data))
    print(f"{name:<17} ROC AUC {roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]):.3f}")

Output:

Original data     ROC AUC 0.929
Generalised data  ROC AUC 0.928

The score barely moves: 0.929 against 0.928 (ROC AUC, where 1.0 is perfect and 0.5 is guessing). Here the exact age and the exact country added almost nothing to the prediction, but a lot to the risk. That will not hold for every dataset, yet it is common, and it is the practical reason behind the data minimisation rule in Article 5 of the GDPR: do not keep detail you do not need.

6. Test a model for unequal treatment

Now the second risk. Suppose this model were used for something that matters, such as deciding who is offered a premium account or a higher credit limit. Compare its results for men and women in the test set:

from sklearn.metrics import confusion_matrix

def by_sex(model, X_test, y_test, sex):
    pred = model.predict(X_test)
    out = []
    for group in ["Male", "Female"]:
        m = (sex == group).to_numpy()
        tn, fp, fn, tp = confusion_matrix(y_test[m], pred[m]).ravel()
        out.append({"group": group, "people": int(m.sum()),
                    "actually >50K": f"{y_test[m].mean():.1%}",
                    "predicted >50K": f"{pred[m].mean():.1%}",
                    "high earners found": f"{tp / (tp + fn):.1%}",
                    "false alarms": f"{fp / (fp + tn):.1%}"})
    return pd.DataFrame(out).set_index("group")

X = prepare(df)
model, X_test, y_test = fit(X)
sex_test = df.loc[X_test.index, "sex"]
print(by_sex(model, X_test, y_test, sex_test).to_string())

Output:

        people actually >50K predicted >50K high earners found false alarms
group                                                                      
Male      9736         30.4%          26.2%              67.0%         8.3%
Female    4917         11.1%           8.1%              57.9%         1.9%

The model predicts a high income for 26.2% of men and 8.1% of women. Part of that reflects the data: in this 1994 sample 30.4% of men and 11.1% of women earned over 50K. But the errors are uneven as well. Among people who really are high earners, the model finds 67.0% of the men and only 57.9% of the women. A woman who qualifies is more likely to be missed than a man who qualifies. You can check figures like these for any model with our confusion matrix calculator.

7. Remove the sex column and test again

The obvious fix is to delete the sensitive column, so the model cannot use it. Try it:

blind, Xb_test, yb_test = fit(X.drop(columns=["sex"]))
print("Model trained without the sex column:")
print(by_sex(blind, Xb_test, yb_test, sex_test).to_string())

Output:

Model trained without the sex column:
        people actually >50K predicted >50K high earners found false alarms
group                                                                      
Male      9736         30.4%          25.9%              66.6%         8.0%
Female    4917         11.1%           8.1%              57.5%         1.9%

Almost nothing changes: 66.6% of high-earning men found against 57.5% of high-earning women. The model never sees the sex column and behaves the same way. The reason is that other columns carry the same information:

is_female = (df["sex"] == "Female").astype(int)

def guess_sex(columns):
    Xp = X[columns]
    X_train, X_test, s_train, s_test = train_test_split(
        Xp, is_female, test_size=0.3, stratify=is_female, random_state=42)
    m = HistGradientBoostingClassifier(categorical_features="from_dtype", random_state=42)
    m.fit(X_train, s_train)
    return roc_auc_score(s_test, m.predict_proba(X_test)[:, 1]), m.score(X_test, s_test)

others = [c for c in features if c != "sex"]
for name, columns in [("All other columns", others),
                      ("Without relationship", [c for c in others if c != "relationship"]),
                      ("Occupation and hours only", ["occupation", "hours_per_week"])]:
    auc, acc = guess_sex(columns)
    print(f"{name:<26} ROC AUC {auc:.3f}   accuracy {acc:.1%}")
print(f"Always guessing 'Male' would score {1 - is_female.mean():.1%}")

Output:

All other columns          ROC AUC 0.935   accuracy 84.7%
Without relationship       ROC AUC 0.872   accuracy 80.1%
Occupation and hours only  ROC AUC 0.785   accuracy 73.6%
Always guessing 'Male' would score 66.8%

A second model can guess a person’s sex from the remaining columns with 84.7% accuracy, far better than the 66.8% you get by always guessing “male”. The relationship column (husband, wife) is an obvious giveaway, but even occupation and weekly hours alone reach 73.6%. These stand-in columns are called proxies, and they are why “we do not collect that field” is not proof that a system treats people equally. Fairness has to be measured on the results, as in step 6, not assumed from the list of inputs.

How to manage the dark side of big data

The dark side of big data is not a reason to stop using data. It means the risks need the same routine attention as accuracy. In practice:

  • Collect and keep less. Every extra column raises re-identification risk. Step 5 showed that the detail is often not needed.
  • Measure before you share. Run the group-size check from steps 2 and 3 on any dataset before it leaves your team, including the check for groups that all share one sensitive value.
  • Generalise or aggregate ages, dates and locations in anything published or passed to another company.
  • Test models by group. Compare error rates, not just overall accuracy, for the groups your decisions affect.
  • Do not rely on deleting columns. Look for proxies, and check outcomes after the change.
  • Limit access and keep records. Most breaches start with ordinary accounts that could see more than they needed.
  • Be clear with people about what you collect and why, in words they can read in a minute.

Good habits start early in a project. Our guides to cleaning and preprocessing data and data literacy cover the basics, and the insurance pricing project shows a field where fairness rules shape what a model may use.

Related reading

FAQ

What is the dark side of big data?

It is the set of harms that large-scale data collection can cause to the people in the data: loss of privacy, re-identification of “anonymous” records, data breaches, profiling, unfair automated decisions and surveillance.

Can anonymous data really be traced back to a person?

Often, yes. Removing names does not remove the combination of details that makes a person stand out. In this article’s census data, 32% of records were unique on seven everyday details such as age, occupation and education.

What is k-anonymity?

A dataset is k-anonymous when every person shares their identifying details with at least k minus 1 others, so nobody can be narrowed down to a group smaller than k. It is usually reached by replacing exact values with broader bands and removing very small groups.

Does removing gender or race from the data make a model fair?

No. Other columns usually carry the same information. In this article, a model trained without the sex column gave almost identical results, and sex could be guessed from the remaining columns with about 85% accuracy.

What is a proxy variable?

A column that stands in for another one because the two are closely related. Postcode can act as a proxy for income or ethnicity, and job title or working hours for sex.

How can companies use big data responsibly?

Collect only what is needed, measure re-identification risk before sharing data, generalise or aggregate detailed fields, test models for unequal error rates between groups, limit who can access personal data and explain clearly what is collected.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights