Sub topic 11
Reading the model: which words drive each class
A fitted linear model can show which terms push a document toward each class. This chapter shows how to read those weights, check whether they make sense, and avoid the usual traps. It assumes you have built the TF-IDF and logistic regression pipeline from the earlier chapters and know what coef_ and regularization are.
What the coefficients mean
Logistic regression scores a document as a weighted sum of its TF-IDF values, plus an intercept. Each class has one weight per vocabulary term. In scikit-learn these weights are stored in coef_.
- For
kclasses withk > 2,coef_has shape(k, n_features). Rowibelongs toclasses_[i]. - For two classes,
coef_has shape(1, n_features). The row describes the second class inclasses_. Positive weights push toward that class, and negative weights push toward the first. - A positive weight raises the class score when the term is present. A negative weight lowers it. A weight near zero means the term has little influence.
For multiclass models, the classifier turns the per-class scores into probabilities with a softmax. A term's weight is a statement about the score of one class. It is not a probability by itself.
Listing the top terms per class
The following block is self-contained. It trains the pipeline and prints, for each class, the terms with the largest positive weights and the terms with the most negative weights.
import numpy as np
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
categories = ["sci.space", "rec.autos", "talk.politics.misc"]
remove = ("headers", "footers", "quotes")
train = fetch_20newsgroups(subset="train", categories=categories, remove=remove)
test = fetch_20newsgroups(subset="test", categories=categories, remove=remove)
model = make_pipeline(
TfidfVectorizer(sublinear_tf=True, ngram_range=(1, 2), min_df=2, stop_words="english"),
LogisticRegression(C=1.0, max_iter=1000),
)
model.fit(train.data, train.target)
vectorizer = model.named_steps["tfidfvectorizer"]
classifier = model.named_steps["logisticregression"]
feature_names = vectorizer.get_feature_names_out()
for i, label in enumerate(train.target_names):
order = np.argsort(classifier.coef_[i])
print(label)
print(" toward:", list(feature_names[order[-10:][::-1]]))
print(" away: ", list(feature_names[order[:10]]))Check classifier.classes_ against train.target_names. Both follow the sorted label order here, but if you encode labels yourself, use classifier.classes_ to map rows to labels.
Expect the "toward" lists to contain words such as space, nasa, or orbit for sci.space, and car, engine, or dealer for rec.autos. If you see mostly junk, such as email fragments, numbers, or usernames, the model has found shortcuts in the data. That is a data problem and not a modeling success.
Why the weights are comparable
TF-IDF rows are L2-normalized by default, so every feature value lies between 0 and 1. Because the features share a scale, you can compare weights across terms without standardizing. This comparison breaks if you add unscaled features such as raw document length or counts alongside TF-IDF. A feature on a larger scale will have a smaller coefficient for the same effect.
Scale also affects how regularization treats each term. The L2 penalty shrinks all weights toward zero, regardless of how informative they are. A term that appears in only a few documents has to earn its weight from limited evidence, so it often stays small.
Explaining one prediction
Global top-term lists describe the model overall. To explain a single document, multiply its TF-IDF values by the predicted class's weights. Each product is that term's contribution to the class score for that document.
doc = test.data[0]
x = vectorizer.transform([doc])
pred = int(classifier.predict(x)[0])
contrib = x.multiply(classifier.coef_[pred]).toarray().ravel()
top = np.argsort(contrib)[::-1][:8]
print("true: ", test.target_names[test.target[0]])
print("predicted:", test.target_names[pred])
for j in top:
if contrib[j] > 0:
print(f"{feature_names[j]:25s} {contrib[j]:.3f}")
print("intercept:", round(float(classifier.intercept_[pred]), 3))Only terms that appear in the document contribute, because absent terms have a TF-IDF value of zero. The full class score is the sum of all contributions plus the intercept. If the predicted class wins by a narrow margin, compare it with the runner-up class using the same method. The terms with the largest difference in contribution explain the decision.
Checking that the weights are trustworthy
Coefficients are a description of the fitted model. They are not a ranking of the most important words in the world. Several effects can make them misleading.
Correlated terms share credit
If nasa and shuttle almost always appear together, the model can split the weight between them in many ways. L2 regularization tends to spread weight evenly across correlated terms. L1 regularization tends to pick one and zero out the rest. Neither tells you which word "really" matters. With bigrams in the vocabulary, this effect is stronger, because space shuttle overlaps with both space and shuttle.
Weights change with regularization
A small C shrinks weights and favors common, reliable terms. A large C lets rare terms take large weights to fit the training set. Compare the lists at two settings to see which terms are stable.
def top_terms(C, class_index=0, n=8):
m = make_pipeline(
TfidfVectorizer(sublinear_tf=True, min_df=2, stop_words="english"),
LogisticRegression(C=C, max_iter=1000),
)
m.fit(train.data, train.target)
names = m.named_steps["tfidfvectorizer"].get_feature_names_out()
coefs = m.named_steps["logisticregression"].coef_[class_index]
return set(names[np.argsort(coefs)[-n:]])
low = top_terms(0.1)
high = top_terms(100.0)
print("stable:", sorted(low & high))
print("only at C=0.1:", sorted(low - high))
print("only at C=100:", sorted(high - low))Terms that appear in both lists are good candidates for a real signal. Terms that appear only at high C are often rare words that help fit individual training documents.
The vocabulary is fit on training data only
Terms missing from the training vocabulary have no weight. A word that is a strong signal in the real world but was dropped by min_df or stop_words will not appear in any list. Stop words in particular can carry signal. For example, pronoun use differs between writing styles. If you remove them, you cannot see their effect.
Weights are conditional on the other features
A weight is the effect of a term given all the other terms in the model. A word can have a positive weight for a class even though it appears often in other classes, if a different term explains those documents better. Do not read a weight as "how often this word occurs in this class". For that, count term frequencies per class directly.
Using coefficients to find problems
Reading weights is a debugging tool as much as an explanation tool. It often finds problems that held-out metrics miss, because the held-out set may share the same flaw as the training set.
- Leakage. Headers, footers, signatures, file paths, and IDs can reveal the label. The earlier chapters removed headers, footers, and quotes from the newsgroup posts for this reason. Remove that argument and rerun the top-term listing to see the effect. The top terms will shift to names, hostnames, and email domains.
- Duplicates. Boilerplate text that repeats across documents gets high weight if it correlates with a label.
- Artifacts of preprocessing. Tokens such as
axormaxin the newsgroups data come from encoded text. A model that relies on them is fitting noise. - Bias. In real applications, terms that name groups of people may carry large weights because of sampling in the training data. Review the top terms before deployment.
When you find a problem, fix the data or the preprocessing and retrain. Do not simply delete the term from the output.
Reading weights for binary and imbalanced problems
For a binary model, a single row covers both classes. To get a list for each class, take the largest weights for the positive class and the most negative weights for the other.
def binary_top_terms(pipeline, n=10):
names = pipeline.named_steps["tfidfvectorizer"].get_feature_names_out()
clf = pipeline.named_steps["logisticregression"]
order = np.argsort(clf.coef_[0])
return {
str(clf.classes_[1]): list(names[order[-n:][::-1]]),
str(clf.classes_[0]): list(names[order[:n]]),
}With imbalanced classes, the intercept absorbs much of the prior. Large negative intercepts for rare classes are normal. If you use class_weight="balanced", the weights and intercept change because the loss gives rare-class errors more weight. Compare lists only between models trained with the same settings.
A quick checklist
- Map rows of
coef_toclassifier.classes_, and remember that a binary model has one row. - Make sure all features share a scale before comparing weights.
- Compare top terms at more than one value of
C. - Inspect surprising terms in the raw documents.
- Use per-document contributions to explain individual predictions.
- Do not describe weights as causes or as word frequencies.
| Question | Right tool |
|---|---|
| Which terms does the model use for a class? | Sorted rows of `coef_` |
| Why did the model label this document that way? | Per-document contribution: TF-IDF value times weight |
| How often does a word occur in each class? | Direct term counts per class |
| Is a top term stable? | Compare lists across `C` values and resamples |
Exercise
A binary model has classes_ = ["ham", "spam"]. The term winner has a coefficient of +2.4 in coef_[0]. A document contains winner with a TF-IDF value of 0.2. How does this term affect the score, and which class does it favor?
Show answer
The contribution is 0.2 × 2.4 = 0.48, added to the log-odds score of the second class in classes_, which is spam. The term favors spam. A binary model has only one coefficient row, and it describes the second class. A negative weight would favor ham instead.
Exercise
You retrain the same pipeline with C=100 and the top terms for sci.space change from space, nasa, and orbit to rare names and long bigrams. What does this tell you, and what do you do?
Show answer
A large C weakens regularization, so rare terms can take large weights to fit individual training documents. The names and bigrams are likely overfitting and not general signal. Keep the lower C if cross-validated scores are as good or better, and treat only the terms that appear at both settings as stable signal.