Sub topic 3
Measuring performance: precision, recall, F1, confusion matrix
This chapter assumes you can build the TF-IDF and logistic regression pipeline from the previous chapter, and that you know train/test splits. You will use model, train, and test from that work.
Precision, recall, and F1
Accuracy alone can mislead, especially when one class is rare. Precision and recall give a clearer view for each class.
- Precision is the share of predicted positives that are correct.
- Recall is the share of actual positives the model finds.
- F1 is the harmonic mean of precision and recall.
A confusion matrix counts every prediction by its true and predicted label.
from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(test.data)
print(classification_report(test.target, pred, target_names=test.target_names))
print(confusion_matrix(test.target, pred))Tuning with cross-validation and grid search
GridSearchCV refits the whole pipeline for each parameter combination on each fold. This tunes the n-gram range and the regularization strength C without leaking validation data into the vectorizer.
from sklearn.model_selection import GridSearchCV
param_grid = {
"tfidfvectorizer__ngram_range": [(1, 1), (1, 2)],
"logisticregression__C": [0.1, 1.0, 10.0],
}
search = GridSearchCV(model, param_grid, cv=5, scoring="f1_macro", n_jobs=-1)
search.fit(train.data, train.target)
print(search.best_params_)Reading the model: which words drive each class
Each row of coef_ holds one class's weight for every term. Large positive weights push a document toward that class.
import numpy as np
vectorizer = model.named_steps["tfidfvectorizer"]
classifier = model.named_steps["logisticregression"]
names = vectorizer.get_feature_names_out()
for i, label in enumerate(train.target_names):
top = np.argsort(classifier.coef_[i])[-10:][::-1]
print(label, list(names[top]))When classes are unevenly represented
When one class is much larger, the model can favor it. Set class_weight="balanced" on LogisticRegression and report f1_macro or balanced_accuracy, which weight every class equally.
Limitations and where to go next
A bag-of-words model ignores word order and meaning, so "not good" and "good" can look alike when "not" is a stop word. Its coefficients describe correlation in the training text, not cause. Next, try character n-grams, or compare against a transformer-based classifier on the same held-out set.
Exercise
Your classifier has high recall but low precision for one class. Which kind of error is more common, and what would you change first?
Show answer
False positives are more common, because the model predicts that class too often. Raise the decision threshold or tune C and class weights, then recheck the classification report.