An N-gram is a contiguous sequence of N items from a text sample, where the items are typically tokens (words) or characters. By sliding a window of size N across a text, the sequence 'the quick brown fox' generates the bigrams (N=2) 'the quick', 'quick brown', and 'brown fox'. This technique preserves local word order, a critical advantage over the Bag-of-Words model, making it a foundational feature extraction method for statistical language modeling and text classification.
Glossary
N-gram

What is an N-gram?
An N-gram is a contiguous sequence of N items from a given text sample, where the items can be characters, bytes, or tokens, used as features for language modeling and text classification.
The choice of N balances specificity and coverage. Unigrams (N=1) capture individual term frequency but ignore context, while higher-order N-grams like trigrams (N=3) capture more phrase structure but suffer from data sparsity. In modern NLP, character N-grams are used to create robust, language-agnostic features for tasks like language identification, while token N-grams serve as sparse features in TF-IDF vectorizers for information retrieval and document similarity.
Key Characteristics of N-grams
N-grams are the fundamental building blocks of statistical language modeling, capturing local syntactic patterns by grouping contiguous sequences of tokens. Their simplicity and effectiveness make them indispensable for feature extraction in text classification, machine translation, and speech recognition.
Unigrams, Bigrams, and Trigrams
The most common N-gram orders capture different levels of linguistic context:
- Unigram (N=1): A single token, equivalent to a Bag-of-Words model that discards all word order. Example:
['the', 'cat', 'sat'] - Bigram (N=2): A sequence of two adjacent tokens, capturing immediate local dependencies. Example:
['the cat', 'cat sat'] - Trigram (N=3): A sequence of three tokens, often used in language modeling to predict the next word based on the previous two. Example:
['the cat sat', 'cat sat on']Higher-order N-grams (4-grams, 5-grams) capture more context but suffer from data sparsity.
Character vs. Token N-grams
N-grams can be extracted from two distinct levels of text representation, each serving different purposes:
- Token N-grams: Operate on word-level tokens after tokenization. Used for document classification, topic modeling, and semantic analysis. Example: The phrase 'machine learning' yields the bigram
machine_learning. - Character N-grams: Operate on individual characters, ignoring word boundaries. Essential for handling out-of-vocabulary (OOV) words, spelling variation, and morphologically rich languages. Example: The word 'cat' yields character trigrams
['cat', 'at_', 't__']with padding. Character N-grams are robust to typos and are widely used in spam detection and language identification.
The Markov Assumption
N-gram language models rely on the Markov assumption: the probability of a word depends only on the preceding N-1 words, not the entire history.
- For a bigram model,
P(w_i | w_1, ..., w_{i-1}) ≈ P(w_i | w_{i-1}) - For a trigram model,
P(w_i | w_1, ..., w_{i-1}) ≈ P(w_i | w_{i-2}, w_{i-1})This simplification makes computation tractable by limiting the context window. The probability of a full sentence is the product of its constituent N-gram probabilities, estimated via Maximum Likelihood Estimation from a training corpus.
Smoothing and Data Sparsity
As N increases, the number of possible N-grams grows exponentially, leading to zero probabilities for unseen sequences. Smoothing techniques address this:
- Laplace (Add-One) Smoothing: Adds a small count to every possible N-gram, preventing zero probabilities.
- Backoff (Katz): If an N-gram count is zero, the model recursively backs off to the (N-1)-gram probability.
- Interpolation: Combines weighted probabilities from different N-gram orders. Example:
P(w_i | w_{i-2}, w_{i-1}) = λ₃P(w_i | w_{i-2}, w_{i-1}) + λ₂P(w_i | w_{i-1}) + λ₁P(w_i) - Kneser-Ney Smoothing: The most effective method, using the diversity of contexts a word appears in rather than raw frequency.
N-grams as Feature Vectors
In classical machine learning pipelines, N-grams are converted into sparse numerical vectors for models like Naive Bayes or Support Vector Machines:
- Each unique N-gram in the corpus becomes a dimension in a high-dimensional feature space.
- TF-IDF weighting is applied to downweight common N-grams (like 'of the') and upweight discriminative ones.
- Character N-gram features are particularly effective for language identification and authorship attribution, capturing stylistic fingerprints.
- Despite the rise of neural embeddings, N-gram features remain a strong, interpretable baseline for text classification tasks.
Limitations and Modern Context
While foundational, N-gram models have inherent limitations that modern architectures address:
- Fixed Context Window: Cannot capture long-range dependencies beyond N tokens, unlike Transformer attention mechanisms.
- Vocabulary Explosion: The number of parameters grows exponentially with N, making storage and computation prohibitive for large N.
- No Semantic Generalization: Treats 'car' and 'automobile' as completely unrelated, unlike word embeddings.
- Modern Role: N-grams are now often used as a component in hybrid retrieval systems (e.g., BM25 for sparse lexical matching) or as features in production-grade spam filters and malware detectors where interpretability and speed are critical.
N-grams vs. Other Text Representation Techniques
A comparison of N-gram modeling against Bag-of-Words, TF-IDF, and embedding-based approaches for text representation and feature extraction.
| Feature | N-grams | Bag-of-Words | TF-IDF | Word Embeddings |
|---|---|---|---|---|
Captures word order | ||||
Captures semantics | ||||
Handles OOV terms | ||||
Dimensionality | High (V^N) | High (V) | High (V) | Low (300-1024) |
Sparsity | Extremely sparse | Sparse | Sparse | Dense |
Training required | ||||
Interpretability | High | High | High | Low |
Risk of overfitting | High | Moderate | Moderate | Low |
Frequently Asked Questions
Addressing common technical questions about the construction, application, and limitations of n-gram models in text normalization and feature extraction.
An n-gram is a contiguous sequence of N items from a given sample of text or speech, where the items can be characters, bytes, or tokens. The model works by sliding a window of size N across the text sequence, capturing local context. For example, the sentence 'I love NLP' yields the character trigrams 'I l', ' lo', 'lov', 'ove', 've ', 'e N', ' NL', and 'NLP'. In language modeling, n-grams are used to calculate the probability of a word given its preceding N-1 words, forming the basis of Markov chain text generators. The choice of N directly impacts the trade-off between specificity and data sparsity.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Master the core text processing techniques that form the building blocks of modern language models and search systems.
Bag-of-Words (BoW)
A text representation model that describes a document as an unordered collection of its constituent words, discarding grammar and word order but keeping track of term frequency. When combined with n-gram features, BoW can capture local word order by treating contiguous sequences as individual vocabulary entries.
- Unigram BoW: Each word is an independent feature
- Bigram BoW: Adjacent word pairs become features
- Trigram BoW: Three-word sequences are indexed
TF-IDF Weighting
Term Frequency-Inverse Document Frequency is a statistical weighting scheme that reflects how important a word is to a document in a corpus. It increases proportionally with the word's frequency in the document but is offset by its frequency across all documents, effectively dampening common terms.
- TF: Count of term in document / total terms in document
- IDF: log(Total documents / Documents containing term)
- N-gram TF-IDF vectors are standard features for text classification
Zipf's Law
An empirical law in corpus linguistics stating that the frequency of any word is inversely proportional to its rank in the frequency table. The most frequent word occurs approximately twice as often as the second most frequent word, three times as often as the third, and so on.
- Explains why stop word removal is essential
- N-gram distributions also follow Zipfian patterns
- The long tail of rare n-grams creates sparse feature matrices
Feature Extraction
The process of transforming raw, unstructured text into a numerical feature vector that can be understood by a machine learning algorithm. N-gram features are a classic extraction method where text is represented as a vector of contiguous token sequence counts.
- Unigram features: Individual word presence/absence
- Bigram features: Capture phrases like 'New York'
- Character n-grams: Robust to spelling variations and typos
Out-of-Vocabulary (OOV)
A term for any token encountered during inference that was not present in a model's fixed vocabulary. This is a critical challenge for word-level models. Character n-grams and subword tokenization strategies like BPE mitigate OOV issues by decomposing unknown words into known subword units.
- Word n-gram models suffer from OOV on rare terms
- Character n-grams never encounter true OOV tokens
- Subword tokenization balances vocabulary size and coverage

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us