Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
Train a movie-review sentiment classifier: split first, put TF-IDF and the model in one Pipeline, compare MultinomialNB (F1 0.801) with LinearSVC (F1 0.857), read the confusion matrix and predict new reviews from raw text.
What you will learn
- Split raw text before any vectorizer learns from it
- Put TfidfVectorizer and a model in one Pipeline
- Compare MultinomialNB and LinearSVC with the F1 score and a confusion matrix
- Predict the sentiment of brand-new raw reviews
Before you start
- TF-IDF with TfidfVectorizer
- Train-Test Split and Data Leakage
- Precision, Recall and F1 Score
Think of an email spam filter. You've already marked three emails: "Win a free prize" is spam, "Lunch tomorrow" goes to the inbox, "Free winner, click here" is spam. From these the filter learns which words point where: free and win point to spam, lunch points to the inbox.
Now a brand-new email arrives: "Claim your free gift". The filter never saw this exact email, but it knows the words, so it says spam. Labelled text in, a word-based rule out.
Our movie reviews work the same way, with positive or negative instead of spam or inbox. We already know how to turn words into numbers with bag of words and TF-IDF. Now we train a model on them and check it on reviews it has never seen.
Glue the reviews, then split first
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.metrics import f1_score, ConfusionMatrixDisplay
sents = pd.read_csv("movie_review.csv")
reviews = (sents.groupby(["cv_tag", "tag"])["text"]
.apply(" ".join).reset_index())
X = reviews["text"]
y = (reviews["tag"] == "pos").astype(int) # 1 = pos
print(len(X), "reviews,", y.sum(), "positive")
2000 reviews, 1000 positive
The file has one sentence per row, so we glue the sentences back into 2,000 full reviews. X is the text, and y is 1 when the review is positive.
Then the split, before anything learns from the text. stratify=y keeps half positive and half negative in both parts:
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(1600,) (400,)
1,600 reviews to learn from and 400 to test. Notice that X is still raw text. No vectorizer has seen it yet.
One fit, then only predict
The vectorizer learns from text: its vocabulary and how rare each word is. If it ever sees the test reviews during learning, they leak into the model, exactly like a scaler fitted on all rows in Train-Test Split and Data Leakage. A Pipeline fixes this by tying the vectorizer and the model into one object:
fit, the vectorizer and then the model learn from X_train. During predict, the test reviews ride the same road, but nothing learns from them.Two contestants, one shape
models = {
"MultinomialNB": Pipeline([
("tfidf", TfidfVectorizer()),
("clf", MultinomialNB())]),
"LinearSVC": Pipeline([
("tfidf", TfidfVectorizer()),
("clf", LinearSVC(random_state=42))]),
}
Both pipelines start with a TfidfVectorizer that turns the words into weighted numbers. They differ only in the last step:
- MultinomialNB is naive Bayes on word weights. Fast, simple, and a classic for text.
- LinearSVC is a linear support vector machine. It looks for the widest gap between the positive and the negative reviews.
Fit and score each pipeline
for name, pipe in models.items():
pipe.fit(X_train, y_train)
pred = pipe.predict(X_test)
print(name, "F1:", round(f1_score(y_test, pred), 3))
MultinomialNB F1: 0.801
LinearSVC F1: 0.857
pipe.fit on X_train: the vectorizer learns the words and the model learns its weights. pipe.predict on X_test: the vectorizer only transforms and the model only predicts. Then we print the F1 score.
Both are good, and LinearSVC wins, 0.857 against 0.801. And there's no manual fit_transform anywhere. The pipeline handles the train and the test text the right way.
Where does LinearSVC go wrong?
F1 is one number. A confusion matrix shows where the mistakes are:
best = models["LinearSVC"]
disp = ConfusionMatrixDisplay.from_estimator(
best, X_test, y_test,
display_labels=["neg", "pos"], cmap="Blues")
print(disp.confusion_matrix)
plt.show()
[[160 40]
[ 20 180]]

160 negative reviews were called negative and 180 positive reviews were called positive, so 340 of 400 are right. The most common mistake is the top-right cell: 40 negative reviews called positive. The other way round it's 20. A sarcastic "great, just great" is hard for words alone.
What did the vectorizer learn?
Let's look inside the fitted pipeline and check that nothing leaked:
tfidf = best["tfidf"]
n_words = len(tfidf.vocabulary_)
print(n_words, "words learned from X_train")
print(tfidf.transform(X_test).shape)
36352 words learned from X_train
(400, 36352)
best["tfidf"] is the fitted vectorizer inside the pipeline. It learned 36,352 words from the 1,600 training reviews only. The 400 test reviews get the very same columns. A word that appears only in a test review gets no column; it's simply ignored. So the test reviews taught the vectorizer nothing.
(In the TF-IDF article the vectorizer saw all 2,000 reviews and English stop words were dropped, which gave 39,354 columns. Here it sees fewer reviews and keeps every word, so the number is different.)
Raw text in, label out
And now the fun part, reviews the model has never seen:
new = ["a wonderful, moving film with a brilliant cast",
"a dull, boring mess and a waste of time"]
print(best.predict(new))
[1 0]
1 means positive, for wonderful, moving and brilliant. 0 means negative, for dull, boring and waste. We passed raw text: the pipeline cleans, counts, weighs and predicts in one call.
Common mistakes
- Vectorizing before the split. Fitting
TfidfVectorizeron all 2,000 reviews lets the test text shape the vocabulary and the idf values. Split first, then fit inside a Pipeline. - Calling
fit_transformon the test text. That builds a new vocabulary with different columns. The test set is only ever transformed. - Judging by one number. F1 hides which way the model errs. The confusion matrix showed twice as many negatives called positive as the other way round.
Recap
| Step | Code | Result here |
|---|---|---|
| Split first | train_test_split(..., stratify=y) | 1,600 train, 400 test |
| One Pipeline | Pipeline([("tfidf", ...), ("clf", ...)]) | vectorizer fits on train only |
| Compare models | f1_score | MultinomialNB 0.801, LinearSVC 0.857 |
| Find the errors | ConfusionMatrixDisplay.from_estimator | 340 of 400 right, 40 neg called pos |
| Use it | best.predict(raw_text) | [1 0] |
Try it yourself
Add ngram_range=(1, 2) to the TfidfVectorizer of both pipelines, so word pairs like "not good" become features too. Does F1 go up or down? The notebook and the dataset are in the community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
Next →Why Neural Networks: Pixels, One Neuron and Layers
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Bag of Words with CountVectorizer: Turn Text into Word Counts
A model only does maths, so text has to become numbers first. Clean a review, count its words with CountVectorizer, read the document-term matrix, see why it is sparse, and add word pairs with n-grams. Shown on 2,000 movie reviews.
TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
Plain word counts treat every word the same. TF-IDF multiplies each count by how rare the word is, then scales each row to length 1. Worked by hand on four restaurant reviews, then on 2,000 movie reviews.