Sub topic 10
A First Look at Text Features
Models need numbers, and a free-text column such as a review or a support ticket is a string. This chapter covers the simplest ways to turn text into numeric columns: hand-built statistics, word counts, and TF-IDF weights. It also covers how to fit these steps without leaking validation data.
This chapter assumes you know the fit and transform pattern in scikit-learn, have read the earlier chapters on leakage and on Pipeline with ColumnTransformer, and can read a sparse matrix at a basic level. It is a first look. Embeddings and language models are outside its scope.
Two routes from text to numbers
There are two common routes, and you can combine them.
- Hand-built statistics. Count characters, words, exclamation marks, or digits. Each statistic becomes one numeric column. These columns are cheap to compute and easy to explain.
- Vocabulary-based vectors. Build a vocabulary from the training text, then represent each document as a row with one column per vocabulary term. The values are counts or weights.
Hand-built statistics
Simple counts often carry signal. Spam tends to have more exclamation marks. Long tickets may be more complex. These features use only the row they describe. They learn nothing from other rows, so computing them before the train/test split cannot leak information.
import pandas as pd
df = pd.DataFrame({"review": [
"Great product, works well!",
"Terrible. Broke after two days.",
]})
df["n_chars"] = df["review"].str.len()
df["n_words"] = df["review"].str.split().str.len()
df["n_exclaim"] = df["review"].str.count("!")
df["has_digit"] = df["review"].str.contains(r"\d").astype(int)
print(df)Statistics such as length are usually right-skewed, so the log transform from the earlier chapter often helps.
Bag of words
A bag-of-words representation ignores word order and records only how often each term appears. CountVectorizer does the work in three steps. It lowercases the text, splits it into tokens, and counts the tokens against a vocabulary learned during fit.
from sklearn.feature_extraction.text import CountVectorizer
docs = ["the cat sat", "the cat saw the dog"]
cv = CountVectorizer()
counts = cv.fit_transform(docs)
print(cv.get_feature_names_out())
print(counts.toarray())The output is:
['cat' 'dog' 'sat' 'saw' 'the']
[[1 0 1 0 1]
[1 1 0 1 2]]The result is a sparse matrix, which stores only the nonzero entries. A real vocabulary can have tens of thousands of terms, and most documents use only a few dozen of them. Calling .toarray() on a large matrix can exhaust memory, so use it only on small demos like this one.
The default tokenizer keeps tokens of two or more word characters. Single-letter words such as "a" and "I" are dropped, and punctuation is discarded.
TF-IDF
Raw counts over-weight common words. "the" appears everywhere and tells the model little. TF-IDF (term frequency times inverse document frequency) scales each count by how rare the term is across documents.
In scikit-learn, with the default settings, the inverse document frequency is ln((1 + n) / (1 + df)) + 1. Here n is the number of documents and df is the number of documents containing the term. Each row is then scaled to unit length (L2 norm). A term that appears in every document gets the lowest weight. A term that appears in only a few documents gets a higher one.
The document frequencies are statistics of the training corpus, so TfidfVectorizer has to be fitted on training data only. This is the same leakage rule you have seen for scalers and imputers.
Controlling vocabulary size
The vocabulary can grow very large and noisy. These parameters of CountVectorizer and TfidfVectorizer control it:
| Parameter | Effect | Typical use |
|---|---|---|
| `min_df` | Drop terms in fewer than this many documents (integer) or fraction of documents (float) | Remove typos and one-off tokens |
| `max_df` | Drop terms in more than this fraction of documents | Remove near-universal words |
| `max_features` | Keep only the top terms by corpus frequency | Hard cap on width |
| `ngram_range=(1, 2)` | Add adjacent word pairs | Capture phrases like "not good" |
| `stop_words="english"` | Remove a built-in list of common words | Smaller vocabulary, but can discard useful signal |
| `analyzer="char_wb"` | Use character n-grams within word boundaries | Misspellings and short, noisy text |
Bigrams help because bag of words cannot tell "not good" from "good". They also multiply the vocabulary size, so pair ngram_range=(1, 2) with min_df or max_features.
Text inside a ColumnTransformer
Text vectorizers differ from other transformers in one way. They expect a 1-D sequence of strings, not a 2-D table. In a ColumnTransformer, you therefore give the column name as a plain string, not 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.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({
"review": [
"Great product, works well!",
"Terrible. Broke after two days.",
"Love it, would buy again",
"Awful quality, waste of money",
"Excellent value and fast shipping",
"Does not work, very disappointed",
"Fantastic, exceeded my expectations",
"Poor build and bad support",
"Really happy with this purchase",
"Stopped working after a week",
"Highly recommend, works perfectly",
"Cheap plastic, returned it",
],
"label": [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
})
# Stateless row-level statistics: safe to compute before splitting
df["n_chars"] = df["review"].str.len()
df["n_words"] = df["review"].str.split().str.len()
features = ["review", "n_chars", "n_words"]
preprocess = ColumnTransformer([
("text", TfidfVectorizer(ngram_range=(1, 2), min_df=1), "review"),
("stats", StandardScaler(), ["n_chars", "n_words"]),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
scores = cross_val_score(model, df[features], df["label"], cv=3, scoring="accuracy")
print(scores.mean())The vocabulary, the IDF weights, and the scaler statistics are all learned again inside each training fold, so the validation fold never influences them. This toy dataset is far too small for the score to mean anything. The point is the structure.
Common errors
- Passing the text column as a list. Writing
["review"]makes the vectorizer receive a 2-D table, and it fails with an error such as "Iterable over raw text documents expected, string object received" or a shape complaint. Use"review". - Fitting the vectorizer on all the data. If you call
fit_transformon the full dataset before splitting, document frequencies and the vocabulary include validation text. Keep the vectorizer inside the pipeline. - Densifying a big matrix.
.toarray()or.todense()on a large vocabulary can run out of memory. Most linear models accept sparse input directly. - Scaling sparse counts with centering.
StandardScaler()subtracts the mean by default, which would turn a sparse matrix into a dense one. It raises an error on sparse input unless you setwith_mean=False. TF-IDF output is already normalized, so extra scaling is rarely needed. - Unknown words at serving time. Words not seen in training are ignored by the vectorizer. This is safe, but it means new vocabulary is invisible to the model until you retrain.
- Over-aggressive cleaning. Removing stop words or punctuation can delete signal. "not" is on the English stop-word list, and it flips the meaning of a sentence. Compare variants with cross-validation, as described in the chapter on measuring features.
Choosing an approach
Start with TF-IDF on unigrams and bigrams plus a linear model. This baseline is fast and often strong, and its coefficients show which terms drive predictions. Add hand-built statistics when you have a reason to think length or formatting matters. Move to character n-grams when text is noisy, for example with misspellings, product codes, or short strings. If the baseline falls short because meaning and context matter, that is the point to look at learned embeddings.
Exercise
A teammate calls TfidfVectorizer().fit_transform(df["review"]) on the full dataset, then splits into train and test sets and reports the test score. What is wrong with this, and how do you fix it?
Show answer
The vocabulary and the inverse document frequencies were learned from all the text, including the test rows, so information about the test set leaked into the features. Split first, then fit the vectorizer on the training rows only. The simplest fix is to put the vectorizer in a Pipeline, optionally inside a ColumnTransformer with the column given as the string "review", and pass the whole pipeline to crossvalscore or fit it on the training split.
Exercise
Why can row-level statistics such as word count be computed before splitting the data, while TF-IDF cannot?
Show answer
Word count for a row depends only on that row, so no information flows between rows. TF-IDF depends on document frequencies and a vocabulary computed across the whole corpus, which are fitted statistics. Those must be learned from training data only.