PROMETHEUS OS
NATIVE AI OPERATING SYSTEM
[INIT] Prometheus OS loading...
[CORE] Neural interface initializing...
[AI] LLM router connecting...
[MEM] Memory graph loading...
[AGT] Agent chains on standby...
[SEC] Security protocols active...
[NET] Provider mesh established...
[UI] Workspace rendering...
[DONE] All systems nominal.
Welcome to PROMETHEUS OS.
READY · OFFLINE · SECURE · PRIVATE
🎨 THEME ENGINE
PROMETHEUS OS · 23 THEMES
Trial version: Dark + Light themes only.
Full theme access with PROMETHEUS OS license.
Dark theme active
Experience all 23 themes in PROMETHEUS OS

Privacy-Preserving AI: Attacks, Differential Privacy, Federated Learning and the Law

Advanced 19 min· 4 exercises

Learn how trained models leak information about their training data, and how to defend against it with differential privacy (including DP-SGD), federated learning, secure computation, careful de-identification and data minimization, within the principles of the GDPR.

By the end of this lesson you will be able to
  • Explain the threat model for membership inference, model inversion and training-data extraction, and evaluate attacks with the right metrics.
  • Define (epsilon, delta)-differential privacy, interpret epsilon as a bound on an attacker's success, and calibrate the Laplace and Gaussian mechanisms.
  • Implement the core of DP-SGD (per-example clipping plus Gaussian noise) and describe how privacy accounting works.
  • Compare federated learning, secure aggregation, confidential computing, homomorphic encryption and multi-party computation by what they protect and what they cost.
  • Identify why naive anonymization fails and apply data minimization and the GDPR principles to an AI project.

Before this: Privacy and Your Data, AI Security Risks, Probability and Statistics for AI, Training Deep Networks in Practice

A model is a function fitted to data, and some of that data can be read back out of it. Language models have reproduced phone numbers from their training sets, image classifiers have been inverted into recognizable faces, and simple statistical tests can reveal whether a particular patient's record was used to train a hospital's model. This lesson covers how those leaks happen, the mathematical tools that bound them, the engineering techniques that keep raw data out of reach, and the legal principles that apply when the data is about people.

Intuition: a model is a lossy compression of its data

Picture a student who studies for an exam by memorizing past papers. Ask them a question they saw before and they answer instantly and confidently; ask a new one and they hesitate. Watching that difference in confidence tells you which questions were in their study set. Ask them to "write out a practice paper" and some of what they produce will be the past papers, word for word.

Models behave the same way. Training minimizes loss on the training set, so training examples tend to get lower loss and higher confidence than unseen ones, and rare or repeated examples can be memorized verbatim. Every privacy attack below exploits this gap between how the model treats data it has seen and data it has not. Every defense either shrinks the gap (regularization, differential privacy), keeps the raw data away from the party that could exploit it (federated learning, secure computation), or avoids collecting the data in the first place (minimization).

The threat model

Specify an attack by access (black-box: query outputs only, perhaps only labels; white-box: weights and gradients), knowledge (does the attacker know the data distribution or have similar data?) and goal.

Membership inference

Goal: decide whether a given record xx was in the training set. Shokri et al. (2017) trained shadow models on data similar to the target's, observed how shadow models' output vectors differ on their own members versus non-members, and trained an attack classifier on those vectors. A simpler and strong baseline is the loss-threshold attack: predict "member" if the target model's loss on (x,y)(x, y) is below a threshold τ\tau.

Membership matters because membership itself can be sensitive (being in a cancer-treatment dataset reveals a diagnosis), and because membership inference is the standard yardstick for measuring leakage. Report attacks by their true-positive rate at a low false-positive rate (for example TPR at 0.1% FPR), not by average accuracy: an attack that confidently identifies a few people is a real privacy failure even if its overall accuracy is near 50% (Carlini et al., 2022, make this argument in detail).

Model inversion and attribute inference

Goal: reconstruct features of training data, or infer a sensitive attribute of a known person. Fredrikson et al. (2015) used confidence scores from a face-recognition model to reconstruct recognizable images of people in the training set by optimizing an input to maximize the confidence for a target name, and showed attribute inference against a lifestyle-survey model. Returning only labels or rounded confidences reduced their attack's effectiveness, which is an early example of output minimization as a defense.

Training-data extraction

Goal: recover verbatim training examples from a generative model. Carlini et al. (2021) generated large numbers of samples from GPT-2, ranked them by signals of memorization (for example, a low perplexity under GPT-2 relative to a smaller reference model or to zlib compression), and confirmed hundreds of verbatim training sequences, including names, phone numbers and email addresses. Extraction grows with model size, the number of times a string is duplicated in the training data, and the length of the prompt context. Deduplicating training data is one of the cheapest and most effective mitigations.

Other leak paths you should list in any threat model: gradient sharing (gradients can be inverted into inputs, see federated learning below), embeddings (text embeddings can be partly inverted back to text), retrieval-augmented systems (the model faithfully quotes sensitive documents a user should not see; this is an access-control failure, not a training one) and logs of prompts and outputs.

Differential privacy

The definition

Call two datasets DD and D′D' neighbors if they differ in one individual's record (either by adding/removing one record, or replacing one; state which, since constants change). A randomized mechanism MM is (ε,δ)(\varepsilon, \delta)-differentially private if for all neighboring D,D′D, D' and every set of outputs SS:

Pr⁡[M(D)∈S]≤eε Pr⁡[M(D′)∈S]+δ.\Pr[M(D) \in S] \le e^{\varepsilon} \, \Pr[M(D') \in S] + \delta .

Here ε≥0\varepsilon \ge 0 is the privacy loss budget (smaller is more private) and δ∈[0,1)\delta \in [0, 1) is a small slack, the probability mass on which the eεe^{\varepsilon} bound may fail; it should be much smaller than 1/n1/n for a dataset of nn people. With δ=0\delta = 0 we call it pure ε\varepsilon-DP. The definition is a property of the algorithm, not of a dataset: it holds whatever the attacker knows, including every other record.

What epsilon means for an attacker

Treat membership inference as a hypothesis test between DD (target present) and D′D' (absent). Any attack that outputs "present" is an event SS, so DP implies

TPR≤eε⋅FPR+δ.\text{TPR} \le e^{\varepsilon} \cdot \text{FPR} + \delta .

With ε=1\varepsilon = 1, δ=0\delta = 0 and an attacker who tolerates a 1% false-positive rate, the true-positive rate is at most e1×0.01≈0.0272e^{1} \times 0.01 \approx 0.0272: barely better than guessing at that operating point. With ε=8\varepsilon = 8, the bound is e8×0.01≈29.8e^{8} \times 0.01 \approx 29.8, which is no constraint at all at 1% FPR. That is why large ε\varepsilon values still often defeat practical attacks (the bound is worst-case, and real attacks are weaker) but offer weak guarantees.

Two key properties

  • Post-processing: any computation on the output of a DP mechanism, without touching the data again, remains DP with the same parameters. You can publish the model and let anyone use it.
  • Composition: running mechanisms with budgets ε1,…,εk\varepsilon_1, \dots, \varepsilon_k on the same data is at most (∑iεi,∑iδi)(\sum_i \varepsilon_i, \sum_i \delta_i)-DP. This basic bound is loose; advanced composition and Rényi-DP accountants give much tighter totals for many repeated noisy steps, which is what makes DP training feasible.

The Laplace and Gaussian mechanisms

For a numeric query ff, the ℓ1\ell_1-sensitivity is Δ1f=max⁡D∼D′∥f(D)−f(D′)∥1\Delta_1 f = \max_{D \sim D'} \lVert f(D) - f(D') \rVert_1. The Laplace mechanism releases f(D)+Lap(Δ1f/ε)f(D) + \text{Lap}(\Delta_1 f / \varepsilon) and is ε\varepsilon-DP. The Gaussian mechanism releases f(D)+N(0,σ2)f(D) + \mathcal{N}(0, \sigma^2) with ℓ2\ell_2-sensitivity Δ2f\Delta_2 f; the classical analysis gives (ε,δ)(\varepsilon, \delta)-DP for ε<1\varepsilon < 1 when

σ≥Δ2f2ln⁡(1.25/δ)ε.\sigma \ge \frac{\Delta_2 f \sqrt{2 \ln(1.25/\delta)}}{\varepsilon}.

(Tighter calibrations exist and are used by modern libraries; this one is the textbook version.)

Worked example 1: a private count

A clinic asks "how many patients in this dataset have diabetes?" Adding or removing one person changes the count by at most 1, so Δ1f=1\Delta_1 f = 1. With ε=0.5\varepsilon = 0.5, add Laplace noise with scale b=1/0.5=2b = 1/0.5 = 2. The Laplace distribution has standard deviation 2 b≈2.83\sqrt{2}\, b \approx 2.83, and Pr⁡[∣noise∣>t]=e−t/b\Pr[|\text{noise}| > t] = e^{-t/b}, so the released count is within ±6\pm 6 of the truth with probability 1−e−3≈0.951 - e^{-3} \approx 0.95. For a true count of 1,240 that error is negligible; for a true count of 7 in a rural clinic it swamps the answer. DP protects individuals by making small groups invisible, which is both the point and the cost.

Worked example 2: a private mean

Release the mean salary of n=10,000n = 10{,}000 employees. First clip each salary to [0,200,000][0, 200{,}000] so sensitivity is bounded. Under replace-one neighbors, the mean changes by at most 200,000/10,000=20200{,}000 / 10{,}000 = 20, so Δ2f=20\Delta_2 f = 20. With ε=0.9\varepsilon = 0.9 (the classical bound needs ε<1\varepsilon < 1) and δ=10−5\delta = 10^{-5}:

ln⁡(1.25/10−5)=ln⁡(125,000)≈11.736,2×11.736=23.472≈4.845,\ln(1.25 / 10^{-5}) = \ln(125{,}000) \approx 11.736, \quad \sqrt{2 \times 11.736} = \sqrt{23.472} \approx 4.845,

so σ≈20×4.845/0.9≈107.7\sigma \approx 20 \times 4.845 / 0.9 \approx 107.7. The released mean is typically within about ±215\pm 215 (two standard deviations) of the true mean, on salaries averaging tens of thousands. Notice that clipping introduced bias (anyone above 200,000 is counted as 200,000); choosing the clipping bound is a real modeling decision.

DP-SGD: training models with differential privacy

Abadi et al. (2016) made deep learning differentially private with three changes to stochastic gradient descent. At each step tt:

  1. Sample a batch by including each example independently with probability q=L/Nq = L/N (Poisson sampling; LL is the expected batch size, NN the dataset size).
  2. Clip each per-example gradient gi=∇θℓ(θt;xi)g_i = \nabla_\theta \ell(\theta_t; x_i) to norm at most CC:
gˉi=gi⋅min⁡ ⁣(1,C∥gi∥2).\bar g_i = g_i \cdot \min\!\left(1, \frac{C}{\lVert g_i \rVert_2}\right).
  1. Add noise and average:
g~=1L(∑i∈Btgˉi+N(0,σ2C2I)),θt+1=θt−η g~.\tilde g = \frac{1}{L}\left(\sum_{i \in B_t} \bar g_i + \mathcal{N}(0, \sigma^2 C^2 \mathbf{I})\right), \qquad \theta_{t+1} = \theta_t - \eta\, \tilde g .

Clipping bounds each person's influence on the sum (sensitivity CC); noise with standard deviation σC\sigma C hides it; and a privacy accountant (the moments accountant in the original paper, now usually Rényi DP or numerical accountants) converts the noise multiplier σ\sigma, sampling rate qq, number of steps TT and target δ\delta into a total ε\varepsilon. Sampling helps a lot: each example is only touched in a fraction qq of steps ("privacy amplification by subsampling").

import torch
import torch.nn as nn

def dp_sgd_step(model, loss_fn, xb, yb, lr=0.1, clip=1.0, noise_mult=1.1):
    # One DP-SGD step with explicit per-example clipping (clear, not fast).
    params = [p for p in model.parameters() if p.requires_grad]
    summed = [torch.zeros_like(p) for p in params]
    for x, y in zip(xb, yb):                      # per-example gradients
        model.zero_grad()
        loss_fn(model(x.unsqueeze(0)), y.unsqueeze(0)).backward()
        grads = [p.grad.detach().clone() for p in params]
        norm = torch.sqrt(sum((g ** 2).sum() for g in grads))
        scale = min(1.0, clip / (norm.item() + 1e-12))
        for s, g in zip(summed, grads):
            s += g * scale                        # clipped contribution
    with torch.no_grad():
        for p, s in zip(params, summed):
            noise = torch.randn_like(s) * noise_mult * clip
            p -= lr * (s + noise) / len(xb)       # noisy average
    model.zero_grad()

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(20, 32), nn.ReLU(), nn.Linear(32, 2))
X, Y = torch.randn(64, 20), torch.randint(0, 2, (64,))
for _ in range(5):
    dp_sgd_step(model, nn.CrossEntropyLoss(), X, Y)

This loop is written for clarity. Production code computes per-example gradients in one vectorized pass and uses a maintained library (Opacus for PyTorch, TensorFlow Privacy, or JAX-based equivalents) that also performs Poisson sampling and privacy accounting. Never hand-roll the accountant for a real release. Two practical notes: batch normalization mixes examples within a batch and breaks the per-example analysis (use group or layer normalization), and hyperparameter tuning on private data also consumes privacy budget.

DP training costs accuracy, more so for small datasets and for under-represented groups, whose examples tend to have large gradients that get clipped. Common strategies are pretraining on public data and fine-tuning privately, larger batches, and fewer, larger-noise steps. There is no universal "safe" ε\varepsilon; reported deployments range from below 1 to well above 10, and you should state ε\varepsilon, δ\delta, the neighbor definition and the unit of privacy (one record, or one user with many records) whenever you claim DP.

Differential privacy has been deployed at scale outside ML too: the U.S. Census Bureau used it to protect 2020 Census redistricting data, and Google's RAPPOR (Erlingsson et al., 2014) used local DP, where each user randomizes their own data before sending it, so the collector never sees raw values.

Federated learning

In federated learning (McMahan et al., 2017), data stays on clients (phones, hospitals) and only model updates travel. Federated Averaging (FedAvg): the server sends weights wtw_t to a sample of clients; each client kk runs a few epochs of local SGD on its nkn_k examples to get wt+1kw_{t+1}^{k}; the server averages

wt+1=∑knkn wt+1k,n=∑knk.w_{t+1} = \sum_{k} \frac{n_k}{n} \, w_{t+1}^{k}, \qquad n = \sum_k n_k .

Federated learning is data minimization, not a privacy guarantee. Updates can leak training data: gradient-inversion attacks have reconstructed images and text from shared gradients, especially with small local batches. The standard stack therefore adds secure aggregation (a cryptographic protocol so the server learns only the sum of many clients' updates, not any single update; Bonawitz et al., 2017) and differential privacy on the aggregate (often user-level, clipping each client's whole update). Practical challenges include non-identically-distributed client data, stragglers and dropouts, and poisoning by malicious clients.

Secure computation: confidential computing, HE and MPC

TechniqueWhat it protectsTrust assumptionPracticality (evergreen summary)
Confidential computing (trusted execution environments on CPUs and some datacenter GPUs, with remote attestation)Data and model in use, from the cloud operator and host OSTrust the hardware vendor and its attestation; side channels are a known weaknessPractical today for training and inference, with modest overhead
Homomorphic encryption (HE; e.g. CKKS for approximate arithmetic)Inputs and outputs from the server computing on themCryptographic onlyOrders of magnitude slower; feasible for linear models and small networks, research-stage for large models
Secure multi-party computation (MPC; secret sharing, garbled circuits)Each party's inputs from the othersAssumes some parties do not colludePractical for specific tasks (private set intersection, aggregate statistics, small-model inference); heavy communication for large models

None of these limit what the output reveals: a model trained inside an enclave can still memorize and leak data. Combine "who can see the data during computation" defenses with "what the result reveals" defenses such as DP.

Anonymization pitfalls

Removing names is pseudonymization, not anonymization. Sweeney (2000) estimated that about 87% of the U.S. population could be uniquely identified by 5-digit ZIP code, gender and date of birth. Narayanan and Shmatikov (2008) re-identified users in the "anonymized" Netflix Prize dataset by matching a handful of movie ratings and dates against public IMDb reviews: high-dimensional, sparse data makes almost everyone unique. Classical fixes such as kk-anonymity (every record indistinguishable from at least k−1k-1 others on quasi-identifiers) and ℓ\ell-diversity break down in high dimensions and against background knowledge. Synthetic data is not automatically private either: a generator can memorize and reproduce records unless it is trained with DP and evaluated with membership-inference tests. Under the GDPR (Recital 26), pseudonymized data is still personal data; only data where identification is not reasonably likely, taking into account all means reasonably likely to be used, falls outside the regulation.

Data minimization and the GDPR

The GDPR's Article 5 principles map directly onto ML practice:

  • Lawfulness, fairness and transparency: have a lawful basis (Art. 6) for training and for inference; tell people. In December 2024 the European Data Protection Board's Opinion 28/2024 addressed when AI models trained on personal data can be considered anonymous and how legitimate interest may serve as a basis, with a case-by-case three-step test.
  • Purpose limitation: data collected for support tickets is not automatically available to train a marketing model.
  • Data minimization: use only what is adequate, relevant and necessary. Drop columns, aggregate, truncate free text, filter PII before training, and prefer features over raw records.
  • Accuracy: models that infer facts about people can create inaccurate personal data.
  • Storage limitation: retention limits for raw data, features, prompts and logs.
  • Integrity and confidentiality: security, including against the model-level attacks above.
  • Accountability: be able to demonstrate all of this (see AI Governance Frameworks).

Also relevant: special-category data (Art. 9: health, ethnicity, biometrics for identification and more) needs an additional condition; data protection by design and by default (Art. 25); DPIAs (Art. 35) for high-risk processing, which large-scale profiling with AI often is; automated decision-making with legal or similarly significant effects (Art. 22) requires safeguards including human intervention; and data-subject rights such as erasure (Art. 17), which is hard to honor for a trained model. Retraining without the data is the clean answer; "machine unlearning" methods that approximate it are an active research area without strong general guarantees, which is another argument for minimizing and filtering data before training.

Common pitfalls

  • Claiming "the model is private because we removed names" or "because we used federated learning". Neither is a guarantee.
  • Quoting ε\varepsilon without δ\delta, the neighbor definition, the unit of privacy, or whether hyperparameter tuning was counted.
  • Evaluating membership inference by accuracy or AUC alone instead of TPR at low FPR.
  • Forgetting non-training leaks: logs, retrieval corpora without access control, embeddings, and evaluation sets.
  • Training on duplicated data; duplication sharply raises memorization.
  • Using batch normalization or non-per-example operations inside DP-SGD, silently voiding the guarantee.
  • Treating synthetic data as anonymous without testing it.

In practice

Start with minimization and filtering: decide which fields you truly need, scrub PII from text corpora, deduplicate, and set retention limits; this removes most risk cheaply. Restrict outputs (labels or rounded scores rather than full probability vectors) where the product allows. Before release, run a membership-inference audit (loss-threshold and a stronger calibrated attack) and, for generative models, canary and extraction tests: insert unique secret strings into training data and check whether the model reproduces them. For sensitive tabular or clinical data, consider DP-SGD with a maintained library, starting from a publicly pretrained model. Use federated learning with secure aggregation when data legally or practically cannot leave its owners, and confidential computing when the threat is the infrastructure operator. Document all of it in the DPIA, and route deletion requests to a process that can actually honor them, which in practice often means scheduled retraining.

Key takeaways

  • Privacy attacks exploit the gap between how a model treats training data and unseen data: membership inference, model inversion and verbatim extraction are the core threats.
  • Differential privacy bounds any attacker's advantage: TPR is at most e^epsilon times FPR plus delta, and the guarantee survives post-processing and composes across releases.
  • DP-SGD makes training private with per-example clipping, Gaussian noise and a privacy accountant, at an accuracy cost that is largest for small data and minority groups.
  • Federated learning, secure aggregation, confidential computing, HE and MPC control who sees data during computation; only DP-style defenses limit what the output reveals.
  • Removing identifiers is pseudonymization, not anonymization; minimization, deduplication and the GDPR principles are the cheapest and most important protections.

Terms in this lesson

Membership inference
An attack that determines whether a specific record was part of a model's training data.
Model inversion
An attack that uses a model's outputs to reconstruct representative features of training data or sensitive attributes of individuals.
Differential privacy
A property of a randomized algorithm guaranteeing that its output distribution changes by at most a factor e^epsilon (plus delta) when any one individual's data is added, removed or replaced.
Sensitivity
The maximum change in a query's output, measured in a chosen norm, between any two neighboring datasets.
DP-SGD
Stochastic gradient descent modified with per-example gradient clipping and calibrated Gaussian noise so that training is differentially private.
Secure aggregation
A cryptographic protocol that lets a server learn the sum of many clients' updates without learning any individual update.
Pseudonymization
Replacing direct identifiers with codes so data cannot be attributed to a person without additional information kept separately; the result is still personal data under the GDPR.

Check your understanding

  1. 1.

    A mechanism is (1, 0)-differentially private. An attacker running membership inference accepts a 2% false-positive rate. What is the maximum possible true-positive rate?

  2. 2.

    Why does DP-SGD clip each per-example gradient rather than the batch-average gradient?

  3. 3.

    A team says: 'We use federated learning, so the model is private.' What is the best response?

  4. 4.

    You release a count with the Laplace mechanism, sensitivity 1, epsilon = 0.25. What is the noise scale b, and what is the probability that the noise exceeds 8 in absolute value?

  5. 5.

    Which statement about anonymization under the GDPR is correct?

Exercises

Work each problem before opening the solution.

  1. Exercise 1Core

    A data team answers three queries on the same patient dataset with pure DP: a count with epsilon = 0.3, a histogram with epsilon = 0.5, and a mean with epsilon = 0.4. (a) Using basic sequential composition, what is the total privacy loss? (b) The policy budget is epsilon = 1.0. Can they release a fourth query, and with what budget at most? (c) A downstream analyst rounds and plots the released numbers. Does that consume budget?

    Show solution

    (a) Basic composition adds the epsilons: 0.3 + 0.5 + 0.4 = 1.2.

    (b) They have already exceeded the budget (1.2 > 1.0), so no further release is allowed under basic composition. (Tighter accountants rarely help much for so few pure-DP queries; the right fix is to plan budgets before releasing.)

    (c) No. Rounding and plotting are post-processing of DP outputs without access to the raw data, so they preserve the guarantee and consume no budget.

  2. Exercise 2Core

    Implement a Laplace mechanism in numpy for a counting query and empirically check that, for epsilon = 0.5, about 95% of released values fall within plus or minus 6 of the true count.

    Show solution
    import numpy as np
    
    def laplace_count(true_count, epsilon, rng, sensitivity=1.0):
        return true_count + rng.laplace(0.0, sensitivity / epsilon)
    
    rng = np.random.default_rng(0)
    eps, truth = 0.5, 1240
    releases = np.array([laplace_count(truth, eps, rng) for _ in range(100_000)])
    within = np.mean(np.abs(releases - truth) <= 6)
    print(round(within, 3))   # about 0.950
    

    The scale is b = 1/0.5 = 2 and P(|noise| <= 6) = 1 - e^(-6/2) = 1 - e^(-3) = 0.9502, so the empirical fraction is about 0.95.

  3. Exercise 3Core

    Compute the Gaussian-mechanism noise needed to release the average age (clipped to [0, 100]) of 5,000 people with epsilon = 0.5 and delta = 1e-6, using the classical bound and replace-one neighbors. Then explain one reason a real deployment might use a different sigma.

    Show solution

    Sensitivity of the mean under replace-one: 100 / 5,000 = 0.02.

    ln(1.25 / 1e-6) = ln(1,250,000) = 14.039. 2 x 14.039 = 28.078; sqrt = 5.299.

    sigma = 0.02 x 5.299 / 0.5 = 0.212 years.

    A real deployment might use a smaller sigma because tighter analyses of the Gaussian mechanism (analytic calibration) achieve the same (epsilon, delta) with less noise, or a different sigma if the unit of privacy is a user with several records (larger sensitivity) or if the add/remove neighbor definition is used, which changes the sensitivity of a mean because n itself changes.

  4. Exercise 4Challenge

    Run a loss-threshold membership-inference attack against an overfit model. Train a random forest on half of a dataset (members) and keep the other half as non-members. Use the per-example cross-entropy loss as the attack score (lower loss = more likely member). Report the attack AUC and the TPR at 1% FPR. Then reduce overfitting (limit tree depth) and compare. Use scikit-learn's breast cancer dataset.

    Show solution
    import numpy as np
    from sklearn.datasets import load_breast_cancer
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import roc_auc_score, roc_curve
    
    X, y = load_breast_cancer(return_X_y=True)
    Xm, Xn, ym, yn = train_test_split(X, y, test_size=0.5, random_state=0)
    
    def attack(model):
        model.fit(Xm, ym)
        def losses(X_, y_):
            p = model.predict_proba(X_)[np.arange(len(y_)), y_]
            return -np.log(np.clip(p, 1e-6, 1.0))
        scores = np.concatenate([-losses(Xm, ym), -losses(Xn, yn)])  # high = member
        labels = np.concatenate([np.ones(len(ym)), np.zeros(len(yn))])
        fpr, tpr, _ = roc_curve(labels, scores)
        tpr_at_1 = tpr[fpr <= 0.01].max()
        return roc_auc_score(labels, scores), tpr_at_1
    
    print("deep  :", attack(RandomForestClassifier(n_estimators=200, random_state=0)))
    print("depth3:", attack(RandomForestClassifier(n_estimators=200, max_depth=3, random_state=0)))
    

    Interpretation. The fully grown forest assigns near-zero loss to almost every training point, while some non-members get noticeably higher loss, so the attack AUC is above 0.5 (about 0.58 in one run with scikit-learn 1.9; exact numbers vary with version and seed). Because many members and many easy non-members both get near-zero loss, TPR at 1% FPR can be near zero even when AUC is above chance, which is why both numbers should be reported. Limiting depth to 3 shrinks the train/test loss gap and pushes AUC toward 0.5 (about 0.53 in the same run). On this small, easy dataset the leakage is mild; on high-dimensional data with rare examples it is typically much larger. Regularization reduces leakage on average but gives no guarantee for the most vulnerable individual records; only DP provides a worst-case bound. Note tpr[fpr <= 0.01] is never empty because the ROC curve always starts at (0, 0).

Further reading

Go further

Sources

Fact-checked and last reviewed 2026-11-05

Stay in the loop
Prometheus OS™ · Native AI OS · Built for the future © 2025 - 2026