Inferensys

Glossary

N-gram

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.
Data engineer managing feature store on laptop, feature definitions visible, casual data engineering session.
TEXT FEATURE ENGINEERING

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.

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.

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.

FOUNDATIONAL CONCEPT

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.

01

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.
02

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.
03

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.
04

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.
05

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.
06

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.
FEATURE COMPARISON

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.

FeatureN-gramsBag-of-WordsTF-IDFWord 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

N-GRAM CLARIFICATION

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.

Prasad Kumkar

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.