Bag-of-Words and N-Grams in NLP
Introduction to Bag-of-Words and N-Grams
Welcome to this lesson on Bag-of-Words (BoW) and N-Grams, a foundational technique in Natural Language Processing (NLP) for converting text data into numerical representations. Before we move on to more advanced text vectorization methods, understanding BoW is crucial because it provides the basic framework for handling textual data in machine learning models.
In this lesson, you will learn:
- What the Bag-of-Words model is and why it’s useful.
- How n-grams enhance text representation.
- How to implement BoW with scikit-learn’s
CountVectorizer. - Challenges and best practices for working with BoW.
What is Bag-of-Words?
The Bag-of-Words (BoW) model is a simple yet effective way to represent text data numerically. It converts text into a fixed-length numerical feature vector by counting word occurrences, disregarding grammar and word order.
How BoW Works
- Tokenization: Splitting text into individual words (tokens).
- Building a Vocabulary: Creating a list of all unique words in the dataset.
- Encoding: Counting how many times each word appears in a document.
Example
Consider these three sample documents:
- "Machine learning is amazing."
- "Bag-of-Words is a fundamental NLP technique."
- "NLP models often rely on n-grams."
Step 1: Creating the Vocabulary
The unique words across all sentences are:
tokenized = ["machine", "learning", "is", "amazing", "bag-of-words", "a", "fundamental", "nlp", "technique", "models", "often", "rely", "on", "n-grams"]
Step 2: Creating the Frequency Matrix
Each sentence is represented as a vector:
| Machine | Learning | Is | Amazing | Bag-of-Words | A | Fundamental | NLP | Technique | Models | Often | Rely | On | N-Grams | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Doc 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| Doc 2 | 0 | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
| Doc 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 1 |
Each row represents a document, and each column represents the occurrence of a word in that document.
