Sub topic 2
Turning Text into Features with TF-IDF
This chapter assumes you know basic Python, can install packages with pip, and understand training and test data. It also assumes you have scikit-learn installed (pip install scikit-learn).
Turning text into features
A classifier needs numbers, not sentences. TF-IDF (term frequency times inverse document frequency) converts each text into a vector of numbers, one per word or word pair. A word scores high when it appears often in one text but rarely across the whole dataset. Words such as "the" score low because they appear everywhere.
Training a logistic regression classifier
Logistic regression is a linear model that learns a weight for each feature and outputs a probability for each label. Pairing it with TF-IDF gives a strong baseline that trains in seconds. The code below chains both steps in one pipeline, so the vectorizer learns its vocabulary only from the training data.
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",
"It arrived on Tuesday",
"The box was grey",
]
train_labels = ["pos", "pos", "pos", "neg", "neg", "neg", "neu", "neu"]
test_texts = ["Love the quality", "Disappointed, it broke quickly",
"The box was white", "Works fine I guess"]
test_labels = ["pos", "neg", "neu", "neu"]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), lowercase=True),
LogisticRegression(max_iter=1000, class_weight="balanced"),
)
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", "neu", "pos"]))Measuring performance: precision, recall, F1, and the confusion matrix
Accuracy alone can mislead. Precision answers "of the posts I labeled negative, how many really were?" Recall answers "of the truly negative posts, how many did I find?" F1 is the harmonic mean of the two. The confusion matrix shows each true label against each predicted label, so you can see which classes get mixed up.
Handling imbalanced classes and the neutral label
Reviews are often lopsided, with many positive and few negative examples. Neutral text is also hard to label consistently. The class_weight="balanced" setting in the code above tells the model to penalize mistakes on rare classes more heavily. Check the per-class recall after this change, because a class-weight fix can lower precision on the majority class.
Exercise
Exercise
In the confusion matrix, rows are true labels and columns are predicted labels. If the "neg" row has a value of 0 in the "neg" column, what does that mean for recall on the negative class?
Show answer
Recall for "neg" is 0 divided by the total number of true negatives. Every true negative was predicted as another label, so the model found none of them.