Bag of words and TF-IDF
Quick answer
Bag-of-words counts terms without preserving their order. TF-IDF weights terms by within-document frequency and rarity across training documents. Examples are static Python snippets tested locally on CPU; scikit-learn or PyTorch is required for selected examples. ByteMind execution is unverified.
Counts with frozen vocabulary
from sklearn.feature_extraction.text import CountVectorizerv=CountVectorizer(tokenizer=str.split,token_pattern=None,lowercase=False)v.fit(["red red blue","blue"])print(v.get_feature_names_out().tolist(),v.transform(["red unseen"]).toarray().tolist())Expected output (locally tested): ['blue', 'red'] [[0, 1]]. Unknown tokens are ignored.
How it works
For a fixed vocabulary, count vectors are sparse: each column represents a training term. With scikit-learn defaults smooth_idf=True and sublinear_tf=False, IDF(t)=log((1+n)/(1+df(t)))+1 and raw weight is count(t,d)*IDF(t); default norm=l2 divides each nonzero row by its Euclidean norm. Document frequency counts documents containing a term, not occurrences. Empty or entirely OOV documents yield zero vectors if a nonempty vocabulary was fitted. Fit vocabulary and IDF only on training text; put vectorizer and classifier in Pipeline for CV. With a custom tokenizer set token_pattern=None; use lowercase=False when the preprocessing policy already casefolds. Word n-grams capture limited order, character n-grams may help spelling variants but increase feature count. Sparse matrices should not be converted to dense on large corpora. Text duplicates, template families and author-specific markers can leak; split by source group before fitting.
TF-IDF without row normalization
from sklearn.feature_extraction.text import TfidfVectorizerv=TfidfVectorizer(norm=None)x=v.fit_transform(["red red blue","blue"])print(v.idf_.round(6).tolist(),x.toarray().round(6).tolist())Expected output (locally tested): [1.0, 1.405465] [[1.0, 2.81093], [1.0, 0.0]]. Red occurs in one document; its raw count is two.
Common mistakes
Do not use IDF from held-out documents, confuse counts with document frequency, or treat a zero vector as proof of a negative label.
Practice and next steps
Calculate smoothed IDF for a term appearing in one of two documents. Compare an all-OOV query to a known term.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bag of words and TF-IDF — knowledge check
Apply bag of words and tf-idf to small examples and debugging scenarios.
What is document frequency?
Which data fits IDF?
What does a fully OOV query yield in a frozen count vectorizer?
What does default L2 normalization do?
What can a word bigram retain?