Sub topic 5
Turning Text into Features with TF-IDF
This chapter assumes basic Python, familiarity with lists and dictionaries, and a basic understanding of supervised learning. You should know that a classifier learns from training examples and then predicts labels for new text.
Machine-learning models work with numbers, not raw sentences. TF-IDF converts a collection of documents into numeric feature vectors. TF-IDF means term frequency–inverse document frequency. It gives a high value to words that are important in one document but uncommon across the collection.
The working model
A document can be a review, a social post, or one sentence. TF-IDF creates one column for each vocabulary term and one row for each document.
The score has two parts:
- Term frequency measures how often a term appears in a document.
- Inverse document frequency reduces the weight of terms that appear in many documents.
A common form is:
TF-IDF(term, document) = TF(term, document) × IDF(term)
The exact formula varies by implementation. Scikit-learn uses a smoothed IDF calculation by default. The important behavior is that common words receive less weight, while distinctive words receive more weight.
For example, “the” may appear in nearly every review, so it carries little information. “Excellent” may appear in only a few reviews, so it can help distinguish positive text.
Building a TF-IDF matrix
TfidfVectorizer performs several steps:
- It tokenizes each document into terms.
- It builds a vocabulary.
- It counts terms in each document.
- It calculates IDF values.
- It returns a sparse matrix of feature values.
A sparse matrix stores mostly nonzero values instead of allocating space for every possible document-term pair.
from sklearn.feature_extraction.text import TfidfVectorizer
documents = [
"Great battery and bright screen",
"Bright screen but poor battery",
"Poor customer service",
]
vectorizer = TfidfVectorizer(lowercase=True)
matrix = vectorizer.fit_transform(documents)
print("Vocabulary:", vectorizer.get_feature_names_out())
print("Matrix shape:", matrix.shape)
print(matrix.toarray().round(3))The matrix shape is (3, 8) for this vocabulary. Each row represents a document. Each column represents one term. The values are not raw word counts. They reflect both frequency and how widely each word is used.
Choosing useful features
You can change how the vocabulary is constructed.
| Option | Purpose | Example |
|---|---|---|
| `ngram_range=(1, 2)` | Include single words and two-word phrases | `poor battery` |
| `min_df=2` | Ignore terms appearing in fewer than two documents | Remove rare typos |
| `max_df=0.9` | Ignore terms appearing in more than 90% of documents | Remove overly common terms |
| `sublinear_tf=True` | Reduce the effect of repeated terms | Treat ten repeats as less than ten times one repeat |
Single words are called unigrams. Two-word phrases are bigrams. Bigrams help preserve meaning in phrases such as “not good” or “very helpful,” although they do not solve negation in every case.
Avoiding data leakage
Fit the vectorizer only on training data. Fitting it on the complete dataset allows information from the test set to influence the vocabulary and IDF values. That makes evaluation less trustworthy.
A pipeline keeps feature extraction and classification together:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), min_df=1),
LogisticRegression(max_iter=1000),
)
model.fit(train_texts, train_labels)
predictions = model.predict(test_texts)The pipeline fits TF-IDF using only the data passed to fit. During prediction, it applies the already learned vocabulary and IDF values to new documents.
Exercise
Why should the TF-IDF vectorizer be fitted only on training documents?
Show answer
Fitting it on test documents leaks information about the evaluation data and can make the measured performance look better than it really is.