Sub topic 10
A First Look at Text Features
This chapter assumes you know how to build a scikit-learn Pipeline and ColumnTransformer, and that you understand why transformers must be fitted on training data only. Text is the one feature type that needs a conversion step before any model can use it. A model needs numbers, so we turn each document into a numeric vector.
From Documents to Counts
The simplest approach is the bag-of-words model. It builds a vocabulary from the training documents. Each document then becomes a vector that counts how often each vocabulary word appears. Word order is lost, but for many tasks the counts carry enough signal.
CountVectorizer does this. It lowercases text, splits it into tokens, and counts them.
from sklearn.feature_extraction.text import CountVectorizer
docs = ["Cheap flights to Paris", "Paris hotel deals", "Cheap hotel deals"]
vec = CountVectorizer()
counts = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(counts.toarray())The result is a sparse matrix. Most entries are zero, and scikit-learn stores only the nonzero ones. Most models in scikit-learn accept sparse input directly.
TF-IDF Weighting
Raw counts over-reward common words such as "the". TF-IDF fixes this. The term frequency (TF) is how often a word appears in a document. The inverse document frequency (IDF) shrinks the weight of words that appear in many documents. A word that is frequent in one document but rare overall gets a high score.
TfidfVectorizer combines counting and weighting. Its most useful settings are these:
| Setting | Effect |
|---|---|
| `stop_words="english"` | Drops very common words |
| `ngram_range=(1, 2)` | Adds two-word phrases such as "cheap flights" |
| `min_df=2` | Ignores words found in fewer than 2 documents |
| `max_features=5000` | Keeps only the most frequent terms |
Without limits, the vocabulary can reach hundreds of thousands of columns. min_df and max_features keep it manageable.
Text Inside a Pipeline
The vocabulary and IDF values are learned from data, so they are fitted state. They must be learned from training data only, which is the leakage rule from earlier chapters. Put the vectorizer in the pipeline.
One detail differs from other transformers. Text vectorizers expect a single column of strings, not a 2D array. In a ColumnTransformer, pass the column name as a string, not as a list.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({
"review": ["great product", "terrible, broke fast", "great value",
"broke after a day", "works great", "terrible quality"],
"price": [20, 15, 18, 25, 30, 12],
"label": [1, 0, 1, 0, 1, 0],
})
prep = ColumnTransformer([
("text", TfidfVectorizer(ngram_range=(1, 2)), "review"),
("num", StandardScaler(), ["price"]),
])
model = Pipeline([
("prep", prep),
("clf", LogisticRegression(max_iter=1000)),
])
model.fit(df[["review", "price"]], df["label"])
print(model.predict(pd.DataFrame({"review": ["great"], "price": [20]})))Note "review" without brackets. Writing ["review"] would pass a 2D object, and the vectorizer would raise an error.
Simple Hand-Built Text Features
Not every text feature needs a vocabulary. Cheap statistics can be strong signals: character length, word count, number of exclamation marks, or whether the text contains a digit. These need no fitting, so they carry no leakage risk. Add them as separate columns with df["review"].str.len().
Common Errors
- Fitting the vectorizer on all data. Test-set words then enter the vocabulary, which is leakage. Keep it in the pipeline.
- Passing a list of columns. Use a string for text columns.
- Unbounded vocabulary. Use
min_dformax_features. - Scaling sparse matrices.
StandardScalercenters by default, which would make the matrix dense. Usewith_mean=Falseif you must scale it. - Unseen words. Words absent from training are ignored at prediction time. That is expected behavior, not a bug.
Exercise
You build a ColumnTransformer with ("text", TfidfVectorizer(), ["review"]) and get an error when fitting. What is the cause, and how do you fix it?
Show answer
The column is given as a list, so the vectorizer receives a 2D DataFrame, but it expects a 1D sequence of strings. Pass the column name as a plain string: ("text", TfidfVectorizer(), "review").
Exercise
Why should TfidfVectorizer be fitted inside cross-validation folds rather than once on the full dataset?
Show answer
Its vocabulary and IDF weights are learned from data. Fitting on the full dataset lets validation-fold documents influence them, which leaks information and inflates the validation score. Placing the vectorizer in a pipeline passed to cross_val_score refits it on each training fold.