Sub topic 6
Logistic Regression on Sparse Features
This chapter assumes basic Python, NumPy, and supervised learning. You should know that a training set teaches a model and that a test set measures it on examples the model did not see. You should also be comfortable with TF-IDF vectors and the idea of a feature.
The working model
Logistic regression is a linear classification algorithm. It combines the input features with learned weights and converts the result into class probabilities.
For one binary classification example, the model computes:
z = w1x1 + w2x2 + ... + b
It then applies the logistic function:
p = 1 / (1 + exp(-z))
Here, x values are feature values, w values are learned weights, and b is a bias term. The probability p represents the estimated probability of the positive class.
Text data often has thousands of features, but most documents contain only a small fraction of the vocabulary. A document-term matrix therefore contains many zeros. This is a sparse matrix. Scikit-learn stores sparse matrices efficiently and LogisticRegression can work with them directly.
| Part | Meaning in text classification |
|---|---|
| Feature | A word or n-gram in the vocabulary |
| Feature value | The word's TF-IDF weight in a document |
| Weight | How strongly that feature supports a class |
| Bias | The class score before considering the words |
For multiple classes, logistic regression calculates a score for each class and turns the scores into probabilities. The predicted label is usually the class with the largest probability.
Why linear models fit sparse text
A word can provide a strong signal for a topic. For example, terms such as orbit and planet may support a space-related class, while engine and tire may support an automobile class. Logistic regression learns these relationships from labeled examples.
The model does not need to create a dense representation of every document. It computes contributions only for the nonzero entries in the sparse vector. This keeps both memory use and computation manageable.
The model learns a weight for every vocabulary feature. A positive weight pushes a document toward a class. A negative weight pushes it away from that class. The size of the weight indicates the strength of the effect, although it must be considered alongside the feature's scale and frequency.
Training a classifier
The following example creates TF-IDF features and trains logistic regression. The pipeline keeps feature construction and classification together.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
documents = [
"the spacecraft entered orbit around the planet",
"astronauts studied a distant galaxy",
"the car engine needs a new filter",
"the driver replaced the tire and brake",
]
labels = ["space", "space", "autos", "autos"]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2)),
LogisticRegression(max_iter=1000),
)
model.fit(documents, labels)
new_documents = [
"the spacecraft reached orbit",
"the car needs a new brake",
]
predictions = model.predict(new_documents)
probabilities = model.predict_proba(new_documents)
print(predictions)
print(probabilities.round(3))max_iter sets the maximum number of optimization steps. Text problems can have many features, so the default limit may be too small. A convergence warning means the solver stopped before finding a sufficiently stable solution. Increasing max_iter is one possible response, but it is also worth checking feature scaling, regularization, and the solver choice.
Regularization and the C parameter
Text vocabularies are often much larger than the number of documents. Without constraints, the model can assign very large weights to rare words that happen to occur in the training data. This is overfitting.
Regularization adds a penalty for large weights. Scikit-learn uses L2 regularization by default. It usually shrinks weights toward zero without removing features completely.
The C parameter controls the trade-off:
- A small
Capplies stronger regularization. - A large
Callows larger weights and fits the training data more closely. - The best value depends on the dataset and should be selected with validation.
Common errors
- Fitting the vectorizer on the test set leaks information into evaluation.
- Using a very large
Ccan make rare terms dominate. - Treating a probability as certainty hides model uncertainty.
- Ignoring convergence warnings can leave the model under-trained.
- Comparing raw coefficients across differently scaled features can mislead interpretation.
Exercise
A classifier predicts the correct label on its training documents but performs poorly on new documents. Which logistic regression setting could you reduce first, and why?
Show answer
Reduce C. A smaller C strengthens regularization, which limits large weights and can reduce overfitting. Confirm the choice with held-out validation data.