Sub topic 13
Limitations and where to go next
This chapter closes the tutorial. It assumes you can build and evaluate the TF-IDF plus logistic regression pipeline from the earlier chapters. It also assumes you know what a held-out set, cross-validation and a coefficient are. Here you will see what this model family cannot do, how to spot those failures in your own data, and what to try next.
Why this baseline is still worth having
A TF-IDF and logistic regression pipeline trains in seconds on a laptop, and it needs no GPU. You can inspect its coefficients, and it is hard to break. On topic-style tasks such as routing support tickets, tagging news or filtering spam, it is often within a few points of far larger models. Build it first, even if you expect to replace it. It gives you a number to beat and a quick check that your labels are usable.
Its limits come from three design choices:
- Each document is a bag of independent terms, so word order is discarded.
- The vocabulary is fixed at training time, so unseen words are ignored.
- The decision rule is linear, so each term adds a fixed amount of evidence regardless of context.
Limitation 1: word order and context are lost
A unigram document-term matrix counts words and nothing else. Two documents with the same words in a different order get the same vector.
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
docs = ["dog bites man", "man bites dog"]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(docs).toarray()
print(vectorizer.get_feature_names_out())
print(np.allclose(X[0], X[1]))The final line prints True. For topic classification this rarely matters, because the vocabulary of a space article differs from that of a car review. For tasks where meaning depends on who did what to whom, it matters a great deal. Negation is the usual example. "The battery is good" and "The battery is not good" differ by one common word, and a unigram model has to treat "not" as a weak signal that applies everywhere.
Adding bigrams, as you did with ngram_range=(1, 2), recovers some local context because "not good" becomes its own feature. This helps only partly:
- The vocabulary grows quickly, and most bigrams are rare.
- Negation can reach further than two words, as in "not at all what I would call good".
- Sarcasm, hedging and comparisons ("better than before, but still bad") depend on the whole sentence.
Limitation 2: unseen words and surface forms
The vocabulary is learned from the training set. At prediction time, any word outside it is silently dropped. If a document contains no known terms, its row is all zeros, and the classifier falls back on the intercept, which reflects the training class balance.
from sklearn.feature_extraction.text import TfidfVectorizer
train_docs = [
"the rocket reached orbit",
"the engine of the car stalled",
"the senator proposed a new bill",
]
vectorizer = TfidfVectorizer()
vectorizer.fit(train_docs)
unseen = vectorizer.transform(["quantum entanglement experiments"])
print(unseen.nnz)This prints 0. A model deployed on text from a different period or community will see more and more of these empty or nearly empty rows. Spelling variants, typos, new product names and slang cause the same problem. "Classification" and "clasification" are unrelated columns as far as the model knows.
Character n-grams are a cheap partial fix. They break each word into overlapping character pieces, so near-identical spellings share features.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
pair = ["classification", "clasification"]
word_vec = TfidfVectorizer(analyzer="word")
char_vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 4))
word_sim = cosine_similarity(word_vec.fit_transform(pair))[0, 1]
char_sim = cosine_similarity(char_vec.fit_transform(pair))[0, 1]
print(round(word_sim, 2), round(char_sim, 2))The word analyzer finds no shared tokens, so its similarity is 0.0. The character analyzer finds many shared pieces, so its similarity is clearly above zero. The cost is a much larger feature space and coefficients that are harder to read.
Limitation 3: no notion of meaning
TF-IDF treats "car", "automobile" and "vehicle" as three unrelated columns. If your training data uses "car" and your production data uses "automobile", the model must learn each word separately, and it can only do so for words it has seen with labels. Synonymy and polysemy (one word with several senses, such as "bank" or "python") are invisible to it.
The model needs enough labeled examples for each phrasing of an idea. This is why bag-of-words models need more labeled data than pretrained models when the vocabulary is varied, and why they work best when the label is tied to distinctive vocabulary.
Limitation 4: a linear model with fixed term weights
Logistic regression adds up one weight per term. It cannot represent "this word is positive in the context of restaurants but negative in the context of movies" unless you build separate features or separate models. "Unpredictable" is a good example: praise for a thriller, criticism for a car.
Interactions are possible only by hand, for example by prefixing tokens with a domain tag. A nonlinear model such as gradient boosting can learn interactions, but on sparse, high-dimensional text it rarely beats a regularized linear model without much more tuning.
Limitation 5: evaluation and data problems that no model fixes
Several failures come from the data and the evaluation setup. They apply equally to the more advanced models in the next section.
- Leakage through shortcuts. In the newsgroups example, removing headers, footers and quotes lowers the score because those parts identified the group directly. If your own data has signatures, boilerplate, ticket IDs or template text that correlates with the label, the model will learn them. The top coefficients usually show this first.
- Distribution shift. A held-out set drawn from the same period and source as the training data overestimates performance on future data. Where possible, split by time.
- Label noise and ambiguity. If annotators disagree, the ceiling on any metric is lower than 100%. Check agreement on a sample before spending effort on model changes.
- Probabilities that are not calibrated. Regularized logistic regression is usually better calibrated than many classifiers, but with strong regularization or class weights its probabilities drift. Do not use them as true confidences without checking, for example with a reliability curve or
CalibratedClassifierCV.
Summary of failure modes
| Limitation | Cause | Typical symptom | Cheap mitigation |
|---|---|---|---|
| Word order lost | Bag-of-words representation | Negation and role reversal misclassified | Bigrams, or a sequence model |
| Unseen words | Fixed vocabulary | Empty rows, rising errors over time | Retrain regularly, character n-grams |
| No semantics | Each term is an independent column | Synonyms need separate training examples | Pretrained embeddings |
| Linear terms | One fixed weight per term | Context-dependent words are mishandled | Domain-specific models or features |
| Shortcuts | Spurious correlates of the label | Great validation score, poor deployment | Inspect coefficients, clean the text, split by source or time |
| Shift | Training data differs from production | Gradual decline in metrics | Monitor inputs and outputs, retrain |
Diagnosing before you switch models
Changing to a bigger model is expensive. First find out which limitation is actually hurting you.
- Read 50 to 100 misclassified validation documents. Sort them into groups: negation, unseen vocabulary, label noise, genuinely ambiguous.
- Check how many validation documents have few or no in-vocabulary tokens.
- Look at the top coefficients per class for shortcuts such as names, dates or boilerplate.
- Compare training and validation scores. A large gap points to overfitting and stronger regularization, not a new architecture. A small gap with a low score points to missing information in the features.
Where to go next
Each option below targets a specific limitation above.
Stay linear, change the features or the loss
- Linear SVM (
LinearSVC) often matches logistic regression on accuracy and is fast on sparse data, but it does not give probabilities directly. - Complement or multinomial naive Bayes is a strong choice with very little data and trains almost instantly.
HashingVectorizerremoves the stored vocabulary, which saves memory on very large corpora and allows streaming. The tradeoff is that you cannot map columns back to words, so coefficient inspection is lost, and different words can collide in the same column.- Character n-grams help with typos and morphology, as shown above.
Use pretrained embeddings
Sentence embedding models turn each document into a dense vector, which captures synonymy. You can feed these vectors into the same LogisticRegression class. This keeps the training workflow you already know, and it often works well with a few hundred labeled examples. You lose word-level interpretability, so the coefficient reading from the earlier chapter no longer applies.
Fine-tune a transformer
If context matters (negation, sarcasm, long-range dependencies) and you have a few thousand labeled documents, fine-tuning a pretrained transformer is the standard approach. It needs more compute, more careful evaluation, and a plan for latency and cost. Keep the TF-IDF pipeline as the comparison, and adopt the larger model only if it beats the baseline by a margin that justifies the extra cost.
Improve the process
- Build an error-analysis habit: review a sample of mistakes after every change.
- Use a time-based or source-based split when deployment data will differ from training data.
- Track the share of out-of-vocabulary tokens and the predicted class distribution in production. Both are cheap drift signals and need no labels.
- Calibrate probabilities if you use them to make thresholded decisions.
Chapter recap
A TF-IDF and logistic regression classifier is fast, transparent and strong on vocabulary-driven tasks. It struggles where meaning depends on word order, context or synonyms, and it quietly ignores words it never saw during training. Many of its failures are data failures, so inspect your errors and coefficients before changing the model. Move to character n-grams, embeddings or a fine-tuned transformer only when the error analysis points to a limitation they actually address.
Exercise
You trained a TF-IDF and logistic regression model to classify product reviews as positive or negative. Validation F1 is 0.88, but on reviews collected three months later it drops to 0.74. Reading the errors, you see many reviews that mention new product names and slang. Which limitation is the most likely cause, and name two checks or fixes you would try before switching to a transformer.
Show answer
The most likely cause is the fixed vocabulary combined with distribution shift. New product names and slang are out-of-vocabulary, so the model drops them and has little to work with. Checks and fixes: measure the share of tokens or documents with few in-vocabulary terms in the new data, retrain on recent labeled data, try character n-grams, and set up a time-based split so future validation reflects this drift.
Exercise
A colleague adds ngram_range=(1, 2) and says it solves the negation problem. Give two reasons this is only a partial solution.
Show answer
Bigrams only capture two adjacent words, so negation that spans more words ("not at all what I would call good") is missed. Bigrams also enlarge the vocabulary with many rare features, which raises the risk of overfitting and means most bigram features have few training examples. Sarcasm and hedging depend on the whole sentence, which bigrams cannot represent.
Exercise
Write a short check, in Python, that confirms two documents with the same words in a different order produce identical unigram TF-IDF vectors, and state what it shows about the representation.
Show answer
Fit TfidfVectorizer() on ["dog bites man", "man bites dog"], convert the result with .toarray(), and call np.allclose(X[0], X[1]). It returns True. This shows the unigram representation ignores word order entirely, so the model cannot distinguish the two sentences.