Turning words into features.
Understand token counts, vocabulary, sparse matrices, n-grams, and TF–IDF.
Start with the meaning.
A model that expects numeric feature rows cannot directly consume a sentence as a number. A text vectorizer turns documents into numeric columns. The simplest bag-of-words representation builds a vocabulary from training documents and counts how often each word appears in each document. “Bag” means word order is mostly discarded: “dog bites person” and “person bites dog” can share the same unigram counts even though their meanings differ. This representation can still be effective when word presence signals a category.
A token is one unit the vectorizer chooses to count. Default tokenization may split on punctuation and apply case rules, but those choices are part of the model. A bigram is a pair of neighboring tokens; adding bigrams preserves some local order, such as the difference between “not good” and “good.” Each vocabulary item becomes a column. Most documents contain only a small part of a large vocabulary, so the resulting matrix is sparse, meaning most entries are zero.
How the idea works.
TF–IDF changes word counts by giving common words across many documents less weight and relatively distinctive words more weight. TF is term frequency, and IDF is inverse document frequency. It is a weighting scheme, not a semantic understanding of language. Two synonyms may still occupy separate columns, and sarcasm or context can defeat a simple count model. A classifier trained on TF–IDF features can nevertheless provide a strong, understandable baseline for many text tasks.
The vocabulary and IDF statistics must be learned from training text only. If they are fitted on all documents before splitting, the representation has already seen the test collection. A pipeline with vectorizer followed by classifier keeps the training boundary correct during cross-validation. New documents use the same vocabulary; unseen words are generally ignored by a fixed vocabulary rather than magically added without refitting.
Text data carries special risks. Duplicate articles or near-identical templates can leak across random splits. A model may learn author names, website boilerplate, or publication dates rather than the requested topic or sentiment. Language, spelling, dialect, and changes over time affect what words appear. Evaluating by source, time, and group is as important as evaluating one random sample.
Follow the code.
from sklearn.feature_extraction.text import TfidfVectorizer
train_text = [
"the project meeting starts today",
"the project report is ready",
"today the weather is clear",
]
vectorizer = TfidfVectorizer(ngram_range=(1, 2))
X = vectorizer.fit_transform(train_text)
print(X.shape)
print(vectorizer.get_feature_names_out()[:8])The three strings are training documents. TfidfVectorizer learns tokens and adjacent two-token phrases because ngram_range=(1, 2). fit_transform builds a vocabulary, computes term weights, and returns a sparse document-by-feature matrix. X.shape reports three rows and however many vocabulary columns were created. get_feature_names_out reveals the learned column names; the slice [:8] shows only the first eight so the output remains readable.
The numeric weights do not say whether any document is useful or unwanted; there are no labels here. A classifier would need y values aligned with these three rows. For a later document, vectorizer.transform(new_text) applies the existing vocabulary and IDF statistics. Calling fit_transform again on the new text would change the feature meanings and break the relationship with a fitted classifier.
What the result does not say.
Stopword removal can discard very common words, but a common word such as “not” can be essential. A generic stopword list is a design decision with consequences, not a harmless cleanup. Character n-grams can help with spelling variation and some languages.
Modern embedding models create dense representations that can capture more semantic relationships. They bring different compute, data, privacy, and evaluation questions. Bag-of-words and TF–IDF remain valuable because their assumptions and feature names are comparatively easy to inspect.
One clear idea.
Text vectorization learns a numeric vocabulary from training documents; its choices are part of the fitted model.
The ML cookbook
Complete, explained Python workflows sit alongside this reading course.