Lecture 4 — Membership inference on a 2-D private model¶

A utility trains a model that predicts EV ownership from two features of each household's smart-meter data and publishes it. An attacker wants to know whether one target household was in the training set. It knows every other household $D'$ and the target's own record $z$.

The attack in three steps

  1. The attacker trains the two models the utility could have trained: $\theta_{\text{in}}=\theta^*(D'\cup\{z\})$ and $\theta_{\text{out}}=\theta^*(D')$, two points in the plane.
  2. The utility secretly trains one of them and publishes it, with or without DP noise.
  3. The attacker checks which of its two points the published model is closer to, and guesses "in" or "out".
Part
1 Data: 300 households, two features each
2 The utility trains the EV model (no privacy)
3 The utility publishes it privately (output perturbation)
4 The attacker trains its two candidate models
5 One round of the attack, in the parameter plane
6 Many rounds: how often is the attacker right?
7 Privacy versus accuracy

Setup (once). In Julia, run using Pkg; Pkg.add(["IJulia", "Plots", "LaTeXStrings"]). Then open this notebook in Jupyter or VS Code, choose the Julia kernel, and run the cells from top to bottom.

In [1]:
using LinearAlgebra, Random, Statistics, Printf
using Plots, LaTeXStrings
default(size = (520, 400), legendfontsize = 8, guidefontsize = 11, titlefontsize = 10)

# ------------------------------------------------ settings (change these and rerun)
SEED         = 2
N_HOUSEHOLDS = 300        # training set size n (small, so that one household visibly moves the model)
LAMBDA       = 0.1        # regularization λ
DELTA        = 1e-6       # privacy parameter δ
EPSILONS     = [0.5, 1]       # privacy budgets to compare
FIGURE_DIR   = joinpath(homedir(), "Desktop")   # every figure is saved on your Desktop as .png and .pdf

Random.seed!(SEED)
mkpath(FIGURE_DIR)

"Save a figure as PNG and PDF in FIGURE_DIR, and return it so the notebook shows it."
function save_figure(fig, name)
    for ext in ("png", "pdf")
        savefig(fig, joinpath(FIGURE_DIR, "$name.$ext"))
    end
    println("saved ", joinpath(FIGURE_DIR, name), ".png and .pdf")
    return fig
end;

Part 1 — Data: the surveyed households¶

Each household has two features: its average evening peak (kW) and its average overnight energy (kWh). EV owners have higher values of both, because they charge in the evening and at night. The label y is the survey answer: +1 (EV) or -1 (no EV). About 5% of the answers are wrong.

In [2]:
"""
    make_households(m)

Simulate `m` households. Returns X_raw (m × 2: evening peak in kW, overnight energy in kWh)
and the survey labels y (+1 = EV, -1 = no EV).
"""
function make_households(m)
    X_raw = zeros(m, 2)
    y = zeros(m)
    for i in 1:m
        has_ev = rand() < 0.3
        size_i = exp(0.3 * randn())                                  # bigger and smaller homes
        peak  = size_i * 1.5 * (1 + 0.25randn()) + (has_ev ? 1 + 2rand() : 0.0)
        night = size_i * 3.0 * (1 + 0.25randn()) + (has_ev ? 2 + 6rand() : 0.0)
        X_raw[i, :] = [peak, night]
        y[i] = has_ev ? 1.0 : -1.0
        if rand() < 0.05                                             # wrong survey answer
            y[i] = -y[i]
        end
    end
    return X_raw, y
end;

The analysis of output perturbation needs $\|x_i\|_2\le1$. We subtract a public reference household, divide by a public scale, and clip every household to length at most 1.

In [3]:
public_sample = make_households(50_000)[1]                      # public data, not the training set
reference = vec(mean(public_sample, dims = 1))
scale = quantile([norm(r) for r in eachrow(public_sample .- reference')], 0.95)

function features(X_raw)
    X = (X_raw .- reference') ./ scale
    for i in 1:size(X, 1)
        X[i, :] ./= max(1, norm(X[i, :]))                        # clip to length 1
    end
    return X
end

X_raw, y = make_households(N_HOUSEHOLDS)                         # the training set
X = features(X_raw)
X_test_raw, y_test = make_households(20_000)                     # fresh households, to measure accuracy
X_test = features(X_test_raw)

ev = y .== 1
fig = scatter(X_raw[.!ev, 1], X_raw[.!ev, 2], color = :orange, ms = 3, alpha = 0.7, label = "survey: no EV",
              xlabel = "evening peak (kW)", ylabel = "overnight energy (kWh)", title = "training set (feature space)",
              legend = :topleft)
scatter!(fig, X_raw[ev, 1], X_raw[ev, 2], color = :steelblue, ms = 3, alpha = 0.7, label = "survey: EV")
save_figure(fig, "fig1_training_data")
saved /root/Desktop/fig1_training_data.png and .pdf
Out[3]:
No description has been provided for this image

Part 2 — The utility trains the EV model (no privacy)¶

Regularized logistic regression with two weights: $$ J(\theta;D)=\frac1n\sum_{i=1}^n\ln\big(1+e^{-y_i\theta^\top x_i}\big)+\frac\lambda2\|\theta\|_2^2, \qquad \theta^*(D)=\arg\min_\theta J(\theta;D)\in\mathbb R^2 . $$ Newton's method finds the exact minimizer, as output perturbation assumes.

In [4]:
"""
    train_model(X, y; lambda = LAMBDA, start = zeros(2))

Return the exact minimizer θ* of the regularized logistic loss.
"""
function train_model(X, y; lambda = LAMBDA, start = zeros(size(X, 2)))
    theta = copy(start)
    n = size(X, 1)
    for step in 1:30
        p = 1 ./ (1 .+ exp.(y .* (X * theta)))           # weight of each household's gradient
        gradient = -(X' * (y .* p)) / n + lambda * theta
        hessian = X' * (p .* (1 .- p) .* X) / n + lambda * I
        theta -= hessian \ gradient
    end
    return theta
end

"Fraction of households whose EV status the model predicts correctly."
accuracy(theta, X, y) = mean(sign.(X * theta) .== y);
In [5]:
theta_star = train_model(X, y)
@printf("trained model θ* = (%.3f, %.3f),  test accuracy %.3f\n", theta_star..., accuracy(theta_star, X_test, y_test))
trained model θ* = (0.454, 1.016),  test accuracy 0.875

Part 3 — The utility publishes the model privately¶

Output perturbation (parts (b)–(c) of the exercise):

  • one household moves $\theta^*$ by at most $\Delta_2=\dfrac{2}{n\lambda}$;

  • the published model is $\tilde\theta=\theta^*+\mathcal N(0,\sigma^2 I_2)$.

  • the Gaussian mechanism of part (c) adds noise $\sigma=\dfrac{\Delta_2\sqrt{2\ln(1.25/\delta)}}{\varepsilon}$, valid for $\varepsilon\le1$.

In [6]:
sensitivity = 2 / (N_HOUSEHOLDS * LAMBDA)

"Noise level of the Gaussian mechanism for privacy budget ε (part (c))."
noise_level(epsilon; delta = DELTA) = sensitivity * sqrt(2 * log(1.25 / delta)) / epsilon

"Publish a model: add N(0, σ² I) noise (σ = 0 publishes the exact model)."
publish(theta, sigma) = theta .+ sigma .* randn(length(theta));
In [7]:
@printf("sensitivity Δ2 = 2/(nλ) = %.4f\n\n", sensitivity)
println("    ε        σ      model test accuracy")
for eps in EPSILONS
    s = noise_level(eps)
    acc = mean(accuracy(publish(theta_star, s), X_test, y_test) for _ in 1:500)
    @printf("%5g   %.4f        %.3f\n", eps, s, acc)
end
@printf("  no noise            %.3f\n", accuracy(theta_star, X_test, y_test))
sensitivity Δ2 = 2/(nλ) = 0.0667

    ε        σ      model test accuracy
  0.5   0.7065        0.819
    1   0.3533        0.873
  no noise            0.875

With only 300 households, the noise is comparable to $\theta^*$ itself, so the private model loses some accuracy; halving $\varepsilon$ doubles the noise.

Part 4 — The attacker trains its two candidate models¶

Target. The household the model fits worst, typically a wrong survey answer: the model has to bend toward it, so it is the most exposed household.

The attacker knows all other households and the target's record, so it trains both models the utility might have trained. Each is a point $(\theta_1,\theta_2)$.

In [8]:
losses = log1p.(exp.(-y .* (X * theta_star)))
target = argmax(losses)
others = [i for i in 1:N_HOUSEHOLDS if i != target]

theta_in  = train_model(X, y)                                         # with the target
theta_out = train_model(X[others, :], y[others]; start = theta_in)    # without it
gap = norm(theta_in - theta_out)

@printf("target household %d: survey answer %+d, evening peak %.2f kW, overnight %.2f kWh\n",
        target, Int(y[target]), X_raw[target, :]...)
@printf("theta_in  = (%.4f, %.4f)\n", theta_in...)
@printf("theta_out = (%.4f, %.4f)\n", theta_out...)
@printf("distance between them: %.4f   (at most 2/(nλ) = %.4f)\n", gap, sensitivity)
target household 76: survey answer -1, evening peak 5.62 kW, overnight 11.06 kWh
theta_in  = (0.4544, 1.0157)
theta_out = (0.4645, 1.0328)
distance between them: 0.0198   (at most 2/(nλ) = 0.0667)

Part 5 — One round of the attack, in the parameter plane¶

The whole attack is one comparison: is the published model closer to theta_in or to theta_out?

In [9]:
function attacker_guess(published, theta_in, theta_out)
    distance_to_in  = norm(published - theta_in)
    distance_to_out = norm(published - theta_out)
    guess_in = distance_to_in < distance_to_out
    return guess_in, distance_to_in, distance_to_out
end

function play_one_round(sigma)
    target_in = rand() < 0.5                               # the utility's secret coin
    trained = target_in ? theta_in : theta_out
    published = publish(trained, sigma)
    guess_in, d_in, d_out = attacker_guess(published, theta_in, theta_out)
    return (; target_in, published, guess_in, d_in, d_out)
end

in_or_out(b) = b ? "IN" : "OUT";

The picture. The axes are the two weights of the model, $\theta_1$ and $\theta_2$. The dashed line is where the two distances are equal: on the blue side the published model is closer to $\theta_{\text{in}}$, on the orange side closer to $\theta_{\text{out}}$. The dotted circles show $1\sigma$ and $2\sigma$ of the noise around each candidate.

In [10]:
circle(c, r) = (c[1] .+ r .* cos.(range(0, 2pi, length = 100)), c[2] .+ r .* sin.(range(0, 2pi, length = 100)))

function plot_parameter_plane(sigma, title; published = nothing, clouds = nothing, legend = :outerright,
                              label_size = 10)
    mid = (theta_in + theta_out) / 2
    d = (theta_in - theta_out) / gap                       # from theta_out to theta_in
    v = [-d[2], d[1]]                                      # along the dashed line
    W = max(2gap, 3.5sigma)
    p = plot(xlims = (mid[1] - W, mid[1] + W), ylims = (mid[2] - W, mid[2] + W), aspect_ratio = :equal,
             legend = legend, title = title, xlabel = L"\theta_1", ylabel = L"\theta_2")
    plot!(p, [mid[1] - 3W * v[1], mid[1] + 3W * v[1]], [mid[2] - 3W * v[2], mid[2] + 3W * v[2]],
          color = :black, ls = :dash, lw = 1.5, label = L"\textrm{equal\ distance}")
    # label each side of the dashed line in the corner of the plot that lies deepest on that side
    corners = [mid .+ W .* [sx, sy] for sx in (-1, 1), sy in (-1, 1)][:]
    side = [dot(c - mid, d) for c in corners]
    c_in, c_out = corners[argmax(side)], corners[argmin(side)]
    for (c, label, col) in ((c_in, L"\textrm{closer\ to}\ \theta_{\textrm{in}}", :steelblue),
                            (c_out, L"\textrm{closer\ to}\ \theta_{\textrm{out}}", :orange))
        pos = mid .+ 0.92 .* (c - mid)
        annotate!(p, pos[1], pos[2], text(label, col, label_size, c[1] > mid[1] ? :right : :left,
                                          c[2] > mid[2] ? :top : :bottom))
    end
    if sigma > 0
        for k in (1, 2)
            plot!(p, circle(theta_out, k * sigma)..., color = :orange, ls = :dot,
                  label = k == 1 ? L"\textrm{noise\ around}\ \theta_{\textrm{out}}\ (1\sigma, 2\sigma)" : "")
            plot!(p, circle(theta_in, k * sigma)..., color = :steelblue, ls = :dot,
                  label = k == 1 ? L"\textrm{noise\ around}\ \theta_{\textrm{in}}\ (1\sigma, 2\sigma)" : "")
        end
    end
    if clouds !== nothing                                  # many releases: (target in, target out)
        rel_in, rel_out = clouds
        scatter!(p, first.(rel_out), last.(rel_out), color = :orange, ms = 2.5, alpha = 0.4, msw = 0,
                 label = L"\textrm{released\ models,\ target\ out}")
        scatter!(p, first.(rel_in), last.(rel_in), color = :steelblue, ms = 2.5, alpha = 0.4, msw = 0,
                 label = L"\textrm{released\ models,\ target\ in}")
    end
    if published !== nothing                               # one release, with its two distances
        plot!(p, [published[1], theta_in[1]], [published[2], theta_in[2]], color = :steelblue, lw = 2,
              label = L"\textrm{distance\ to}\ \theta_{\textrm{in}}")
        plot!(p, [published[1], theta_out[1]], [published[2], theta_out[2]], color = :orange, lw = 2,
              label = L"\textrm{distance\ to}\ \theta_{\textrm{out}}")
        scatter!(p, [published[1]], [published[2]], color = :white, markerstrokecolor = :black,
                 markerstrokewidth = 2, ms = 9, label = L"\textrm{published\ model}\ \tilde{\theta}")
    end
    scatter!(p, [theta_out[1]], [theta_out[2]], color = :orange, ms = 6,
             label = L"\theta_{\textrm{out}}\ \textrm{(trained\ without\ target)}")
    scatter!(p, [theta_in[1]], [theta_in[2]], color = :steelblue, ms = 6,
             label = L"\theta_{\textrm{in}}\ \textrm{(trained\ with\ target)}")
    return p
end

function show_round(sigma, name)
    game = play_one_round(sigma)
    @printf("distance to theta_in  = %.4f\n", game.d_in)
    @printf("distance to theta_out = %.4f\n", game.d_out)
    println("attacker guesses ", in_or_out(game.guess_in), ", truth is ", in_or_out(game.target_in),
            game.guess_in == game.target_in ? "  -> correct" : "  -> wrong")
    title = "$name: guess $(in_or_out(game.guess_in)), truth $(in_or_out(game.target_in))"
    plot_parameter_plane(sigma, title; published = game.published)
end

"Play one round, plot it with a legend on the right, and save the figure."
function show_and_save_round(sigma, name, file)
    fig = show_round(sigma, name)
    plot!(fig, size = (800, 430), left_margin = 4Plots.mm, bottom_margin = 4Plots.mm)
    save_figure(fig, file)
end;

Round with the exact model ($\sigma=0$)¶

The white circle is the published model, blue and orange dots are $\theta_{\text{in}}$ and $\theta_{\text{out}}$. Run the cell several times: each run is a new coin flip.

In [11]:
show_and_save_round(0.0, "exact model", "fig2_round_exact")
distance to theta_in  = 0.0000
distance to theta_out = 0.0198
attacker guesses IN, truth is IN  -> correct
saved /root/Desktop/fig2_round_exact.png and .pdf
Out[11]:
No description has been provided for this image

The published model sits exactly on $\theta_{\text{in}}$ or $\theta_{\text{out}}$: the attacker is always right.

Round with strong privacy ($\varepsilon=0.5$)¶

In [12]:
show_and_save_round(noise_level(0.5), "ε = 0.5", "fig3_round_eps0.5")
distance to theta_in  = 1.7726
distance to theta_out = 1.7924
attacker guesses IN, truth is IN  -> correct
saved /root/Desktop/fig3_round_eps0.5.png and .pdf
Out[12]:
No description has been provided for this image

The noise circles are much larger than the distance between the two candidates, which now look like a single point. The published model lands far from both, at almost the same distance, and the side of the dashed line it lands on is decided by the noise.

Round with $\varepsilon=1$¶

In [13]:
show_and_save_round(noise_level(1), "ε = 1", "fig4_round_eps1")
distance to theta_in  = 0.9419
distance to theta_out = 0.9337
attacker guesses OUT, truth is IN  -> wrong
saved /root/Desktop/fig4_round_eps1.png and .pdf
Out[13]:
No description has been provided for this image

Twice the privacy budget halves the noise, but the circles are still far larger than the distance between the candidates: the published model still cannot tell them apart.

Part 6 — Many rounds: how often is the attacker right?¶

We play many rounds and count how often the guess is correct. DP limits any attacker's accuracy to $\dfrac{e^\varepsilon+\delta}{1+e^\varepsilon}$.

In [14]:
function attack_accuracy(sigma; rounds = 20_000)
    correct = 0
    for r in 1:rounds
        game = play_one_round(sigma)
        correct += (game.guess_in == game.target_in)
    end
    return correct / rounds
end

println("                  σ       attacker   DP bound")
@printf("exact model    %.4f      %.3f        -\n", 0.0, attack_accuracy(0.0))
for eps in EPSILONS
    s = noise_level(eps)
    @printf("ε = %-5g      %.4f      %.3f      %.3f\n", eps, s, attack_accuracy(s), (exp(eps) + DELTA) / (1 + exp(eps)))
end
                  σ       attacker   DP bound
exact model    0.0000      1.000        -
ε = 0.5        0.7065      0.505      0.622
ε = 1          0.3533      0.508      0.731

What the attacker sees over many rounds. Each dot is one published model: blue when the target was in, orange when it was out. Each panel has its own scale.

In [15]:
function release_clouds(sigma; rounds = 300)
    rel_in  = [publish(theta_in, sigma) for _ in 1:rounds]
    rel_out = [publish(theta_out, sigma) for _ in 1:rounds]
    return rel_in, rel_out
end

panels = [plot_parameter_plane(0.0, "exact model"; clouds = release_clouds(0.0), legend = false, label_size = 11)]
for eps in EPSILONS
    s = noise_level(eps)
    push!(panels, plot_parameter_plane(s, @sprintf("ε = %g", eps); clouds = release_clouds(s), legend = false,
                                       label_size = 11))
end

# one shared legend under the panels
legend_panel = plot(framestyle = :none, legend = :top, legend_columns = 3, legendfontsize = 11,
                    foreground_color_legend = nothing)
scatter!(legend_panel, [NaN], [NaN], color = :orange, ms = 6, label = L"\theta_{\textrm{out}}\ \textrm{(trained\ without\ target)}")
scatter!(legend_panel, [NaN], [NaN], color = :orange, ms = 3, alpha = 0.6, msw = 0, label = L"\textrm{released\ models,\ target\ out}")
plot!(legend_panel, [NaN], [NaN], color = :orange, ls = :dot, label = L"\textrm{noise\ around}\ \theta_{\textrm{out}}\ (1\sigma, 2\sigma)")
scatter!(legend_panel, [NaN], [NaN], color = :steelblue, ms = 6, label = L"\theta_{\textrm{in}}\ \textrm{(trained\ with\ target)}")
scatter!(legend_panel, [NaN], [NaN], color = :steelblue, ms = 3, alpha = 0.6, msw = 0, label = L"\textrm{released\ models,\ target\ in}")
plot!(legend_panel, [NaN], [NaN], color = :steelblue, ls = :dot, label = L"\textrm{noise\ around}\ \theta_{\textrm{in}}\ (1\sigma, 2\sigma)")
plot!(legend_panel, [NaN], [NaN], color = :black, ls = :dash, lw = 1.5, label = L"\textrm{equal\ distance}")

n_panels = length(panels)
fig = plot(panels..., legend_panel, layout = @layout([grid(1, n_panels); l{0.2h}]), size = (1250, 540),
           titlefontsize = 11, guidefontsize = 12, tickfontsize = 9,      # 10% larger than the defaults
           left_margin = 9Plots.mm, bottom_margin = 3Plots.mm)
save_figure(fig, "fig5_release_clouds")
saved /root/Desktop/fig5_release_clouds.png and .pdf
Out[15]:
No description has been provided for this image

What to notice.

  • Exact model: all blue releases sit on $\theta_{\text{in}}$ and all orange ones on $\theta_{\text{out}}$, on opposite sides of the dashed line. The attacker is always right.
  • $\varepsilon=0.5$: the two clouds lie on top of each other. Half of each cloud is on the wrong side of the line, so the attacker is right only about half the time.
  • $\varepsilon=1$: the clouds are half as wide but still lie on top of each other, and the attacker is still right only about half the time.

Whatever $n$ is, the distance between $\theta_{\text{in}}$ and $\theta_{\text{out}}$ is at most $\Delta_2$, and the noise $\sigma$ is proportional to $\Delta_2$. So for strong privacy the two clouds always overlap almost completely.

Part 7 — Privacy versus accuracy¶

Smaller $\varepsilon$ means more noise $\sigma$: better protection, but a less accurate model. We sweep $\varepsilon$ from $0.05$ to $1$ and track

  • the model's test accuracy, averaged over 300 noisy releases;
  • the attacker's accuracy, simulated with 20,000 rounds of the game of Part 6.
In [16]:
eps_grid   = exp10.(range(log10(0.05), 0, length = 21))       # ε from 0.05 to 1
sigma_grid = [noise_level(eps) for eps in eps_grid]
model_acc  = [mean(accuracy(publish(theta_star, s), X_test, y_test) for _ in 1:300) for s in sigma_grid]
attack_acc = [attack_accuracy(s; rounds = 20_000) for s in sigma_grid]
dp_bound   = [(exp(eps) + DELTA) / (1 + exp(eps)) for eps in eps_grid]

fig = plot(eps_grid, model_acc, xscale = :log10, lw = 2, marker = :circle, ms = 3, color = :seagreen,
           label = "model test accuracy (DP model)", xlabel = L"\textrm{privacy\ budget}\ \varepsilon",
           ylabel = "accuracy", ylims = (0.45, 1.0), legend = :topleft, size = (700, 440),
           xticks = ([0.05, 0.1, 0.2, 0.5, 1], ["0.05", "0.1", "0.2", "0.5", "1"]),
           left_margin = 4Plots.mm, bottom_margin = 4Plots.mm)
hline!(fig, [accuracy(theta_star, X_test, y_test)], color = :seagreen, ls = :dash, label = "model test accuracy (no noise)")
plot!(fig, eps_grid, attack_acc, lw = 2, color = :purple, label = "attacker accuracy (simulated)")
plot!(fig, eps_grid, dp_bound, lw = 1.5, color = :purple, ls = :dash, label = "DP bound on attacker accuracy")
hline!(fig, [0.5], color = :gray, ls = :dot, label = "coin flip")
save_figure(fig, "fig6_accuracy_vs_epsilon")
saved /root/Desktop/fig6_accuracy_vs_epsilon.png and .pdf
Out[16]:
No description has been provided for this image