Attribution and Training-Data Transparency › Worked Example: A Tiny Sentiment Classifier
Language AI HandbookAll chapters To make influence estimation concrete, we will use a bag-of-words logistic regression classifier with a convex objective. Use this example to check the sign convention and see where a local approximation can disagree with a direct refit.
The choice of logistic regression is not accidental. The loss is convex, L2 provides positive curvature for the word weights, and the data provide positive curvature for the unpenalized intercept at finite fitted logits. This is precisely the regime in which the influence function derivation is on its firmest footing. If the approximation misbehaves even here, we would have reason to worry about the method in general. And if it behaves here, we get a clean baseline against which to interpret the messier deep-learning case.
Our training corpus contains short positive and negative movie reviews. The test sentence is "this movie is great." We will estimate the leave-one-out effect of each training document on the test loss. A positive effect means removing the document increases test loss, so the document is helpful for this test sentence. A negative effect means removing the document decreases test loss, so the document is harmful for this test sentence.
The positive test sentence contains both a sentiment cue, “great,” and common words such as “this” and “movie.” Two training reviews can overlap equally with the sentence while carrying opposite labels. The worked example measures whether each review lowers or raises loss on the chosen target.
Building the toy corpus
We start with a fixed vocabulary and binary bag-of-words features. Binary features keep the example simple and avoid count-scaling effects. We append a bias feature to every document vector.
PythonIn [2]Expand
import re
import pandas as pd
import torch
import torch.nn.functional as F
raw_docs = [
("i love this movie", 1),
("this movie is good", 1),
("i hate this movie", 0),
("this movie is boring", 0),
("great film love it", 1),
("bad film hate it", 0),
("wonderful story and great acting", 1),
("terrible story and bad acting", 0),
("i really love the acting", 1),
("i really hate the acting", 0),
]
def tokenize(text):
return re.findall(r"[a-z']+", text.lower())
vocab = sorted({token for text, _ in raw_docs for token in tokenize(text)})
word_to_idx = {word: i for i, word in enumerate(vocab)}
def vectorize(text):
features = torch.zeros(len(vocab), dtype=torch.float64)
for token in tokenize(text):
if token in word_to_idx:
features[word_to_idx[token]] = 1.0
return torch.cat([features, torch.ones(1, dtype=torch.float64)])
X = torch.stack([vectorize(text) for text, _ in raw_docs])
y = torch.tensor([float(label) for _, label in raw_docs], dtype=torch.float64)ConsoleOut [3]Expand
Vocabulary size: 19 Feature matrix shape: (10, 20) Positive examples: 5 Negative examples: 5
The feature matrix has one row per training document and one column per vocabulary item plus a bias column. The labels are binary: 1 for positive sentiment, 0 for negative sentiment. For a neural loss, the same local derivative requires a smooth stationary branch through the fitted point and a nonsingular risk Hessian there. Approximating the Hessian can change the numerical estimate.
One small detail matters for interpretation. The vectorize function appends a final column of ones, which is the bias. The bias is not tied to any token, so when we later regularize only the word weights, the bias remains free to absorb the base rate of positive versus negative labels. An example can still affect the fitted intercept even when it shares no words with the test sentence.
Training the classifier
We train with full-batch LBFGS and a small L2 penalty. Each step uses all ten reviews in this fixture. In larger runs, sources of variation can include minibatch sampling, shuffling, dropout where used, and nondeterministic numerical operations across devices.
Determinism is doing real work here. Each optimizer step uses the full dataset. With the same objective, initialization, optimizer settings, and numerical environment, repeated CPU runs of this fixture return the same scores. If we used stochastic minibatches, two runs could stop at different parameter estimates and produce different scores. The objective would still have the same unique minimizer if the loss, data, and penalty were held fixed. We are isolating the influence approximation from the optimization noise on purpose.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!