Bag-of-Words Feature Extraction with CountVectorizer
Lemmatization reduces words to their base or root form, and in the source's example it cut the feature count from 27,271 to 21,596 while the number of documents stayed at 25,000.
Try it: Text Vectorization: Tokens to Vectors
The text-to-tensor pipeline: standardize, split into tokens, build a frequency-ranked vocabulary with padding and [UNK], map tokens to integer ids, pad or truncate, then one-hot or multi-hot encode and look the ids up in an embedding table.
How it works
- Standardize: lowercase and delete punctuation.
- Split on whitespace into tokens.
- Build the vocabulary: 0 = padding, 1 = [UNK], then words by frequency (ties: first appearance), capped at max tokens.
- Map each token to its id (1 if it did not make the vocabulary), then pad with 0 or truncate to the sequence length.
- Encode: one-hot rows per position or one multi-hot row per text; embed: id k selects row k of the embedding table.
Default run (18 steps): Raw text (59 characters): "The movie was great. The plot was great, the acting wasn't!". A model cannot read strings, so it is turned into numbers step by step. … Embedding lookup: id k selects row k of a fixed 8 x 3 table, giving a (8, 3) dense matrix instead of (8, 8) sparse one-hots. Row 0 (padding) is looked up too; a trained Embedding layer would learn these rows.
Simplified: Bounded ASCII text (up to 200 characters, 40 tokens), whitespace splitting only, and a small FIXED embedding table (a real Embedding layer learns its rows). The multi-hot vector keeps the padding slot (always 0) so its positions line up with the ids.
Loading the simulation…
Predicting the Shape Before Running Anything
This article starts with a prediction rather than a definition. Two text representations are built from the same training data, and each one reports its shape. The shape is a pair of numbers: the first counts rows, which are documents, and the second counts columns, which are features. Before you look at any output, try to say what each print line will report. Then check your guess against the numbers below.
What do you think happens?
Lemmatization reduces words to their base form before counting. If the standard CountVectorizer produces 25,000 rows and 27,271 columns on the training data, what shape does the lemmatized vectorizer produce on the same documents?
Reveal answer
25,000 rows and 21,596 columns. The number of documents stays the same, and the vocabulary shrinks.
Lemmatization merges different surface forms of a word into one base form. Fewer distinct vocabulary terms means fewer columns. Nothing about the documents themselves is removed, so the row count does not change.
What a Bag-of-Words Column Holds
A bag-of-words representation turns each document into a row of counts. Every column corresponds to one vocabulary term, and each cell records how often that term appears in that document. The word order is discarded; only the counts remain. The result is a matrix with one row per document and one column per term.
This structure explains what a column means. If two different surface forms of a word, such as a verb and its past tense, are each counted as their own term, the model must learn from each column separately. The model sees two sparse columns that carry partly overlapping meaning, and it must learn their weights independently. This is the setting in which lemmatization changes the picture.
Lemmatization: a text processing step that reduces words to their base or root form, so that different surface forms of a word are counted together.
Tracing a Column Merge Step by Step
The diagram below is an illustration built for this article, not a real output from the source. It follows three surface forms through lemmatization. Before the step, each form occupies its own column. After the step, all three forms share one base-form column, and that column pools the evidence from every form.
Notice what does not change. Each document still has a count in every remaining column, and the documents are the same documents. Only the set of columns is different. Three columns became one, so the remaining column carries the combined count of all three forms.
Measuring the Feature Reduction in the Source Example
Computing the size of the vocabulary reduction
The standard vectorizer produces 27,271 features, and the lemmatized vectorizer produces 21,596 features on the same 25,000 documents. How many features were removed, and what fraction of the original columns is that?
- 1Confirm the row count
Both matrices have 25,000 rows, because lemmatization changes the vocabulary, not the number of documents.
- 2Compute the difference
$27{,}271 - 21{,}596 = 5{,}675$ features were removed.
- 3Compute the fraction
$\frac{5{,}675}{27{,}271} \approx 0.208$, so roughly 21 percent of the original columns disappeared.
The lemmatized matrix has 5,675 fewer columns, about 21 percent of the original, and the same 25,000 rows.
The reduction is a fact about the matrix shape. It does not yet say anything about accuracy. A smaller matrix is a different object from a better model, and the next section explains the reasoning behind expecting a benefit at all.
Why Fewer Columns Can Act as Regularization
The source gives a specific reason to expect a benefit. Because lemmatization conflates some features, it works like regularization. Regularization limits how much freedom a model has to fit fine details of the training data. When distinct columns are merged, the model has fewer independent weights to adjust, so it has less room to chase patterns that are accidents of one particular sample.
That is also why the source expects the benefit to matter most on small datasets. With little training data, a model with many sparse columns has more opportunities to latch onto accidental patterns, because many columns are supported by only a few documents. Merging columns reduces that risk. On a large training set the model has enough evidence to separate the surface forms, so the merge is less likely to help much.
Setting Up the Cross-Validation Comparison
To test the regularization expectation, the source does not train on the full 25,000-document set. It uses only 1 percent of the data as training data and the rest as test data. The splitter is StratifiedShuffleSplit, which produces random splits, and the experiment runs five of them. The regularization strength C is tuned with GridSearchCV around LogisticRegression, so each representation is evaluated with its own tuned model.
Because the training set is so small, this setup is the case where the regularization argument predicts the largest benefit. It is a deliberate test of the expectation, not a routine evaluation of the full dataset.
Reading the Size of the Gain
| Representation | Mean score (1% training, five splits) | Difference from standard |
|---|---|---|
| Standard CountVectorizer | 0.721 | Baseline |
| Lemmatized vectorizer | 0.731 | +0.010 |
Cross-validation result reported by the source for the two representations
The lemmatized pipeline scored 0.731 and the standard representation scored 0.721. The source calls this a modest improvement. On the score scale the gain is 0.010. It was observed in this one setup, with 1 percent training data and five random splits, so it is evidence for this experiment rather than a general guarantee.
The pack gives only the averages for the two representations. It does not report fold-by-fold scores or the spread across folds, so this source cannot tell you whether 0.010 is large compared with the variation between splits. To judge that, you would need the individual fold scores from the same run.
The source also notes that the result depends on the dataset, as many feature extraction techniques do. It says lemmatization and stemming can help build better models, or at least more compact ones. Those are two different wins. A representation may be smaller without being more accurate, and a small accuracy gain may still be worth a more compact vocabulary.
Finding Where a Surprise Enters the Pipeline
Suppose you run the first snippet and expect a smaller matrix, but the lemmatized shape prints 27271 columns. The diagram below traces the comparison pipeline in order. The checkpoint for an unexpected shape is the first stage where the lemmatized matrix exists. Check that stage before touching the model or the search.
The first print line already points to the cause. The lemmatized matrix came from lemma_vect.fit_transform, so the problem lies in that object or in the text it received. It does not lie in the standard CountVectorizer line that follows. Checking stages in order, starting with the shape of each matrix and the object that produced it, is more efficient than changing the model or the search.
Common mistake Judging lemmatization only by how many columns disappear
Why it failsA smaller vocabulary shows that the matrix changed. It does not show that the model improved.
Do this insteadRead the shape for the size of the change, then read the cross-validation scores to judge accuracy.
Common mistake Treating a 0.010 gain as a general result
Why it failsThe source observed this gain in one setup, with 1 percent training data and five random splits, and says the result varies by dataset.
Do this insteadDescribe the gain as evidence for that experiment, and test it on your own data before relying on it.
Common mistake Changing the model when the shape is wrong
Why it failsAn unexpected column count comes from the vectorizing stage, so tuning the classifier cannot fix it.
Do this insteadStart with the shape of each matrix and the object that produced it, then move down the pipeline.
Checking Your Reading of a Comparison
A colleague reports that lemmatization cut the vocabulary from 27,271 to 21,596 features and says that this proves the lemmatized model is more accurate. Using the source numbers, explain what the shape change establishes, what the score comparison establishes, and what remains untested.
Hints
- Separate the shape result from the accuracy result before you answer.
- The score comparison reports a gain of 0.010 in one setup with 1 percent training data.
- The pack does not give fold-by-fold scores, so you cannot judge the spread from it.
Key Takeaways
- Lemmatization maps different surface forms of a word to a shared base form, so a bag-of-words matrix keeps the same rows and gets fewer columns. In the source example, the vocabulary fell from 27,271 to 21,596 features on 25,000 documents.
- Merging columns acts as a form of regularization because it limits how freely the model can fit details, which is why the source expects the benefit to matter most when the training set is small.
- In the source's 1 percent training experiment with five random splits, the lemmatized pipeline scored 0.731 against 0.721, a modest gain of 0.010 that the source says varies by dataset.
- A smaller matrix is not automatically a better model. Compactness and accuracy are separate outcomes, and each needs its own evidence.
- When a comparison looks wrong, check each stage in order, starting with the shape of each matrix and the object that produced it, before changing the model or the search.