Smoothing in NLP: Laplace, Add-k & Kneser-Ney Explained with Examples
Key Insights
- Smoothing in NLP prevents unseen word sequences from receiving zero probability in statistical language models.
- Laplace smoothing adds 1 to every count, while Add-k smoothing adds a configurable value
, allowing more flexibility in probability estimation.
- Both methods use the vocabulary size to adjust the denominator and distribute probability mass across possible words.
- Good-Turing, interpolation and backoff offer alternative approaches to estimating probabilities for unseen or rare n-grams.
- Kneser-Ney smoothing combines discounted counts with continuation probabilities, making it more informative than simply adding a constant to counts.
- Smoothing affects language-model evaluation by changing probability estimates and perplexity; the best method depends on the model and evaluation data.
- Laplace smoothing can also be applied to Naive Bayes classifiers to prevent zero probabilities when a feature is absent from a class.
Smoothing in NLP is a technique used in statistical n-gram language models to assign non-zero probabilities to word sequences that were not observed in training data. Laplace and Add-k smoothing adjust counts directly, while Kneser-Ney uses discounted counts and continuation probabilities to produce more informative estimates.
But why does this matter? When a language model encounters an unseen word sequence, its raw probability estimate may become zero, affecting predictions and evaluation. This guide explains the zero-probability problem, compares key smoothing techniques in NLP using a shared bigram example, and demonstrates a basic Python implementation.
Your roadmap to becoming a Generative AI Engineer
See what you already know, what to learn next and how long the switch to a GenAI engineering role takes. Tap any step for what to study and build.
What's inside8 stages · 30 steps to job-ready
- Python & engineering foundations
- ML & deep learning essentials
- How LLMs work
- Prompting & building LLM apps
- RAG & model customisation
- Agents & tool use
- Production, evaluation & safety
- Portfolio & job readiness
Python & engineering foundations
What to study
- Core Python: data types, functions, classes, modules
- Virtual environments and package management (pip, uv)
- Writing clean, testable scripts
What to build
A command-line script that reads a CSV, cleans it and writes a summary report.
What to study
- SQL joins, aggregations and window functions
- pandas for cleaning and reshaping data
- Working with text data at scale
What to build
A notebook that cleans a messy text dataset and prepares it for a model.
What to study
- Git branching and pull requests
- How REST APIs work: HTTP methods, status codes, auth headers
- Reading and writing JSON
What to build
Call a public API from Python, handle errors and save the results as JSON.
What to study
- Vectors, matrices and dot products
- Probability and distributions
- Gradients and optimisation, intuitively
What to build
Implement cosine similarity and gradient descent from scratch in NumPy.
ML & deep learning essentials
What to study
- Supervised vs unsupervised learning
- Train/test splits, overfitting and evaluation metrics
- scikit-learn workflows
What to build
Train and evaluate a text classifier with scikit-learn.
What to study
- Tokenisation and text preprocessing
- Word embeddings and semantic similarity
- Sequence models (RNN, LSTM) and why transformers replaced them
What to build
Build a semantic search over 500 short texts using sentence embeddings.
What to study
- Layers, activations, loss functions and backpropagation
- Training loops, batching and GPUs
- PyTorch tensors and autograd
What to build
Train a fully connected network on a small dataset and plot its learning curve.
How LLMs work
What to study
- Self-attention and multi-head attention
- Encoder, decoder and encoder-decoder models
- Positional encoding and why scale matters
What to build
Walk through a minimal transformer implementation and explain each block in a short write-up.
What to study
- The Transformers library, model hub and datasets
- Running open-weights models locally
- Fine-tuning a pre-trained model for a task
What to build
Fine-tune a small pre-trained transformer for sentiment or topic classification.
What to study
- Closed vs open-weights model families
- Tokens, context windows, temperature and sampling
- Comparing models on cost, latency and quality
What to build
A comparison table of three models answering the same 20 prompts, with cost and latency.
What to study
- Quantisation, pruning and distillation
- When a small model beats a large one
- On-device and low-cost inference
What to build
Quantise an open model and compare its speed and quality against the original.
Prompting & building LLM apps
What to study
- System prompts, few-shot examples and chain-of-thought
- Prompt test sets and versioning
- Reducing hallucinations through prompt design
What to build
A prompt library with a 30-example test set and before/after scores.
What to study
- Calling LLM APIs: streaming, rate limits, keys
- Serving with FastAPI and simple UIs with Streamlit
- Caching and cost control
What to build
A small chat app with streaming responses, deployed for others to try.
What to study
- JSON schema outputs and validation
- Function / tool calling
- Retries and graceful failure
What to build
An invoice or resume parser that returns validated JSON.
What to study
- Chains, prompts and output parsers
- Document loaders and retrievers
- When a framework helps and when it gets in the way
What to build
Rebuild your chat app with LangChain and compare the code with your plain-API version.
RAG & model customisation
What to study
- Embedding models and similarity search
- Vector databases (e.g. pgvector, Pinecone, Weaviate)
- Chunking strategies and metadata filters
What to build
Index a document set in a vector database and query it with filters.
What to study
- Supervised fine-tuning vs prompting vs RAG
- LoRA and other parameter-efficient methods
- Preparing instruction datasets
What to build
LoRA fine-tune an open-weights model on a narrow task and compare it with prompting alone.
What to study
- Vision transformers and CLIP-style models
- Image captioning and visual question answering
- Combining text and image retrieval
What to build
An image search app that finds photos from a text description.
What to study
- The RAG pipeline end to end
- Re-ranking, hybrid search and citations
- Measuring retrieval quality
What to build
A document Q&A assistant that cites its sources, with a retrieval-quality report.
What to study
- Instruction tuning and reward models
- RLHF and DPO, conceptually and with TRL
- Where alignment fits in real products
What to build
Train a small reward model and run a preference-tuning loop on a toy task.
Agents & tool use
What to study
- ReAct, planning and reflection patterns
- Single-agent vs multi-agent setups
- Memory: short-term, long-term and retrieval
What to build
A research agent that searches, reads and summarises sources on a topic.
What to study
- Model Context Protocol (MCP) servers and clients
- Connecting agents to databases, CRMs and internal APIs
- Permissions and audit trails for tool calls
What to build
An MCP server that exposes two tools from a real API, used by your agent.
What to study
- Graphs, state and checkpoints
- Human-in-the-loop approvals
- Error handling in multi-step workflows
What to build
Rebuild your research agent as a LangGraph workflow with an approval step.
Production, evaluation & safety
What to study
- Docker images for AI apps
- CI/CD basics
- Secrets and environment configuration
What to build
Containerise your RAG assistant and deploy it with a CI pipeline.
What to study
- Building evaluation datasets
- LLM-as-judge and its limits
- Regression testing prompts and models
What to build
An eval harness that scores your assistant on 50 cases and runs on every change.
What to study
- Tracing LLM calls
- Tracking token cost and latency
- Dashboards and alerting
What to build
Add tracing and a cost dashboard to your deployed app.
What to study
- Managed model platforms on AWS, GCP and Azure
- Serverless deployment and autoscaling
- Data privacy and region choices
What to build
Deploy your app on one cloud using a managed model endpoint.
What to study
- Hallucination, bias and privacy risks
- Prompt injection and defences
- PII handling and content filtering
What to build
Add input and output guardrails to your assistant and document the risks you tested.
Portfolio & job readiness
What to study
- GenAI system design questions
- Explaining trade-offs: RAG vs fine-tuning, cost vs quality
- Coding rounds in Python
What to build
Mock-interview notes for three GenAI system design questions.
What to study
- Choosing a domain problem (healthcare, fintech, edtech)
- Writing clear READMEs and architecture notes
- Recording a short demo
What to build
A client-ready AI agent for one domain, with a public demo and write-up.
Fine-tuned text classifier
Adapting a pre-trained transformer to a real task.
Fine-tune a small pre-trained transformer on a labelled dataset, evaluate it properly and compare it with a classic ML baseline.
Structured data extractor
Turning messy documents into clean JSON.
Use an LLM API with schema-validated outputs to extract fields from invoices or resumes, with a prompt test set to track accuracy.
Document Q&A assistant
Retrieval-augmented answers with citations.
Index a document collection in a vector database and build an assistant that answers questions with cited sources and a retrieval-quality report.
LoRA fine-tune of an open model
Customising a model when prompting isn't enough.
Fine-tune an open-weights model with LoRA on a narrow task and document when it beats prompting and RAG, and when it doesn't.
Reward model & preference tuning
Teaching a model what good looks like.
Train a small reward model on preference data and run a preference-tuning loop, with a write-up of what changed.
Multimodal image search
Finding images from plain-language descriptions.
Embed images and text in a shared space and build a search app that retrieves photos from a description.
Tool-using research agent
An agent that plans, acts and asks for approval.
Build a LangGraph agent that searches, reads and summarises sources, calls tools through an MCP server and pauses for human approval.
Deployed GenAI service
From notebook to a monitored production API.
Containerise an LLM app, deploy it on a cloud platform with CI/CD, and add tracing plus a cost and latency dashboard.
Eval harness with guardrails
Proving your AI app works, and stays safe.
Create a 50-case evaluation set, automate scoring on every change, and add input and output guardrails against prompt injection and PII leaks.
Domain AI agent capstone
A client-ready agent for a real industry problem.
Pick a domain such as healthcare, fintech or edtech and ship an agent that combines retrieval, tools, evals and guardrails, with a public demo and write-up.
GenAI glossary 17 terms
Tap a term to see what it means. You will hear these in every GenAI interview.
- LLM
- Large language model: a neural network trained on huge amounts of text to predict and generate language.
- Transformer
- The neural network architecture behind modern LLMs, built around the attention mechanism.
- Token
- A chunk of text (often part of a word) that a model reads and writes. Pricing and limits are counted in tokens.
- Context window
- The maximum number of tokens a model can consider at once, including your prompt and its answer.
- Prompt engineering
- Designing instructions and examples so a model reliably produces the output you need.
- Embeddings
- Numeric vectors that capture meaning, so similar texts end up close together.
- Vector database
- A database built to store embeddings and find the most similar ones quickly.
- RAG
- Retrieval-augmented generation: fetching relevant documents and giving them to the model so answers are grounded.
- Fine-tuning
- Further training a pre-trained model on your own data to specialise it.
- LoRA
- Low-rank adaptation: a parameter-efficient fine-tuning method that trains small add-on weights instead of the whole model.
- Agent
- An LLM system that plans steps, calls tools and acts towards a goal, often over several turns.
- Tool calling
- Letting a model call functions or APIs, such as search or a database query, with structured arguments.
- MCP
- Model Context Protocol: an open standard for connecting AI applications to tools and data sources.
- Evals
- Systematic tests that measure how well an AI system performs on representative cases.
- Guardrails
- Checks on inputs and outputs that keep an AI system safe, on-topic and compliant.
- Hallucination
- When a model states something false or unsupported with confidence.
- Prompt injection
- An attack where malicious text tricks a model into ignoring its instructions.
Close your gaps with a structured programme
The Certificate Programme in Generative AI from CEP, IIT Delhi covers transformers, fine-tuning, RAG, agents and responsible AI through live weekend classes and hands-on projects.
Why is Smoothing Needed in NLP?
Smoothing prevents unseen n-grams from receiving zero probability in a statistical language model.
The Zero-Probability Problem in N-Gram Models
An n-gram is a sequence of n consecutive tokens: a unigram is one token, a bigram is two, and a trigram is three. N-gram language models estimate the probability of a word based on its preceding context.
For a bigram, the maximum-likelihood estimate is:
P(wᵢ | wᵢ₋₁) = C(wᵢ₋₁, wᵢ) / C(wᵢ₋₁)
Here, C(wᵢ₋₁, wᵢ) is the bigram count, and C(wᵢ₋₁) is the context count.
If “like enjoy” never appears in the training corpus, its estimated probability is zero. Since sentence probabilities are calculated by multiplying conditional probabilities, one unseen bigram can make the entire sentence probability zero. This is the zero probability problem in NLP, often caused by data sparsity.
How Smoothing Helps
Smoothing adjusts probability estimates to account for unseen events while maintaining a normalised probability distribution. It is useful in count-based language models for applications such as speech recognition, text prediction and spelling correction.
What is Laplace Smoothing in NLP?
Laplace smoothing, also called Add-One smoothing, adds one to every possible n-gram count. This prevents zero counts from producing zero probabilities, although it can assign excessive probability to rare or unseen events.
Laplace Smoothing Formula
For bigrams, the Laplace smoothing formula is:
Pₗₐₚₗₐcₑ(wᵢ | wᵢ₋₁) = [C(wᵢ₋₁, wᵢ) + 1] / [C(wᵢ₋₁) + V]
Here, (V) is the vocabulary size: the number of possible next tokens. The denominator increases by (V) because one is added to each possible next-token count.
Worked Bigram Example: Calculating Laplace Probabilities
Consider this illustrative corpus:
- “I like NLP”
- “I like AI”
- “I enjoy AI”
Assume consistent sentence-boundary handling and a prediction vocabulary of (V=6). The context “like” occurs twice, followed by “NLP” once and “AI” once.
| Next word after “like” | Count | Laplace calculation | Probability |
|---|---|---|---|
| NLP | 1 | ((1+1)/(2+6)) | 0.25 |
| AI | 1 | ((1+1)/(2+6)) | 0.25 |
| enjoy | 0 | ((0+1)/(2+6)) | 0.125 |
Although “enjoy” never follows “like” in the corpus, it receives a non-zero probability. These are three of the six possible next tokens; the other three also receive probability mass. The example uses a fixed vocabulary to keep the arithmetic simple.
What is Add-k Smoothing, and How is it Different from Laplace Smoothing?
Add-k smoothing adds a constant (k) to every possible n-gram count rather than always adding one. Laplace smoothing is the special case where (k=1); smaller positive values make the adjustment less aggressive.
Add-k Smoothing Formula and Example
The Add-k smoothing formula is:
Pₖ(wᵢ | wᵢ₋₁) = [C(wᵢ₋₁, wᵢ) + k] / [C(wᵢ₋₁) + kV]
Using the same example, let (k=0.5) and (V=6). The denominator is (2+(0.5\times6)=5).
- For “NLP”: ((1+0.5)/5=0.30)
- For unseen “enjoy”: ((0+0.5)/5=0.10)
The unseen word receives a probability of 0.10 instead of 0.125 under Laplace smoothing. A smaller (k) reduces the count adjustment, but it does not automatically improve model performance.
Laplace vs Add-k Smoothing
| Aspect | Laplace | Add-k |
|---|---|---|
| Count adjustment | Adds 1 | Adds chosen (k) |
| Relationship | Special case of Add-k | General additive method |
| Main benefit | Simple baseline | Adjustable smoothing strength |
| Main limitation | Can over-smooth | Requires choosing (k) |
What are Good-Turing, Interpolation, and Backoff Smoothing?
These smoothing techniques in NLP estimate unseen events using count patterns or information from lower-order n-grams.
Good-Turing Smoothing
Good-Turing smoothing uses frequency-of-frequency counts—the number of n-grams observed once, twice and so on—to estimate how much probability should be reserved for unseen events. It adjusts estimates based on the distribution of observed counts rather than simply adding a fixed constant.
Interpolation and Backoff
Interpolation smoothing in NLP combines estimates from multiple n-gram orders, such as unigram, bigram and trigram probabilities, using weights.
Backoff smoothing uses a lower-order estimate when a higher-order n-gram is unseen or lacks sufficient evidence. For example, if a trigram is missing, the model may fall back to its bigram estimate. The key distinction in smoothing vs backoff is that interpolation combines estimates, while backoff conditionally falls back to a lower-order model.
What is Kneser-Ney Smoothing?
Kneser-Ney smoothing discounts observed n-gram counts and redistributes some probability mass using lower-order continuation probabilities. Instead of relying only on a word's overall frequency, it considers how many distinct contexts the word follows.
Kneser-Ney Smoothing Intuition
Discounting reduces observed counts slightly and reallocates the removed probability mass to other possibilities. Continuation probability reflects how many distinct preceding contexts a word appears after.
Imagine one word frequently follows a single common word, while another follows many different words. The second may be a more useful general continuation, even if its total count is lower. Kneser-Ney captures this distinction.
Modified Kneser-Ney uses different discounts for different count ranges. It is a strong classical method for n-gram language modelling, but no smoothing method is universally best across all datasets and evaluation settings.
How can you Implement Laplace Smoothing in Python?
A basic Laplace smoother adds one to the observed count and the vocabulary size to the context count. This illustrates smoothing in NLP Python without requiring a full language-model implementation.
Simple Python Example
def laplace_smoothing(count, context_count, vocab_size):
return (count + 1) / (context_count + vocab_size)
# "NLP" appears once after "like"
p_seen = laplace_smoothing(1, 2, 6)
# "enjoy" never appears after "like"
p_unseen = laplace_smoothing(0, 2, 6)
print(p_seen) # 0.25
print(p_unseen) # 0.125 The inputs are the bigram count, context count and vocabulary size. The vocabulary must be defined consistently. This function calculates one probability; a complete language model must also handle tokenisation, sentence boundaries and counts.
How is Laplace Smoothing Used in Naive Bayes?
In text classification, Laplace smoothing in Naive Bayes prevents a word absent from a class's training documents from making its likelihood zero.
The general likelihood formula is:
P(w | c) = [C(w, c) + α] / [N꜀ + αV]
Here, C(w, c) is the count of word w in context or class c, N꜀ is the total count of observations in context or class c, α is the smoothing parameter, and V is the vocabulary size. In scikit-learn's MultinomialNB, the α parameter provides additive smoothing: (α=1) corresponds to Laplace smoothing, while smaller positive values correspond to Lidstone smoothing.
How Does Smoothing Affect Perplexity?
Language model perplexity measures how well a model predicts a test sequence. Smoothing changes probability estimates and can therefore affect perplexity, but it does not guarantee improvement. A zero-probability test sequence can make the usual perplexity calculation infinite or undefined.
Compare smoothing methods on held-out data rather than choosing one based only on formula simplicity.
Conclusion
Smoothing helps statistical language models handle unseen word sequences. Laplace provides a simple baseline, Add-k makes the adjustment tunable, and Kneser-Ney uses discounted counts and continuation probabilities for more context-aware estimates. Good-Turing, interpolation and backoff offer other ways to address sparse counts. The most suitable method depends on the data and should be evaluated on held-out examples.
Want to build a stronger foundation in NLP and understand how statistical language models connect with modern Generative AI? Explore the Generative AI programme by IIT Delhi, delivered on Varsity by InterviewBit to deepen your understanding of the techniques behind today’s AI systems.
Frequently Asked Questions
Does smoothing create new word sequences in the training corpus?
No. Smoothing changes the probability estimates assigned to possible events, including sequences not observed in the training data.
Can smoothing assign probability to a word outside the vocabulary?
Not by itself. The model needs an explicit strategy, such as mapping unknown words to an <UNK> token.
Does every smoothing method preserve a valid probability distribution?
A correctly formulated and normalised method should assign probabilities that sum to one over the defined outcomes. Counts and vocabulary definitions must remain consistent.
What happens if the smoothing parameter is too large?
Excessive additive smoothing can flatten the probability distribution, making observed and unseen events less distinguishable.
Is Add-k smoothing the same as discounting?
No. Add-k increases counts by a constant, while discounting methods reduce observed counts and redistribute probability mass.
Can smoothing be applied to trigrams as well as bigrams?
Yes. The same general principles apply to higher-order n-grams, where sparsity often becomes more severe as context length increases.
How should I choose the value of k in Add-k smoothing?
Compare candidate values on held-out validation data. The best value depends on the corpus and task.
Why can a frequent word still have a low continuation probability?
Continuation probability depends on the number of distinct preceding contexts, not simply the word's total frequency.
Is Kneser-Ney smoothing used in modern large language models?
Kneser-Ney is a classical technique for count-based n-gram models. Modern neural language models generally use different training and probability-estimation approaches.
Should I always use smoothing when training a language model?
Smoothing is important for many sparse count-based models, but the method and its necessity depend on the model family, vocabulary handling and evaluation setup.