Sub topic 6
Logistic regression on sparse features
This chapter covers how logistic regression turns a TF-IDF row into a class probability, how its solvers handle sparse data, and which edge cases cause trouble. It assumes you have read the earlier chapters on the document-term matrix and TF-IDF. It also assumes you know what a training set is, can read log and exp, and can run scikit-learn code. Regularization and the choice of C get their own chapter, so they appear here only where they affect training.
From a score to a probability
Logistic regression is a linear model. For a document with feature vector x (one TF-IDF row), it learns one weight per term and a bias, called the intercept. It computes a score:
z = w · x + b
The score z can be any real number. The sigmoid function converts it to a probability between 0 and 1:
p(class = 1) = 1 / (1 + exp(-z))
When z = 0, the probability is 0.5. A positive z favors class 1 and a negative z favors class 0. The score z is the log-odds, log(p / (1 - p)). That is why each weight is easy to read: increasing a term's TF-IDF value by one unit adds w to the log-odds.
For more than two classes, scikit-learn's default lbfgs solver fits a multinomial model. It learns one weight vector per class, computes one score z_k per class, and applies softmax: p_k = exp(z_k) / sum_j exp(z_j). The probabilities sum to 1 across classes. The predicted label is the class with the highest probability.
Why a linear model fits sparse text
A TF-IDF matrix has one column per vocabulary term. A realistic vocabulary has tens of thousands of columns, but each document uses only a few dozen of them. scikit-learn stores the matrix in a sparse format (scipy.sparse.csr_matrix) that keeps only the nonzero entries.
The dot product w · x only needs the terms that appear in the document. Scoring a document costs time proportional to its number of nonzero entries, not to the vocabulary size. Training cost likewise scales with the total number of nonzero entries in the matrix.
Linear models also suit this setting for a second reason. In a high-dimensional space with relatively few documents, classes are often close to linearly separable. A simple hyperplane often does the job, so a more flexible model has little room to improve on it.
Run this small example. It fits a binary classifier and checks the sigmoid formula by hand:
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
docs = [
"the striker scored a late goal",
"the team won the match",
"the goalkeeper saved a penalty",
"the coach praised the team after the match",
"simmer the sauce with garlic and basil",
"bake the bread in a hot oven",
"chop the onions and fry in butter",
"the recipe needs garlic and fresh basil",
]
labels = np.array([1, 1, 1, 1, 0, 0, 0, 0]) # 1 = sports, 0 = cooking
vec = TfidfVectorizer()
X = vec.fit_transform(docs)
print(type(X).__name__, X.shape, X.nnz)
print(f"density: {X.nnz / (X.shape[0] * X.shape[1]):.2%}")
clf = LogisticRegression(C=10, max_iter=1000)
clf.fit(X, labels)
print(clf.coef_.shape, clf.intercept_.shape)
new = vec.transform(["the team scored in the match"])
z = clf.decision_function(new)[0]
p_manual = 1 / (1 + np.exp(-z))
p_model = clf.predict_proba(new)[0, 1]
print(round(z, 3), round(p_manual, 3), round(p_model, 3))The last line prints the same probability twice, once from the manual sigmoid and once from predict_proba. The column [0, 1] selects the probability of class 1, because clf.classes_ is [0, 1]. The shape of coef_ is (1, n_features) for a binary problem. For a problem with K > 2 classes it is (K, n_features), with one row per class.
How the model is trained
Training finds the weights that make the labeled documents most likely. For each document the model pays a penalty called log loss:
loss = -[y * log(p) + (1 - y) * log(1 - p)]
A confident wrong prediction is penalized heavily. A confident correct one costs almost nothing. scikit-learn minimizes the following objective with the default L2 penalty:
0.5 * ||w||^2 + C * sum(loss over all documents)
The first term keeps the weights small. C sets how much the data counts relative to that penalty. A large C means weak regularization. The intercept is not penalized by lbfgs, but liblinear does penalize it.
The log loss with an L2 penalty is a convex function. It has a single global minimum, and every solver that converges reaches the same answer up to tolerance. Solver choice therefore changes speed and available options, not the model you end up with.
Choosing a solver
| Solver | Penalties | Multiclass | When to use it |
|---|---|---|---|
| `lbfgs` (default) | L2, none | Multinomial | A good first choice for small and medium problems |
| `liblinear` | L1, L2 | One-vs-rest only | Small datasets, or when you need an L1 penalty |
| `saga` | L1, L2, elastic net | Multinomial | Very large datasets, or sparse solutions with multinomial loss |
| `newton-cg` | L2, none | Multinomial | An alternative to `lbfgs`, slower on very wide matrices |
One-vs-rest trains one binary classifier per class against all the others. Its per-class scores are not tied together by softmax, so the probabilities are normalized afterwards. Multinomial training fits all classes jointly.
You can check that solvers agree on a convex problem:
for solver in ["lbfgs", "liblinear", "saga"]:
m = LogisticRegression(solver=solver, C=10, max_iter=5000, tol=1e-6)
m.fit(X, labels)
print(solver, round(float(np.linalg.norm(m.coef_)), 3))The three norms should be close. They can differ slightly in the third decimal place, because liblinear also penalizes the intercept and each solver stops at its own tolerance.
Edge cases and common errors
Separable data and non-convergence
Suppose you have far more terms than documents. A hyperplane can then separate the training labels perfectly. With no penalty, the log loss keeps falling as the weights grow, so the optimum is at infinity and the solver never settles. With a penalty the optimum is finite, which is one reason C should not be set arbitrarily large.
The usual symptom is a ConvergenceWarning that says the solver failed to converge. Try these fixes in order:
- Increase
max_iter, for example to 1000 or 5000. - Lower
Cso the penalty bites harder. - Check that the features are scaled, which TF-IDF normally ensures.
Scaling sparse input
StandardScaler subtracts the mean by default. That would turn zeros into nonzero values and destroy the sparsity, so scikit-learn raises an error on sparse input. If you must scale, use StandardScaler(with_mean=False) or MaxAbsScaler. Both keep zeros as zeros.
Documents with no known words
Terms that were not in the training vocabulary are ignored at prediction time. A document made entirely of unknown words becomes a row of all zeros. Then w · x is 0 and the score is the intercept alone:
empty = vec.transform(["zzz qqq"])
print(empty.nnz)
print(clf.decision_function(empty)[0], clf.intercept_[0])
print(clf.predict_proba(empty))The two printed scores are equal. The model's answer for such a document reflects only the class balance it saw in training. In production, check for nnz == 0 and route those documents to a fallback instead of trusting the output.
Probabilities are not always calibrated
The model says 0.9, but that does not guarantee it is right 90 percent of the time. Regularization shrinks weights, which pulls probabilities toward 0.5, so scores tend to be underconfident when C is small. If you need trustworthy probabilities, for example to set a decision threshold, measure calibration on held-out data. You can also wrap the model in CalibratedClassifierCV. For ranking or for the plain argmax label, calibration rarely matters.
Multiclass details
With K classes, coef_ has K rows, and each row is a per-class weight vector. In the multinomial model, adding the same constant to every class's scores leaves the softmax output unchanged. The solver pins the solution down through the penalty term. The practical consequence is that individual coefficients are only meaningful relative to the other classes' coefficients for the same term.
What to remember
- Logistic regression computes a linear score from a sparse TF-IDF row and converts it to probabilities with the sigmoid, or with softmax for several classes.
- Cost scales with the number of nonzero entries, which is why it handles very wide text matrices well.
- The training problem is convex, so solvers differ in speed and supported penalties, not in the answer.
- Watch for convergence warnings, scaling errors on sparse input, all-zero rows, and uncalibrated probabilities.
Exercise
A binary logistic regression model has intercept b = -1.0, and a document's sparse vector has only two nonzero entries, 0.5 and 0.4, with weights 3.0 and 2.5 on those terms. What are the score z and the probability of class 1, rounded to two decimals?
Show answer
z = 3.0 0.5 + 2.5 0.4 + (-1.0) = 1.5 + 1.0 - 1.0 = 1.5. The probability is 1 / (1 + exp(-1.5)) = 1 / (1 + 0.2231) = 0.82. Only the two nonzero terms contribute to the dot product.
Exercise
You fit a LogisticRegression on TF-IDF features and get a ConvergenceWarning. Name two changes that may fix it, and explain why a very large C makes the problem worse on high-dimensional text data.
Show answer
Increase max_iter, or lower C (also check that features are scaled). With far more terms than documents, the training data is often linearly separable. A very large C makes the penalty almost vanish, so the loss keeps decreasing as the weights grow and the solver needs many more iterations without reaching a stable optimum.
Exercise
Why does a document containing only out-of-vocabulary words always receive the same prediction, and what value determines it?
Show answer
Unknown words are dropped by the vectorizer, so the document becomes an all-zero row. The dot product w · x is then 0, so the score equals the intercept (per class in the multiclass case). The prediction therefore depends only on the intercept and not on the document.