Sub topic 11
Reading the Model: Which Words Drive Each Class
Assume you know basic Python, NumPy, and supervised learning. You should also understand training and test sets, TF-IDF features, and logistic regression. This chapter focuses on interpreting a fitted scikit-learn model, not on proving that its explanations are causal.
What a coefficient means
A logistic regression classifier assigns one learned coefficient to each input feature. In a text model, each feature is usually a word or n-gram.
For a document represented by feature vector \(x\), the classifier computes a score from a weighted sum:
z = w_1x_1 + w_2x_2 + \cdots + w_dx_d + bHere, \(wi\) is a coefficient and \(b\) is an intercept. A positive coefficient raises the score for a class. A negative coefficient lowers it. The feature value \(xi\) is the document's TF-IDF weight for that term.
A coefficient is therefore interpreted together with the feature value:
\text{term contribution} = \text{TF-IDF value} \times \text{coefficient}A large coefficient does not guarantee a large contribution. The term must also appear in the document with a meaningful TF-IDF value.
For a multiclass model, coef_ has one row per class. Each row contains one coefficient per vocabulary feature.
| Object | Meaning |
|---|---|
| `feature_names[j]` | The term at column `j` |
| `coef_[i, j]` | The weight of that term for class `i` |
| `intercept_[i]` | The baseline score for class `i` |
| `classes_[i]` | The label represented by row `i` |
Inspecting influential terms
The following example trains a three-class model and prints the terms with the largest positive coefficients for each class.
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
documents = [
"rocket launches orbit around the planet",
"space telescope observes a distant galaxy",
"astronaut travels aboard the space station",
"the car engine needs a new tire",
"the driver repaired the vehicle brake",
"a sedan travels on the highway",
"the election campaign discussed a new policy",
"the senator proposed a government law",
"voters debated the national election",
]
labels = [
"space", "space", "space",
"autos", "autos", "autos",
"politics", "politics", "politics",
]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2)),
LogisticRegression(max_iter=1000),
)
model.fit(documents, labels)
vectorizer = model.named_steps["tfidfvectorizer"]
classifier = model.named_steps["logisticregression"]
feature_names = vectorizer.get_feature_names_out()
for row, label in enumerate(classifier.classes_):
top_indices = np.argsort(classifier.coef_[row])[-8:][::-1]
top_terms = feature_names[top_indices]
top_weights = classifier.coef_[row, top_indices]
print(f"\n{label}")
for term, weight in zip(top_terms, top_weights):
print(f"{term:20} {weight: .3f}")np.argsort returns feature positions ordered by coefficient value. Selecting the last positions gives the largest weights. Reversing them displays the strongest terms first.
With binary logistic regression, coef_[0] represents the positive direction for classes_[1]. A positive value supports the second class, while a negative value supports the first class. With three or more classes, each row describes that class's score relative to the others.
Reading coefficients carefully
A high positive weight means that a term helps distinguish a class from competing classes in the training data. It does not mean that the term defines the class in every context.
For example, the word rocket may strongly support space, while engine supports autos. A common word such as the usually receives little useful weight because it appears across many documents. TF-IDF already reduces the influence of terms that occur in many documents.
Negative coefficients are useful too. A term with a strongly negative weight for space may provide evidence for autos or politics. In a multiclass model, inspect the same term across rows to see where its weight is strongest.
Coefficients and individual predictions
Global coefficients show which features generally distinguish a class. To explain one prediction, calculate each feature's local contribution. For a linear model, multiply the document's TF-IDF row by the classifier's coefficient row.
This distinction matters. A term can have a large global coefficient but contribute nothing to a document that does not contain it. Conversely, several moderate terms can combine to produce a strong prediction.
Common interpretation errors
- Comparing coefficient values across differently trained models can be misleading. Vocabulary, preprocessing, regularization, and data size all affect them.
- Treating coefficients as probabilities is incorrect. A coefficient is a weight, not a confidence value.
- Reading only the largest positive terms misses evidence against a class.
- Assuming a word causes a label confuses correlation with causation.
- Ignoring n-grams can hide useful phrases such as
space stationorbrake failure.
Exercise
If a term has a coefficient of 2.0 but a document's TF-IDF value for that term is 0, how much does that term contribute to the document's score?
Show answer
It contributes 0 because the contribution is the coefficient multiplied by the document's TF-IDF value.