Concepts / Implementing Lemmatization in Text Preprocessing

Implementing Lemmatization in Text Preprocessing

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.

  • Programming

Predicting the Shape Before Running Anything

This article starts with code instead of theory. The excerpt below builds two text representations of the same training documents and prints the shape of each one. Shape tells you how many rows and how many columns a matrix has. In this setting, rows are documents and columns are features. Before you read the output, try to say what each print line will report. Your prediction is the point of the exercise, because the difference between what you expected and what the output shows is where the learning happens.

python
Output (expected)
(25000, 27271)
(25000, 21596)
Notes on the code
  • train_docs is assumed to be the 25,000-document training text.
  • lemma_tokenizer is a function you supply. It takes a document string and returns lemmatized tokens. This article does not assume any particular lemmatizer library.
  • The first print line reports the standard representation; the second reports the lemmatized one. The printed output shown here reflects the source's reported numbers for this data.

What do you think happens?

Before reading the output: will the lemmatized matrix have more columns, fewer columns, or the same number of columns as the standard matrix? And will the number of rows change?

  • More columns, same rows

  • Fewer columns, same rows

  • Same columns, fewer rows

  • Fewer columns, fewer rows

Reveal answer
Answer:

Fewer columns, same rows. The lemmatized matrix has 21,596 columns where the standard one has 27,271, and both still have 25,000 rows.

Lemmatization changes which vocabulary terms become separate columns, not how many documents you have. Rows are documents, and the document count stayed at 25,000.

Reading Shape as a Feature Count

A bag-of-words matrix has one column for each vocabulary term. Each column counts how often that term appears in each document. So the number of columns is the number of features the model can use. When you change how words are normalized before counting, you change the vocabulary, and the column count follows. Shape output is therefore a fast check on what preprocessing actually did.

Before

CountVectorizer on raw tokens: 25,000 rows, 27,271 feature columns

27,271 feature columns

After

CountVectorizer on lemmatized tokens: 25,000 rows, 21,596 feature columns

21,596 feature columns

Look at what changed and what did not. The number of columns dropped, and the number of rows, which counts documents, did not change at all. Lemmatization does not remove documents or alter any document's text length in the matrix sense. It changes the set of column labels, so that several surface forms of a word share one column.

Worked example

Measuring the Feature Count Reduction

The standard representation has 27,271 features and the lemmatized representation has 21,596 features, with 25,000 documents in both. How many features were removed, and what fraction of the original columns does that represent?

  1. 1
    Find the difference in feature counts

    Subtract the lemmatized count from the standard count: 27,271 minus 21,596 equals 5,675 features removed.

  2. 2
    Express the difference as a fraction of the original

    Divide the removed count by the original feature count: $\frac{5675}{27271} \approx 0.208$.

  3. 3
    Convert to a percentage

    $0.208$ is about 21 percent, so lemmatization removed roughly one fifth of the original columns.

  4. 4
    Confirm what stayed the same

    The document count is 25,000 in both representations. Only the feature dimension changed.

Result

Lemmatization removed 5,675 features, about 21 percent of the original columns, and left the 25,000 documents unchanged.

Many Word Forms, One Column

Lemmatization reduces words to their base or root form. Different surface forms of the same word, such as running, runs, and ran, can all map to one base form. Once that mapping is applied before counting, the three forms no longer each get their own column. Their counts pool into a single column for the base form. The mapping is many-to-one: several keys point to one value.

runningsurface formrunone shared columnrunssurface formransurface formmaps tomaps tomaps to
Which surface word forms collapse into a single lemma, and how does that many-to-one mapping reduce the vocabulary?

Read the diagram as a vocabulary reduction. Before lemmatization, the three forms would be three separate columns, each counting its own occurrences. After lemmatization, the counts for all three accumulate in one column. Multiply this pattern across a whole corpus, and it accounts for the drop from 27,271 to 21,596 features in the source's example. Each remaining column now pools evidence from several surface forms.

Why Fewer Columns Can Help

A smaller feature set is not automatically a better model. 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. Merging columns that carry overlapping meaning means the model has fewer separate knobs to tune to accidental patterns.

The effect is expected to matter most when the dataset is small. With little training data, a model that has many sparse columns has more chances to latch onto patterns that appear only by chance. A word that shows up in two or three training documents gives the model very little evidence, yet it still gets its own column. Merging those rare forms into a shared column pools their evidence and reduces that risk. With a large training set, there is more evidence per column to begin with, so the regularizing effect of merging is expected to matter less.

The One-Percent Experiment Design

To test the small-dataset expectation, the source does not train on the full 25,000-document set. It runs a cross-validation experiment that uses only 1 percent of the data as training data, with the rest serving as test data. The splitter is StratifiedShuffleSplit, which produces five random splits. Inside each split, GridSearchCV searches over the regularization strength C for a LogisticRegression model. Both the standard CountVectorizer arm and the lemmatized arm go through this same search, so the comparison isolates the effect of the preprocessing step.

ArmPreprocessing before countingFeature columnsCV score
StandardCountVectorizer on raw tokens27,2710.721
LemmatizedCountVectorizer with lemmatized tokens21,5960.731

Source-reported results for 1 percent training data, five random splits, with C tuned by GridSearchCV around LogisticRegression.

Notice that the two arms differ in exactly one stage: how the text is tokenized and normalized before counting. The splitter, the search, and the classifier are the same. That is what lets you attribute the score difference to the preprocessing rather than to the model setup. The table also shows the two wins the source mentions: the lemmatized arm uses fewer columns and scores slightly higher.

Reading the Size of the Gain

The lemmatized pipeline scored 0.731 against 0.721 for the standard representation. The gain is a difference of 0.010 on the score scale. The source calls this a modest improvement. Read the number carefully: it is a real difference in this experiment, but it is small, and it was observed under one specific setup of 1 percent training data with five random splits.

The source is also careful about generality. It states that the result varies depending on the dataset, as many feature extraction techniques do. It notes that lemmatization and stemming can sometimes help build better, or at least more compact, models. So there are two possible wins to check separately: accuracy and compactness. A small accuracy gain may still be worth a much more compact vocabulary, and a compact vocabulary may give no accuracy gain at all.

Locating the Unexpected Result

Now return to the opening code. Suppose you expected a smaller matrix from the lemmatized arm, but its shape prints 27,271 columns, which matches the standard arm. Where should you look? Work through the pipeline in order and check each stage's output against what you expected, starting with the earliest stage that could have gone wrong. Do not change the model or the search first. The first print line already points to the cause: the lemmatized matrix was produced by lemma_vect.fit_transform, so the problem lies in that object or in the text it was given, not in the standard CountVectorizer line that follows.

Training text25,000 documentslemma_vect.fit_transformfirst check: lemmatizedshapeLemmatized shapeunexpected: 27,271 columns1 percent splitStratifiedShuffleSplitGridSearchCVtunes C forLogisticRegressionStandardCountVectorizerraw tokensStandard shape27,271 columnsfit_transformprints shapefit_transformprints shapeonly if shape is correctper split
Which step in the preprocessing-to-cross-validation pipeline first produces the unexpected result, and what flows into it?

The diagram shows why the order matters. The shape check after lemma_vect.fit_transform is the first place the discrepancy can be seen. Everything downstream, including the split, the grid search, and the scores, receives whatever that stage produced. If the lemmatized matrix is wrong at its first output, every later score is built on the wrong features, so comparing scores before checking shapes would waste effort.

Mistakes Beginners Make

  • Common mistake

    Assuming fewer columns means a better model

    What it looks like

    Seeing 21,596 columns instead of 27,271 and concluding the lemmatized model must score higher.

    Why it fails

    The source ties the benefit to regularization and says the effect varies by dataset. Column count alone does not establish accuracy.

    Do this instead

    Compare the CV scores under identical settings, and treat the column reduction as a separate fact to report alongside them.

  • Common mistake

    Reading the row count as changed by lemmatization

    What it looks like

    Expecting the lemmatized matrix to have fewer rows because words were merged.

    Why it fails

    Rows are documents. Lemmatization changes the vocabulary, and the source's example kept 25,000 documents throughout.

    Do this instead

    Check the first element of the shape tuple against the document count and expect it to match in both arms.

  • Common mistake

    Generalizing the 0.010 gain

    What it looks like

    Writing that lemmatization adds 0.010 accuracy to any text classifier.

    Why it fails

    The gain was observed in one experiment with 1 percent training data and five random splits, and the source says results vary by dataset.

    Do this instead

    Report the gain with its setup, and run the same comparison on your own data before claiming a benefit.

  • Common mistake

    Debugging the model when the shape is wrong

    What it looks like

    Adjusting C in GridSearchCV after the lemmatized matrix prints the standard column count.

    Why it fails

    The unexpected value comes from the vectorization stage, so tuning the model cannot fix the features it receives.

    Do this instead

    Check each stage in order, starting with the shape and the object that produced it, before touching the model or the search.

  • Common mistake

    Forgetting that the lemmatizer must actually be passed to the vectorizer

Practice: Trace the Pipeline

MEDIUM

You build a lemmatized vectorizer and a standard vectorizer on the same 25,000 training documents. The lemmatized shape prints (25000, 27271) and the standard shape prints (25000, 27271). Before running any model, state which stage you would inspect first, what you would expect its output to be, and why you would not start by tuning C.

Hints
  • Which print line reports the lemmatized matrix, and which object produced it?
  • A correct lemmatized vectorizer should reduce the column count relative to the standard one in the source's example.
  • Downstream stages, including the split and GridSearchCV, only receive what the vectorizer outputs.

Key Takeaways

  • Lemmatization maps surface word forms to a base or root form, so several forms can share one column in a bag-of-words matrix.
  • In the source's example, lemmatization reduced features from 27,271 to 21,596, removing 5,675 columns (about 21 percent) while the 25,000 documents stayed the same.
  • Because lemmatization merges some features, it acts like regularization, and the source expects that benefit to matter most when training data is small.
  • In the 1 percent cross-validation experiment, the lemmatized arm scored 0.731 against 0.721 for the standard arm, a modest gain of 0.010 that is specific to that setup and varies by dataset.
  • When a result is unexpected, check shapes stage by stage, starting with the object that produced the matrix, before changing the model or the search.

Related concepts

More concepts starting with I