Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 133/ 160
07. Deep Learning & NLP

Text Preprocessing (Tokenization, Lemmatization)

Normalize text with tokenization, stopwords, stemming/lemmatization for classical NLP.

BeginnerTokenize · Lemma3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Before a computer can count words, you tidy the text: make letters the same case, split it into words, drop the very common ones and turn words like running and runs into the same base word.

Think of it like…

Sorting mail before delivery. You straighten the envelopes (normalisation), separate them into individual pieces (tokenisation), discard junk flyers (stop words) and file variations of the same name under one entry (stemming or lemmatisation), but if you throw away the word "not" you may deliver the opposite message.

Where you’ve seen it

The sentence "The Cats are running quickly!!" is lowercased and tokenised into the, cats, are, running, quickly after the punctuation is stripped. Removing English stop words leaves cats, running, quickly. A Porter stemmer produces cat, run and quickli (stems need not be real words), while a WordNet lemmatiser given the right part of speech returns cat, run and quickly. The part of speech matters: lemmatising running as a noun leaves it unchanged, but as a verb gives run. On a small vocabulary example, the five forms Run, run, RUNNING, runs, ran are five types; lowercasing reduces them to four, stemming to two (run, ran) and verb lemmatisation to one. A sentiment team found that the default stop-word list contains not, so "not good" became "good" and accuracy on negated reviews dropped; they kept negations and added bigrams. They also fitted the vocabulary and min_df threshold on the training split only, wrapped every step in a scikit-learn pipeline so that production uses exactly the same transformation and, for the later transformer model, deleted the stemming and stop-word steps and used the model's own tokeniser instead.

Words you’ll hear

Token
A unit of text produced by tokenisation: a word, character or subword.
Stop words
Very frequent function words such as the, of and is, often removed in classical pipelines.
Stemming vs lemmatisation
Rule-based suffix chopping versus dictionary-based mapping to a lemma.
Vocabulary
The set of distinct tokens a model knows.

Visual diagram

Loading interactive diagram

Theory & deep dive

Normalising and tokenising

Start with normalisation: Unicode normalisation (NFKC) so visually identical characters match, lowercasing when case carries no meaning, collapsing whitespace, and decisions on URLs, emails, numbers, hashtags and emojis (replace with a placeholder token, or keep emojis for sentiment). Tokenisation splits text into units: whitespace splitting is brittle, regex tokenisers handle punctuation, language-aware tokenisers (spaCy, NLTK) handle contractions and abbreviations, and subword tokenisers (BPE, WordPiece) split rare words into frequent pieces so there is no out-of-vocabulary problem. Tokenisation choices change the vocabulary size and downstream accuracy, so treat them as hyperparameters.

Count the effect: Run, run, RUNNING, runs and ran are five types. Lowercasing merges Run with run, leaving four; Porter stemming maps running and runs to run, leaving two types (run and ran); lemmatising as verbs maps ran to run too, leaving one. For a corpus with a 40,000-word vocabulary this kind of reduction can shrink the feature space by a third or more and lets rare variants share evidence, but each merge also loses distinctions that may matter (for example, between a noun and a verb).

Vocabulary reduction

Tokens: Run, run, RUNNING, runs, ran → 5 types. Lowercase: run, running, runs, ran → 4. Porter stem: run, run, run, ran → 2. Verb lemma: run ×5 → 1.

Key takeaway: Normalise and tokenise consistently, and treat each merge as a trade between fewer features and lost nuance.

Stop words, stemming, lemmatisation and pitfalls

Stop-word removal drops frequent function words to shrink the feature space and focus on content words, but default lists contain words that carry meaning: not, no, nor and negations flip sentiment ("not good" → "good"), and in tasks such as authorship or intent detection function words are informative. Prefer a custom list or none at all when using TF-IDF with max_df, which down-weights ubiquitous words automatically. Stemming (Porter, Snowball) is fast and crude: it can over-stem (universe and university sharing a stem) and under-stem and returns non-words (studies → studi). Lemmatisation uses a dictionary and part-of-speech tags, giving valid lemmas (studies → study, better → good as an adjective), but needs POS tagging and is slower.

Rules of thumb: for linear models on TF-IDF try light preprocessing (lowercase, tokenise, maybe lemmatise) and validate each step by cross-validation; for embeddings and transformers use the model's tokeniser and skip stemming, stop-word removal and heavy cleaning, because the model needs natural text. Avoid leakage (fit vocabularies and frequency thresholds on training data only), keep preprocessing in a versioned pipeline shared by training and serving, handle languages explicitly (stemmers and stop lists are language-specific) and inspect examples of what the cleaning does to real rows, particularly for emails, code and product codes.

Stemmer versus lemmatiser

studies, studying → Porter: studi, studi (not a real word). Lemmatiser with verb POS: study, study. The sentence "not good" with a default stop list becomes "good", whereas keeping not (or using bigrams) preserves the negation.

Key takeaway: Check what each step removes, keep negations, and for transformers let the model's tokeniser do the work.

How it works, step by step

Step 1 of 4
Data scientist

1. Normalise the raw text

Apply Unicode normalisation, handle case, whitespace and special tokens such as URLs and numbers.

The Cats are running quickly!! → lowercased
Key numbers at this step
Decide
emojis, URLs, numbers

When to use it & trade-offs

What it is

Text preprocessing turns raw strings into clean, consistent tokens that a model can count or embed. Common steps are normalisation (Unicode, lowercasing, whitespace, handling URLs, numbers and emojis), tokenisation (splitting into words, characters or subwords), stop-word removal (dropping very frequent function words), stemming (chopping suffixes with rules, so running → run and studies → studi) and lemmatisation (mapping a word to its dictionary form using part-of-speech knowledge, so studies → study and better → good as an adjective). Classical pipelines (bag of words, TF-IDF) benefit from this reduction in vocabulary; transformer models bring their own subword tokeniser and usually need far less cleaning.

Why it matters: Models see tokens, not words, so every inconsistency becomes a separate feature: Run, run and RUNNING are three vocabulary entries unless you normalise them. Good preprocessing shrinks the vocabulary, reduces sparsity and improves generalisation for classical models; bad preprocessing destroys signal (removing the stop word not turns not good into good and flips sentiment). It also has leakage and consistency risks: the same steps must be applied identically at training and serving time.

When to reach for it

  • Lowercasing and tokenising before TF-IDF
  • Lemmatising for cleaner topic modelling
  • Using the pretrained model's tokeniser for transformers

When to avoid or be careful

  • Default stop-word lists on sentiment tasks
  • Stemming text that will feed a transformer
  • Fitting the vocabulary on the full dataset before splitting

Reducing words to base forms

Stemming
Best for: Fast search and classic bag-of-words models

Strengths: Very quick; shrinks the vocabulary.

Watch out: Crude; output may not be real words.

Lemmatisation
Best for: Cleaner features when accuracy matters

Strengths: Valid dictionary forms.

Watch out: Slower; needs part-of-speech tags.

Subword tokenisation (BPE, WordPiece)
Best for: Neural and transformer models

Strengths: No unknown words; compact vocabulary.

Watch out: Pieces are less human-readable.

Interview signals & numbers to know

When this topic comes up

  • “What is the difference between stemming and lemmatisation?”
  • Why removing stop words can hurt
  • Subword tokenisation and out-of-vocabulary words
  • Training–serving consistency
  • How preprocessing affects vocabulary size

Benchmarks & rules of thumb

5 → 4 → 2 → 1 -
vocabulary types after lowercasing, stemming and verb lemmatising run forms
studies → studi -
typical Porter stem, not a valid word
not -
a stop word in default English lists, and a sentiment flipper

Common mistakes & follow-ups

Common interview mistakes

  • Removing not and no from sentiment data.
  • Lemmatising without part-of-speech information and getting no change.
  • Cleaning text differently in training and serving.

Likely interviewer follow-ups

  • How would you preprocess text for a transformer versus TF-IDF?
  • What can go wrong with stop-word removal?
  • What is BPE and why is it used?
Interview tip: Mention the negation trap and the training–serving pipeline; both show production awareness.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Text Preprocessing (Tokenization, Lemmatization) with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Sequence Models (RNNs, LSTMs, GRUs)
Next topic
Bag-of-Words & TF-IDF