Sub topic 6
Training a Logistic Regression Classifier
This chapter assumes you know basic Python, can install packages with pip, and understand the idea of supervised learning: you train on labeled examples and predict labels for new ones. It also assumes you have seen TF-IDF features, which turn each text into a vector of weighted word counts. Here you will use those vectors to train a logistic regression classifier, the standard baseline for sentiment analysis.
Why logistic regression is the standard baseline
Logistic regression is a linear model. It gives each feature (here, each word or word pair) a weight, adds up the weights of the features present in a text, and turns that sum into a probability.
For two classes, the model computes a score z = w · x + b. Here x is the TF-IDF vector, w is the learned weight vector, and b is a bias term. The sigmoid function then maps the score to a probability between 0 and 1:
P(positive | text) = 1 / (1 + exp(-z))A large positive weight on "love" pushes the score up. A large negative weight on "terrible" pushes it down. This is why the model suits sentiment analysis:
- It is fast to train, even on hundreds of thousands of reviews.
- It works well on sparse, high-dimensional TF-IDF vectors.
- It is easy to inspect, because you can list the words with the largest weights.
- It outputs probabilities, so you can set a confidence threshold.
It is also a strong reference point. If a transformer model beats it by only a few points, that tells you something about whether the extra cost is worth it.
The pipeline
The data flows through three stages, and the same stages must run at training time and at prediction time.
Scikit-learn's Pipeline keeps these stages together. This matters for one reason in particular: the vectorizer learns its vocabulary and IDF values from the training data only. If you fit it on the full dataset before splitting, information from the test set leaks into the features. A pipeline fitted on the training split avoids that mistake.
A first working model
The script below trains on a small toy dataset so that it runs instantly. It uses the pipeline form and prints a report. A real run needs thousands of labeled examples.
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)
pred = model.predict(test_texts)
print(classification_report(test_labels, pred, zero_division=0))
print(confusion_matrix(test_labels, pred, labels=["neg", "pos"]))Three details are worth noting:
ngram_range=(1, 2)includes single words and adjacent word pairs. Pairs such as "not good" give the model a limited way to capture negation, because "not good" gets its own weight.max_iter=1000gives the optimizer enough steps to converge. The default of 100 often produces a convergence warning on larger text data.zero_division=0stops the report from raising warnings when a class receives no predictions.
Reading the learned weights
Because the model is linear, you can see what it learned. The helper below lists the features with the most negative and most positive weights for a binary model.
import numpy as np
def top_features(model, n=5):
vectorizer = model.named_steps["tfidfvectorizer"]
clf = model.named_steps["logisticregression"]
names = np.array(vectorizer.get_feature_names_out())
order = np.argsort(clf.coef_[0])
return names[order[:n]], names[order[-n:]]
neg_words, pos_words = top_features(model)
print("Most negative:", list(neg_words))
print("Most positive:", list(pos_words))For a binary model, clf.coef_ has one row. Positive weights favor clf.classes_[1], which is "pos" here because scikit-learn sorts class labels alphabetically ("neg" comes before "pos"). Check clf.classes_ before you interpret the sign of any weight.
Inspect the weights on a real dataset and you will often see surprises. Product names, shipping terms, or a reviewer's habitual phrase can get large weights. These often indicate that the model has learned a shortcut in the data instead of sentiment.
The settings that matter
Most of the tuning effort goes into a few parameters.
| Parameter | What it does | Typical guidance |
|---|---|---|
| `C` | Inverse of regularization strength. Smaller values mean stronger regularization. | Search over values such as 0.1, 1, 10, 100. The default is 1.0. |
| `penalty` | Type of regularization. L2 (default) shrinks all weights. L1 drives many weights to zero. | Keep L2 unless you want a sparse, smaller model. |
| `class_weight` | Reweights classes in the loss function. | Use `"balanced"` when classes are skewed. |
| `max_iter` | Maximum optimizer iterations. | Raise it if you see a convergence warning. |
| `ngram_range` (vectorizer) | Which word sequences become features. | Start with `(1, 2)`. |
| `min_df` (vectorizer) | Drops terms that appear in fewer than this many documents. | Use 2 to 5 to remove typos and one-off tokens. |
Regularization deserves a closer look. With tens of thousands of features and far fewer documents, an unregularized model can fit the training data perfectly by assigning large weights to rare words. Regularization adds a penalty on large weights, so the model has to justify each weight with evidence from many examples. A small C gives a simpler model that may underfit. A large C gives a flexible model that may overfit.
Tuning with cross-validation
Do not choose C by looking at test-set results. Use cross-validation on the training data, and keep the test set for one final check.
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
def tune(texts, labels):
X_train, X_test, y_train, y_test = train_test_split(
texts, labels, test_size=0.2, stratify=labels, random_state=42
)
pipe = Pipeline([
("tfidf", TfidfVectorizer(ngram_range=(1, 2), min_df=2)),
("clf", LogisticRegression(max_iter=1000)),
])
grid = GridSearchCV(
pipe,
param_grid={"clf__C": [0.1, 1, 10, 100]},
scoring="f1_macro",
cv=5,
)
grid.fit(X_train, y_train)
print("Best C:", grid.best_params_["clf__C"])
print("Held-out macro F1:", grid.score(X_test, y_test))
return grid.best_estimator_Call tune(texts, labels) with your own lists once you have a few thousand labeled examples. Several choices here are deliberate:
stratify=labelskeeps the class proportions the same in both splits.- The vectorizer sits inside the pipeline, so each cross-validation fold fits its own vocabulary. No fold sees its validation data during feature building.
scoring="f1_macro"averages F1 over classes with equal weight. Plain accuracy hides weak performance on small classes.- Parameters inside a pipeline use the step name and two underscores, for example
clf__C.
Three or more classes
If your labels are positive, neutral, and negative, the same code works with no change. Scikit-learn's LogisticRegression uses a multinomial (softmax) formulation by default with the lbfgs solver, so it learns one weight vector per class and returns probabilities that sum to 1.
predict_proba returns one column per class, in the order of model.classes_. This gives you a way to handle uncertain cases:
probs = model.predict_proba(["It arrived on Tuesday"])[0]
for cls, p in zip(model.classes_, probs):
print(cls, round(float(p), 3))A common use is a confidence threshold: if the top probability is below, say, 0.6, send the text for human review instead of accepting the label. Probabilities from regularized logistic regression are usually reasonable but not perfectly calibrated, so pick the threshold from validation data, not by intuition.
Common errors
- Fitting the vectorizer before splitting. The vocabulary and IDF values then include test data. Scores look better than they should. Put the vectorizer in a pipeline.
- Reading weights without checking class order. Look at
clf.classes_first. - Ignoring imbalance. If 85% of posts are neutral, a model that always predicts neutral scores 85% accuracy and is useless. Use macro F1 and consider
class_weight="balanced". - Duplicates across splits. Reviews and social posts often contain near-identical copies, such as retweets or templated text. If copies land in both train and test sets, the score is inflated. Remove duplicates before splitting.
- Over-cleaning the text. Stripping punctuation and emojis removes signals such as "!!!" or a frowning face. Normalize deliberately, as in the previous chapters, and let the model see what carries sentiment.
- Convergence warnings. Raise
max_iter. Scaling is not an issue here, because TF-IDF vectors are already normalized. - Trusting one random split. On small data, scores change noticeably from one split to another. Use cross-validation and report the spread.
Where this model stops
A linear bag-of-words model sums word evidence. It cannot represent the way "not" flips a nearby word unless that pair appears often as a bigram. It cannot detect sarcasm, and it cannot use word order beyond n-grams. A model trained on product reviews will also weight domain words, such as "battery" or "refund," in ways that may not transfer to social posts. The later chapters on transformers, linguistic challenges, and domain shift deal with these limits. Even so, this baseline gives you a measured score to compare against, and its inspectable weights help you debug the data.
Exercise
You train a three-class model (neg, neu, pos) on a dataset where 80% of examples are neutral. Accuracy is 0.82, but you suspect the model is weak. Name two changes you would make to the evaluation and one change to the training setup, and say why.
Show answer
For evaluation, report per-class precision, recall, and F1 and look at the confusion matrix, because accuracy is dominated by the neutral class and hides poor results on neg and pos. Also use macro F1 as the headline metric, and as the tuning score in cross-validation, since it weights each class equally. For training, set class_weight="balanced" in LogisticRegression so errors on the rare classes cost more in the loss. Stratify the train/test split so each class appears in both sets in the same proportion.
Exercise
A teammate fits TfidfVectorizer on all 50,000 reviews, then splits into train and test sets and reports a high F1. What is wrong, and how do you fix it?
Show answer
The vectorizer learned its vocabulary and IDF weights from the test reviews too, so test information leaked into the features and the score is optimistic. Split the raw texts first, then fit the vectorizer on the training texts only. The simplest way is to wrap the vectorizer and classifier in a scikit-learn pipeline and call fit on the training split, so the test texts are only transformed with the fitted vocabulary.