Sub topic 6
Training a Logistic Regression Classifier
Assume you know basic Python, can install packages with pip, and understand that labeled examples are split into training and test data. This chapter assumes that text has already been cleaned and explains how TF-IDF features become sentiment predictions.
Why logistic regression works for text
Logistic regression is a supervised classification algorithm. It learns a weight for each input feature and combines those weights into a score. For sentiment analysis, the features are usually words or word pairs represented by TF-IDF values.
The model converts its score into a probability with the logistic, or sigmoid, function:
p = \frac{1}{1 + e^{-z}}Here, p is the estimated probability of the positive class and z is the weighted sum of the features. With two classes, the model can label text as positive when its probability is at least 0.5. You can change this threshold when false positives and false negatives have different costs.
Logistic regression is a useful baseline because it is fast, interpretable, and often surprisingly strong for short text. It is different from linear regression, which predicts a continuous number rather than a class probability.
Build the classifier with a pipeline
A Pipeline connects preprocessing and prediction. This prevents a common mistake: fitting the vectorizer separately on the test data. The vectorizer must learn its vocabulary and IDF values from training data only.
The example uses one-word and two-word features. A two-word feature is called a bigram, such as not good. Bigrams can preserve useful context that individual words lose.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.pipeline import make_pipeline
train_texts = [
"Great product, works perfectly",
"Absolutely love it",
"Fantastic quality and fast shipping",
"Terrible, broke after one day",
"Waste of money, very disappointed",
"Awful customer service",
]
train_labels = ["pos", "pos", "pos", "neg", "neg", "neg"]
test_texts = [
"Love the quality",
"Disappointed, it broke quickly",
]
test_labels = ["pos", "neg"]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), lowercase=True),
LogisticRegression(max_iter=1000),
)
model.fit(train_texts, train_labels)
predictions = model.predict(test_texts)
probabilities = model.predict_proba(test_texts)
print(classification_report(test_labels, predictions, zero_division=0))
print(confusion_matrix(test_labels, predictions, labels=["neg", "pos"]))
for text, label, probability in zip(
test_texts, predictions, probabilities
):
print(text, "->", label, probability.max())max_iter=1000 gives the optimizer more attempts to find stable weights. If you see a convergence warning, increase this value or scale back the feature space.
The classifier learns associations, not meaning. If the training data often contains “excellent” in positive examples, that word receives a positive weight. A word such as “broken” may receive a negative weight. This makes the model easy to inspect, but it also lets spelling errors, topic words, and biased labels influence predictions.
Useful settings and common errors
| Setting | Purpose | Trade-off |
|---|---|---|
| `ngram_range=(1, 2)` | Uses words and bigrams | More features and more memory |
| `max_iter=1000` | Allows more optimization steps | Takes longer if the problem is difficult |
| `class_weight="balanced"` | Gives more weight to rare classes | Can reduce majority-class accuracy |
Use class_weight="balanced" when the training set has serious class imbalance. Do not use it automatically. Compare the results on a representative validation set.
A tiny dataset can demonstrate the API, but it cannot measure real-world quality. Use a large, stratified split and keep posts from the same user or product review group together when leakage is possible.
Exercise
Why should the TF-IDF vectorizer and logistic regression model be fitted only on the training data?
Show answer
Fitting on test data leaks information about the test set into the model, producing an overly optimistic evaluation.