Natural Language Processing (NLP)

NLP aims to make human language accessible to computers.
ML_AI/images/nlp-1.png

🛡 Pre-Processing

Turns unstructured chaos into something that can be used in NLP.

Pipeline Overview

A practical text pre-processing pipeline usually flows through cleaning, normalization, tokenization, and optional linguistic processing (stop words, lemmatization, POS) before feature extraction.

flowchart LR
    A[Raw Text] --> B["1\. Cleaning
(Whole String)"] B --> C["2\. Normalize
(Whole String)"] C --> D["3\. Tokenize
\(Split into tokens\)"] D --> E["4\. Optional: Remove Stop Words"] E --> F["5\. Optional: Lemmatize / Stem"] F --> G["6\. Parse / Tag (Task dependent)"]

1. Cleaning

Text cleaning removes unwanted elements ("noise") so the model focuses on useful signal.

For example:

Task-first rule

Do not blindly remove punctuation, emojis, or hashtags. In sentiment analysis, these often carry strong signal.

2. Normalization

Text normalization transforms text into a standard, consistent format so the computer recognizes variations of the same word as identical.

ML_AI/images/nlp-2.png

3. Tokenization

Tokenization is the process of ➀ breaking down a stream, ➁ phrase, ➂ sentence, ➃ paragraph, or ➄ an entire text document of text into smaller units, which are called tokens.
These tokens can be words, phrases, symbols, or other meaningful elements depending on the context and the task at hand in NLP. Words, numbers or punctuation marks can be tokens.

Tokenization is the foundation and first step when working on your NLP pipeline or tasks; Tokens can help us to understand the ➀ frequency of a particular word in the data and ➁ can be used directly as a vector representing the data. In this way, the string goes from being unstructured into a numerical data structure which helps NLP.

Modern NLP reminder

Transformer models (BERT, GPT-style models) usually use subword tokenization such as WordPiece, BPE, or SentencePiece, not only word-level tokenization.

Types of Tokenization:

1. Sentence Tokenization:

In this type of tokenization, text is split into sentences based on punctuation marks such as periods, exclamation marks, and question marks.

2. Word Tokenization:

This is the most common form, where text is split into words based on whitespace and punctuation. In this example, word tokenization splits the text into individual words, respecting punctuation marks and retaining the structure of the text. Each word becomes a token that can be further analyzed or processed for tasks such as sentiment analysis, named entity recognition, or text classification.

Handle contractions and possessives appropriately (e.g., "don't" -> ["do", "n't"], "cat's" -> ["cat", "'s"]).

3. Subword Tokenization:

This splits words into smaller units, which is often useful for languages with complex word formations or for generating more robust word representations. Subword tokenization breaks words into smaller units, useful for languages with complex morphology or for generating robust word representations. In this example, "Unsupervised" is split into "Un" and "supervised," providing more granularity in representation compared to traditional word tokenization.

mindmap
  root((Tokenization))
    WhiteSpaceTokenization["White Space Tokenization"]
    
    SubwordTokenization["Subword Tokenization"]
      SubwordTokenization --> BytePairEncoding["Byte Pair Encoding"]
      SubwordTokenization --> WordPieceEncoding["Word Piece Encoding"]
      SubwordTokenization --> SentencePieceEncoding["Sentence Piece Encoding"]
      SubwordTokenization --> UnigramModel["Unigram language model"]
    
    RuleBasedTokenization["Rule based Tokenization"]
    
    DictionaryBasedTokenization["Dictionary based Tokenization"]
    
    PennTreeTokenization["Penn Tree Tokenization"]
    
    MosesTokenizer["Moses Tokenizer"]
    
    SpacyTokenizer["Spacy Tokenizer"]
NLTK provides these types of tokenizers:
  1. word_tokenize(): This function splits text into individual words or tokens.
  2. sent_tokenize(): This function splits text into sentences based on punctuation marks such as periods, exclamation marks, and question marks. This function ensures that each sentence is treated as a separate unit of analysis.
  3. TweetTokenizer(): This function is designed specifically for processing social media texts, which often contain hashtags, mentions, and emoticons.
  4. RegexpTokenizer(): This tokenization is based on regular expressions, allowing users to define custom patterns for token boundaries.
  5. WhitespaceTokenizer(): This function is based on whitespace characters, useful for cases where text is already preprocessed or structured.

Refer to www.comet.com/site/blog/tokenization-techniques-in-nlp for more details on each

Code example: Open in ColabOpen in Colab

4. Stopword Removal

Remove common stopwords, sparse terms, and particular words to focus on meaningful words. NLTK provides a list of stopwords.

⚠️ Important: stopword removal is optional. It can help classical ML pipelines, but it can hurt tasks like sentiment and question answering where words like "not", "no", and "never" are critical.

Case Study

To find and remove these specific words, what method is easier for the computer

  • Option 1: When the text is still one long continuous string
  • Option 2: After the text has been broken down into individual tokens (words)?

It is actually much more effective to handle stop words ✅ after the text has been broken down into individual tokens (words).
Here is why: when the text is just one long string, the computer sees it as a single block of characters. It doesn't inherently know where one word ends and the next begins. By tokenizing first, we chop that string into an explicit list of distinct words. Once we have that list, the computer can easily loop through it and check: "Is this specific token on my stop word list?" If yes, it drops it.

Code Example: Open in ColabOpen in Colab

5. Adv. Normalization — Stemming vs Lemmatization

Stemming and lemmatization replace groups of words with their root forms
ML_AI/images/nlp-3.png

1. Stemming

Stemming is a text normalization technique used to reduce words to their base or root form.

Code Example: Open in ColabOpen in Colab

2. Lemmatization

Lemmatization is like stemming, but the outputs are always real Words. Lemmatization converts words to their base or dictionary form.

Example with POS awareness:

Code Example: Open in ColabOpen in Colab

Comparison between Stemming and Lemmatization

For instance, stemming the word 'amazed' can return 'amaz'. However, lemmatizing 'amazed' gives 'amaze'.

Aspect Stemming Lemmatization
Method Chops off suffixes Dictionary + POS lookup
Speed Fast Slower
Output May be non-words (joyfulli) Always valid words (joy)
Context aware No Yes

6. Text EDA Checkpoint (After Basic Pre-processing)

Exploratory Data Analysis (EDA) is typically done after basic cleaning/tokenization and before heavy feature engineering.

What to inspect:

Common visuals:

ML_AI/images/nlp-5.png500

🛡 Text Parsing

Text parsing means analyzing grammatical structure after tokenization, not just counting words.

1. Part of Speech (POS) Tagging

POS tagging assigns grammatical labels to tokens (noun, verb, adjective, etc.).
It helps with syntax, information extraction, and downstream tasks like NER and dependency parsing.

Common approaches:

Common POS Tags

DT -> Determiner
NN -> Noun
VBZ -> Verb, 3rd person singular present
VBG -> Verb, gerund / present participle
IN -> Preposition / subordinating conjunction

Code Example: Open in ColabOpen in Colab

2. Syntactic Parsing

Syntactic parsing is an essential Natural Language Processing (NLP) technique that analyzes the grammatical structure of a sentence. By mapping words to their structural or relational roles (e.g., nouns, verbs, subjects, objects), it breaks down text to help machines decode grammar and extract meaning.

As a result of recursively parsing the observed relationship between the words is represented in a top-down manner and depicted as a tree, which is known as the dependency tree.
These grammar relations can be used as features for many NLP problems such as entity-wise sentiment analysis, entity identification, and text classification.

ML_AI/images/text-parsing-1.png

Code Example: Open in ColabOpen in Colab

3. Chunking (Shallow Parsing)

Chunk extraction or partial parsing is a process of extracting short phrases from the sentence (tagged with Part-of-Speech) without building a full parse tree.
It is useful when you need light-weight structure with lower computational cost. It uses a special regexp syntax for rules that delimit the chunks. These rules must be converted to ‘regular’ regular expressions before a sentence can be chunked.

Code Example: Open in ColabOpen in Colab

4. Named Entity Recognition (NER)

Named Entity Recognition identifies and classifies entities in text into categories such as person, organization, location, date, and money.

Example Text: "Amazon, the multinational technology company, announced plans to acquire Whole Foods Market for $13.7 billion."

Entity Extraction Output:

Code Example: Open in ColabOpen in Colab

5. Relation Extraction

Relation extraction identifies semantic relationships between entities.

Example:

External References