6.3.10Interpretability & Explainability

Counterfactual explanations

2,456 words11 min readdifficulty · medium1 backlinks

What ARE Counterfactual Explanations?

Why these three criteria?

  • Proximity: If changes are huge, the explanation isn't useful ("To get approved, become a different person").
  • Validity: f(x)f(\mathbf{x}') must actually produce yy' (not just be close).
  • Plausibility: x\mathbf{x}' must be realistic (age can't be negative, you can't "uncomplete" a degree).

HOW to Generate Counterfactuals

Derivation from First Principles

Problem setup: We have xRd\mathbf{x} \in \mathbb{R}^d and black-box f:Rd{0,1}f: \mathbb{R}^d \to \{0,1\} with f(x)=0f(\mathbf{x}) = 0 (loan denied). We want x\mathbf{x}' where f(x)=1f(\mathbf{x}') = 1 (approved).

Step 1: Define the loss function

We need to balance three competing goals:

L(x)=xx1sparsity+λhinge(f(x))prediction loss+γdmanifold(x)realism\mathcal{L}(\mathbf{x}') = \underbrace{\|\mathbf{x}' - \mathbf{x}\|_1}_{\text{sparsity}} + \lambda \underbrace{\text{hinge}(f(\mathbf{x}'))}_{\text{prediction loss}} + \gamma \underbrace{d_{\text{manifold}}(\mathbf{x}')}_{\text{realism}}

Why each term?

  1. L1L_1 distance (xx1\|\mathbf{x}' - \mathbf{x}\|_1): Encourages changing few features. L1L_1 gives sparse solutions (many components stay at zero change). Why not L2L_2? L2=(xixi)2L_2 = \sqrt{\sum (x_i' - x_i)^2} spreads change across many features; L1=xixiL_1= \sum |x_i' - x_i| concentrates it.

  2. Hinge loss on prediction: For binary classifier outputing probability p=f(x)p = f(\mathbf{x}'): hinge(p)=max(0,0.5p)\text{hinge}(p) = \max(0, 0.5 - p) This is zero when p>0.5p > 0.5 (desired class), positive otherwise. Why hinge? Differentiable, pushes pp past decision boundary.

  3. Manifold distance: Penalizes unrealistic combinations. Could use:

    • Distance to nearest training point: minxitrainxxi\min_{\mathbf{x}_i \in \text{train}} \|\mathbf{x'} - \mathbf{x}_i\|
    • VAE reconstruction error: VAE-decode(VAE-encode(x))x\|\text{VAE-decode}(\text{VAE-encode}(\mathbf{x}')) - \mathbf{x}'\|
    • Feature validity constraints (age 0\geq 0, categorical levels)

Step 2: Optimization

Gradient-based (Wachter et al. 2017): x(t+1)=x(t)αxL(x(t))\mathbf{x}'^{(t+1)} = \mathbf{x}'^{(t)} - \alpha \nabla_{\mathbf{x}'} \mathcal{L}(\mathbf{x}'^{(t)})

Start with x(0)=x\mathbf{x}'^{(0)} = \mathbf{x}, iterate until f(x)=yf(\mathbf{x}') = y' or max steps.

For categorical features: Use one-hot encoding, then round to nearest valid category after optimization.

For constraints (e.g., age 18\geq 18): Project x\mathbf{x}' onto feasible set after each step: xclip(x,loweri,upperi) for each feature i\mathbf{x}' \leftarrow \text{clip}(\mathbf{x}', \text{lower}_i, \text{upper}_i) \text{ for each feature } i



WHY This Works: The Geometry of Decision Boundaries

Consider a linear classifier: f(x)=sign(wx+b)f(\mathbf{x}) = \text{sign}(\mathbf{w}^\top \mathbf{x} + b).

The decision boundary is wx+b=0\mathbf{w}^\top \mathbf{x} + b = 0. If x\mathbf{x} is on the negative side, the closest point on the boundary is: xboundary=xwx+bw2w\mathbf{x}_{\text{boundary}} = \mathbf{x} - \frac{\mathbf{w}^\top \mathbf{x} + b}{\|\mathbf{w}\|^2} \mathbf{w}

Derivation: We want to minimize xx2\|\mathbf{x}' - \mathbf{x}\|^2 subject to wx+b=0\mathbf{w}^\top \mathbf{x}' + b = 0. Use Lagrange multipliers: L=xx2+μ(wx+b)\mathcal{L} = \|\mathbf{x}' - \mathbf{x}\|^2 + \mu(\mathbf{w}^\top \mathbf{x}' + b)

Take xL=2(xx)+μw=0    x=xμ2w\nabla_{\mathbf{x}'} \mathcal{L} = 2(\mathbf{x}' - \mathbf{x}) + \mu \mathbf{w} = 0 \implies \mathbf{x}' = \mathbf{x} - \frac{\mu}{2}\mathbf{w}.

Substitute into constraint: w(xμ2w)+b=0    μ=2(wx+b)w2\mathbf{w}^\top(\mathbf{x} - \frac{\mu}{2}\mathbf{w}) + b = 0 \implies \mu = \frac{2(\mathbf{w}^\top \mathbf{x} + b)}{\|\mathbf{w}\|^2}.

Thus: x=xwx+bw2w\mathbf{x}' = \mathbf{x} - \frac{\mathbf{w}^\top \mathbf{x} + b}{\|\mathbf{w}\|^2}\mathbf{w}. ✓

For neural networks: The boundary is nonlinear, so we use gradient descent to "walk toward" it.




Methods for Generating Counterfactuals

1. Gradient-Based (Wachter et al.)

Algorithm:

Initialize x' = x
for t = 1 to max_iter:
    loss = ||x' - x||₁ + λ·hinge(f(x')) + γ·plausibility(x')
    x' = x' - α·∇(loss)
    x' = project_to_valid(x')  # enforce constraints
    if f(x') == y_target: break
return x'

Pros: Fast, works with any differentiable model. Cons: Can find adversarial (implausible) examples.

2. DiCE (Diverse Counterfactual Explanations)

Idea: Generate multiple diverse counterfactuals, not just one.

Why? Users want options: "Either increase income by $10k OR improve credit score by 40 points."

Method: Add diversity term to loss: L=i=1kxix1+λihinge(f(xi))γi<jxixj1\mathcal{L} = \sum_{i=1}^k \|\mathbf{x}_i' - \mathbf{x}\|_1 + \lambda \sum_i \text{hinge}(f(\mathbf{x}_i')) - \gamma \sum_{i<j} \|\mathbf{x}_i' - \mathbf{x}_j'\|_1

The last term penalizes counterfactuals being similar to each other. We want x1,x2,\mathbf{x}_1', \mathbf{x}_2', \ldots to be far apart.

3. FACE (Feasible and Actionable Counterfactuals)

Adds causal constraints: Some features can't change (race, gender) or can only increase (education level).

Directed acyclic graph (DAG) GG encodes causal structure. Only allow changes consistent with GG.




Evaluation Metrics for Counterfactuals

How do we measure counterfactual quality?

Metric Formula Desirable Value
Validity 1f(x)=y\mathbb{1}_{f(\mathbf{x}') = y'} 1 (must flip prediction)
Proximity xx1\|\|\mathbf{x}' - \mathbf{x}\|\|_1 Small (few changes)
Sparsity {i:xixi}\|\{i : x_i' \neq x_i\}\| Small (few features changed)
Plausibility minxitrainxxi\min_{\mathbf{x}_i \in \text{train}} \|\mathbf{x}' - \mathbf{x}_i\|\| Small (close to training data)
Diversity (for sets) 1k(k1)i<jxixj\frac{1}{k(k-1)}\sum_{i<j} \|\|\mathbf{x}_i' - \mathbf{x}_j'\|\| Large (different options)

Trade-offs: Proximity vs. plausibility (closest counterfactual might be unrealistic). Sparsity vs. validity (changing1 feature might not suffice).


Recall Explain to a 12-Year-Old

Imagine you applied to a club and got rejected. You ask, "Why?" They say, "Because reasons." Not helpful!

Now imagine they say: "If you had2 more friends already in the club, you'd be accepted." That's a counterfactual—it tells you exactly what to change to get in.

Counterfactual explanations for AI are the same: the computer says "You were rejected for a loan. But if your income was $5k higher, you'd be approved." It's not explaining its whole decision process—it's giving you a specific action you can take.

Why is this better than "Your income was important"? Because "important" doesn't tell you how much to change it. The counterfactual gives you a concrete goal.



Connections LIME: Both provide local explanations, but LIME approximates with linear model, counterfactuals show specific input changes

  • SHAP: SHAP explains "why this prediction?", counterfactuals explain "what to change?"
  • Adversarial Examples: Counterfactuals are "good" adversarial examples (realistic, interpretable); adversarials are "bad" (minimal imperceptible noise)
  • Causal Inference: Counterfactuals respect causal structure (do-calculus), unlike correlation-based methods
  • Recourse: Algorithmic recourse = actionable counterfactuals subject to constraints (cost, feasibility)
  • Model Debugging: Out-of-distribution counterfactuals reveal model flaws and biases

#flashcards/ai-ml

What are the three key properties a counterfactual explanation must satisfy? :: (1) Validity: f(x)=yf(\mathbf{x}') = y' (different prediction), (2) Proximity: x\mathbf{x}' is close to x\mathbf{x} (minimal change), (3) Plausibility: x\mathbf{x}' is realistic/actionable

Why do we use L1L_1 norm instead of L2L_2 norm for counterfactual proximity in tabular data?
L1=xixiL_1 = \sum |x_i' - x_i| encourages sparse changes (few features modified), while L2=(xixi)2L_2 = \sqrt{\sum (x_i' - x_i)^2} spreads small changes across many features. For interpretability, we want to change as few features as possible.

Write the optimization objective for generating a counterfactual x\mathbf{x}' from x\mathbf{x} :: $$\min_{\mathbf{x}'} |\mathbf{x}' - \mathbf{x}|1 + \lambda \cdot \text{hinge}(f(\mathbf{x}')) + \gamma \cdot d{\text{manifold}}(\mathbf{x}') \text{ where the three terms balance proximity, prediction validity, and realism.}

What is the "actionability" problem in counterfactual explanations?
Some features are immutable (age, race, past events) or difficult to change. A counterfactual suggesting "change your age from 25 to 45" is mathematically valid but useless to the user. Solution: mark immutable features with infinite cost or hard constraints.

How does DiCE (Diverse Counterfactual Explanations) differ from single-counterfactual methods? :: DiCE generates multiple diverse counterfactuals by adding a diversity term -\gamma \sum_{i<j} |\mathbf{x}_i' - \mathbf{x}_j'| that penalizes similarity between counterfactuals. This gives users options: "Either increase income OR improve credit score."

For a linear classifier f(\mathbf{x}) = \text{sign}(\mathbf{w}^\top \mathbf{x} + b), what is the closest point on the decision boundary to \mathbf{x}? :::xboundary=xwx+bw2w\mathbf{x}_{\text{boundary}} = \mathbf{x} - \frac{\mathbf{w}^\top \mathbf{x} + b}{\|\mathbf{w}\|^2} \mathbf{w} This is derived by minimizing xx2\|\mathbf{x}' - \mathbf{x}\|^2 subject to wx+b=0\mathbf{w}^\top \mathbf{x}' + b = 0 using Lagrange multipliers.

What is the plausibility constraint in counterfactual generation and how is it enforced?
Plausibility ensures x\mathbf{x}' lies in the data manifold (realistic). Enforced by: (1) distance to nearest training point, (2) VAE reconstruction error, (3) feature validity constraints (e.g., age 0\geq 0), or (4) generating x=G(z)\mathbf{x}' = G(\mathbf{z}) through a generative model.
Why are counterfactuals more actionable than SHAP or LIME explanations?
SHAP/LIME explain "which features contributed to the prediction" (attribution), while counterfactuals specify "change feature X from value A to value B for outcome Y" (prescription). Counterfactuals directly answer "what should I do?" making them more actionable for end users.

Concept Map

answers

provides

requires

requires

requires

encoded by

encoded by

encoded by

term of

term of

term of

minimized in

yields

Counterfactual explanation

What minimal change flips prediction

Actionable and contrastive

Proximity - close to x

Validity - different prediction

Plausibility - on data manifold

Optimization loss function

L1 distance - sparsity

Hinge loss on prediction

Manifold distance - realism

Minimize loss to find x prime

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Counterfactual explanations ka matlab hai: "Agar aapne input mein yeh chota sa change kiya hota, toh model ka decision ulta ho jata." Jaise agar loan rejecthua, toh system bolega: "Agar aapki salary45k ke bajaye 52k hoti, toh approve ho jata." Yeh explanation sirf bata nahi ki kya importantha—yeh directly action plan deta hai ki kya karna hai.

Teen important chezein honi chahiye har counterfactual mein: (1) Close* – original input se bahut zyada change nahi, (2) Correct – nayi input pe prediction sach mein flip honi chahiye, (3) Credible – realistic change hona chahiye, impossible nahi (jaise "age 25 se 45 karo" bilkul bekar explanation hai, kyunki age toh change nahi ho sakti). Hamara optimization formula L1L_1 distance use karta hai taki kam se kam features change hon (sparse solution), aur sath mein ek penalty term hota hai jo check karta hai ki naya input training data jaisa realistic hai ya nahi.

Counterfactuals kafi powerful hain kyunki yeh human thinking ke pas hain—hum naturally sochte hain "agar maine yeh kiya hota toh..." Aur users ke liye actionable hote hain: LIME ya SHAP sirf batate hain "income importantha," lekin counterfactual kehta hai "income 7k aur badha do." Isse users ko clear direction milta hai. DiCE method multiple diverse counterfactuals deta hai—matlab options milte hain: "Ya toh income badhao YA credit score improve karo." Yeh flexibility real-world mein bahut kaam ati hai.

Go deeper — visual, from zero

Test yourself — Interpretability & Explainability

Connections