Sub topic 19
Limitations and alternatives
This chapter assumes you can build CountVectorizer and TfidfVectorizer features, read a sparse document-term matrix, and compare vectors with cosine similarity. It explains where those features fail, how to spot each failure, and what to use when they do.
What bag of words throws away
A bag-of-words vector records which vocabulary terms occur in a document and how often or how heavily. TF-IDF changes the weights but not the structure. Three kinds of information are lost.
- Word order. Only counts survive, so documents that contain the same words get the same vector.
- Meaning. Each term is its own column. The model has no idea that "good" and "great" are related.
- Unseen words. Any word not in the fitted vocabulary is silently ignored at prediction time.
The code below shows all three.
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# 1. Word order is lost: both sentences give the same count vector.
order = ["dog bites man", "man bites dog"]
counts = CountVectorizer().fit_transform(order)
print("identical vectors:", (counts[0] != counts[1]).nnz == 0)
# 2. Synonyms look unrelated: no shared terms, so cosine similarity is 0.
synonyms = ["a great film", "a good movie"]
tfidf = TfidfVectorizer().fit_transform(synonyms)
print("synonym similarity:", cosine_similarity(tfidf[0], tfidf[1])[0, 0])
# 3. Unseen words vanish: the new document maps to an all-zero row.
vec = CountVectorizer().fit(["the cat sat"])
new_row = vec.transform(["the dog ran"])
print("known terms in new doc:", vec.get_feature_names_out()[new_row.toarray()[0] > 0])The first check prints True. The second prints 0.0. The third finds only the, because dog and ran were never in the vocabulary.
Failure modes in practice
Negation and scope
"The plot was good" and "the plot was not good" share most of their terms. With unigrams, the only difference is one extra not column, and a linear model can give that column only a small, global weight. Bigrams such as not good help, because the phrase becomes its own feature. They do not cover long-range cases like "I did not think it was good". Setting ngram_range=(1, 2) also grows the vocabulary quickly, so combine it with min_df pruning.
Vocabulary mismatch
Retrieval and similarity search need the query and the document to share terms. A search for "car repair" will not find a page about "automobile maintenance". Raising the weight on rare terms with IDF does not help, because the problem is the absence of any shared column.
Out-of-vocabulary terms and drift
The vocabulary is frozen at fit time. New product names, slang, typos and misspellings all land outside it. Over months, a model trained on old text sees a growing share of its input ignored. Monitor the fraction of tokens in incoming documents that are in the vocabulary. A falling rate is an early sign that retraining is due.
Dimensionality and sparsity
A realistic corpus gives tens or hundreds of thousands of columns. Sparse storage keeps memory manageable, but not every method can use sparse input. Dense algorithms and many distance-based methods become slow or unusable. Also, with many columns and few documents, a model can fit noise. Regularization and vocabulary pruning reduce this risk but do not remove it.
Sensitivity to preprocessing
Results depend on choices that look minor: the token pattern, lowercasing, stop-word lists, and whether numbers are kept. The default token pattern drops one-character tokens, which removes "a" and "I" but also tokens like "C" or "R" in programming text. A stop-word list suited to news can delete words that carry signal in another domain, such as "not" in sentiment tasks. The scikit-learn English list contains "not", which is a common cause of lost negation. Check the list against your task before relying on it.
Corpus-dependent weights
IDF values come from the training corpus, so the same word gets different weights in different corpora. TF-IDF vectors from two separately fitted vectorizers live in different spaces and cannot be compared. If you add documents and refit, every old vector must be recomputed.
Choosing an alternative
The right replacement depends on which limitation hurts.
| Problem | Option | What it changes | Cost |
|---|---|---|---|
| Vocabulary too large or must be stateless | `HashingVectorizer` | Maps tokens to a fixed number of columns with a hash. No vocabulary is stored. | Cannot recover which word a column means. Collisions mix terms. No IDF unless you add `TfidfTransformer`. |
| Better ranking for search | BM25 | Saturates term frequency and adjusts for document length. | Needs a retrieval library or your own code. Still lexical, so no synonym matching. |
| Noisy, redundant dimensions | Latent semantic analysis (`TruncatedSVD` on TF-IDF) | Projects to a few hundred dense dimensions where co-occurring terms share directions. | Dense output. Dimensions are hard to interpret. Gains are modest. |
| Word meaning | Pretrained word embeddings (word2vec, GloVe, fastText) | Each word becomes a dense vector. Related words are close. | Averaging word vectors loses order and can dilute rare, informative terms. |
| Meaning of whole sentences, order and context | Sentence embeddings or fine-tuned transformer models | Represent a whole text in context. Handle synonyms and negation much better. | More compute, more setup, less transparency. Often needs a GPU for fine-tuning. |
When TF-IDF is still the right choice
Do not treat these limits as a reason to skip bag of words.
- It trains in seconds on a CPU and needs no pretrained model.
- Linear models on TF-IDF are often strong baselines on topic classification, spam detection, and long documents where vocabulary carries most of the signal.
- The weights are inspectable. You can list the highest-weighted terms for each class and see why a prediction was made.
- It works for languages and domains where no good pretrained model exists.
A sound workflow is to build the TF-IDF pipeline first, record its cross-validated score, and move to a heavier method only if the gap on a held-out set justifies the cost. If a transformer model gains one point of accuracy but costs ten times the compute and loses explainability, the baseline may still be the better engineering choice.
Exercises
Exercise
A sentiment classifier built on TfidfVectorizer(stop_words="english") often labels "not good at all" as positive. Give two causes tied to bag-of-words limits, and one change for each.
Show answer
Cause 1: the English stop-word list contains "not", so the negation is removed before the model sees it. Change: drop stop_words or use a custom list that keeps negations. Cause 2: with unigrams only, "good" is a positive feature on its own and the model cannot see that "not" modifies it. Change: use ngram_range=(1, 2) so not good becomes its own feature, with min_df to control vocabulary growth.
Exercise
You need to embed a continuous stream of short messages, and the vocabulary keeps growing with new slang. You also need to be able to compute features without storing state between runs. Which option from this chapter fits best, and what do you give up?
Show answer
HashingVectorizer. It maps tokens to a fixed number of columns, so it needs no stored vocabulary and handles new words without refitting. You give up the ability to map a column back to a word, you accept some hash collisions, and you get no IDF weighting unless you apply TfidfTransformer on top (which then needs to be fitted on training data).