TF-IDF Explained: Formula, Worked Example & Python Code
Key Insights
- TF-IDF measures a term’s importance in a document based on its frequency within the document and its rarity across the collection.
- The TF-IDF formula combines Term Frequency (TF) and Inverse Document Frequency (IDF) to assign weights to individual terms.
- A worked numerical example helps explain how terms appearing in fewer documents receive higher TF-IDF scores, even when their frequency within a document is identical.
- Scikit-learn’s TfidfVectorizer simplifies TF-IDF implementation in Python, but its default smoothing and L2 normalisation produce scores that differ from the basic textbook formula.
- TF-IDF supports information retrieval, text classification, and keyword extraction, but it does not inherently understand word meaning, synonyms, or context.
- BM25 and word embeddings offer different approaches to retrieval, while hybrid search can combine lexical and semantic signals for applications such as RAG.
TF-IDF (Term Frequency–Inverse Document Frequency) is a numerical weighting technique used in natural language processing (NLP) and information retrieval to measure how important a word is to a document relative to a collection of documents. It assigns greater weight to terms that appear frequently in a particular document but occur in fewer documents across the collection.
For example, words such as “the” or “is” may appear in almost every article, while terms such as “transformer” or “tokenisation” may help distinguish specific topics. TF-IDF helps a system differentiate between these terms based on their frequency and distribution. In this article, we’ll explore the TF-IDF formula, work through a numerical example, implement TF-IDF in Python using scikit-learn, and compare it with BM25 and word embeddings.
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.
What is TF-IDF? Full Form, TF and IDF Explained
TF-IDF combines two signals: how often a term appears in a document and how many documents contain that term. It gives greater weight to terms that are frequent in a particular document but relatively uncommon across the collection.
What is Term Frequency (TF)?
Term frequency measures how often a word occurs in a document. One simple, normalised term frequency formula is:
If a document contains 100 words and a term appears five times, its TF is (5/100=0.05). Normalisation makes the score reflect the term’s share of the document rather than just its raw count.
What is Inverse Document Frequency (IDF)?
Document frequency in NLP refers to the number of documents containing a term, regardless of how many times it appears in each one. Inverse document frequency (IDF) gives more weight to terms that occur in fewer documents.
The basic IDF formula is:
Here, (N) is the total number of documents and (df(t)) is the number containing term (t). The natural logarithm is used in the calculations below. If a term appears in every document, its IDF is zero under this formula.
What does a TF-IDF Score Tell You?
TF-IDF multiplies the two values:
TF-IDF(t,d) = TF(t,d) × IDF(t)
A high score indicates that a term is relatively prominent in a document and uncommon across the collection. A low score suggests that the term is either infrequent in that document or widespread across the corpus. TF-IDF measures statistical importance, not the meaning of a word.
What is the TF-IDF Formula?
The basic TF-IDF formula combines normalised term frequency with inverse document frequency:
To understand how to calculate TF-IDF, follow these steps:
- Count the term’s occurrences in the document.
- Divide that count by the document’s total number of terms to obtain TF.
- Count how many documents contain the term.
- Calculate IDF using the total document count and document frequency.
- Multiply TF by IDF.
The worked example uses the basic, unsmoothed formula and natural logarithms. Libraries such as scikit-learn use configurable implementations; by default, TfidfVectorizer smooths IDF weights and applies L2 normalisation. These differences affect the final scores.
TF-IDF Worked Example Using Three Documents
Consider this small corpus:
- Document 1: cat sat mat
- Document 2: cat ate fish
- Document 3: dog ate fish
We will calculate TF-IDF for terms in Document 1. Each document contains three terms, and the corpus contains three documents.
How do You Calculate TF-IDF for Document 1?
| Term | Count in Document 1 | TF | Documents containing term (DF) | IDF = ln(3/DF) | TF-IDF |
|---|---|---|---|---|---|
| cat | 1 | 1/3 = 0.333 | 2 | ln(3/2) = 0.405 | 0.135 |
| sat | 1 | 1/3 = 0.333 | 1 | ln(3) = 1.099 | 0.366 |
| mat | 1 | 1/3 = 0.333 | 1 | ln(3) = 1.099 | 0.366 |
For cat, TF is (1/3), while IDF is (\ln(3/2)). Multiplying them gives approximately (0.333 \times 0.405 = 0.135).
For sat, TF remains (1/3), but the term appears in only one document. Its IDF is (\ln(3)), producing a TF-IDF score of approximately (0.366). The same calculation applies to mat.
What does the Worked Example Demonstrate?
All three terms have identical TF values in Document 1, but sat and mat receive higher scores because they occur in fewer documents. This is the central idea behind TF-IDF: the IDF component distinguishes terms that are more specific to a document from those distributed across the corpus.
These values are illustrative, not universal. Different term-frequency definitions, logarithm conventions, smoothing and vector normalisation can produce different scores.
How to Calculate TF-IDF in Python Using scikit-learn
You can generate a TF-IDF matrix using TfidfVectorizer from scikit-learn. This approach is useful when working with larger collections of documents.
Python Code for TF-IDF
Install scikit-learn if it is not already available in your Python environment, then run:
from sklearn.feature_extraction.text import TfidfVectorizer
documents = [
"cat sat mat",
"cat ate fish",
"dog ate fish"
]
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(documents)
print(vectorizer.get_feature_names_out())
print(tfidf_matrix.toarray()) The output contains a vocabulary and a numerical matrix. fit_transform() learns the vocabulary and IDF weights from the documents, then converts the text into TF-IDF features.
- Vocabulary: get_feature_names_out() returns the terms represented by the matrix columns.
- Rows: Each row corresponds to one document.
- Columns: Each column corresponds to a vocabulary term.
- Scores: Each value represents a term’s TF-IDF weight in a particular document.
The default output will not match the manual calculation exactly. Scikit-learn uses smoothed IDF by default and normalises each document vector using L2 normalisation. It also lowercases text by default and applies its tokenisation rules, which can affect the vocabulary.
TF-IDF vs BM25 vs Word Embeddings
TF-IDF, BM25 and word embeddings represent or score text differently. They are related tools, but they are not interchangeable.
| Aspect | TF-IDF | BM25 | Word embeddings |
|---|---|---|---|
| Representation | Weighted term features | Lexical relevance score | Dense numerical vectors |
| Main signal | Term frequency and document rarity | Term frequency, IDF and document-length adjustment | Semantic or contextual similarity, depending on the model |
| Exact keyword matching | Useful | Strong for lexical retrieval | May not reliably preserve exact terms |
| Semantic similarity | Limited | Limited | Often stronger |
| Common uses | Text features and keyword retrieval | Search ranking | Semantic search and dense retrieval |
BM25 builds on related lexical weighting ideas, but adds term-frequency saturation and document-length normalisation. It is widely used in search systems; Elasticsearch, for example, documents BM25 as its default similarity method. See the official Elasticsearch reference.
Word embeddings represent text as dense vectors that can capture relationships beyond exact word overlap. For example, a semantic retrieval system may connect “car” with “automobile”, even if the query and document use different words. However, embeddings can still miss exact identifiers or technical terms. The right approach depends on the query, corpus and retrieval evaluation.
What are the Uses of TF-IDF in NLP and Search?
TF-IDF remains useful when a system needs interpretable text features or wants to identify terms that distinguish documents.
Information Retrieval and Keyword-Based Search
TF-IDF can help match documents against queries by weighting their terms. It provides a statistical relevance signal, but does not fully understand what a user means. Matching the right words is not always the same as answering the right question.
Text Classification and Keyword Extraction
TF-IDF features can be used with machine-learning models for tasks such as spam detection, topic classification and sentiment analysis. They can also help identify terms that distinguish one document or category from another. The results depend on the corpus, preprocessing and model.
TF-IDF in Modern RAG and Hybrid Retrieval
Retrieval-Augmented Generation (RAG) systems retrieve relevant information before passing it to a language model. Lexical retrieval can help find exact terms, product codes or technical identifiers, while dense retrieval can find semantically related content.
Hybrid search combines lexical and semantic retrieval to use both signals. In practical systems, BM25 is a common lexical retrieval method; TF-IDF is not the default ranking method in every RAG system. The best combination should be evaluated against the actual documents and queries.
What are the Limitations of TF-IDF?
TF-IDF captures word frequency and document-level rarity, but it does not inherently understand semantics, context or relationships between words.
Does TF-IDF Understand Meaning and Synonyms?
No. Standard TF-IDF treats words as separate features, so it does not inherently recognise that “car” and “automobile” can refer to the same concept. Preprocessing and n-gram features may improve some matching cases, but they do not provide general semantic understanding.
Does TF-IDF Consider Word Order and Context?
A standard unigram TF-IDF representation does not preserve word order or sentence meaning. Its usefulness can also be affected by rare terms, noisy text and document length, depending on the chosen weighting and normalisation. It is a useful baseline, but not a complete model of language.
Conclusion
TF-IDF is a foundational NLP technique that helps identify important terms in a document based on their frequency and distribution across a collection. By understanding the TF-IDF formula and working through a numerical example, you can interpret these scores and apply them using tools such as scikit-learn. While TF-IDF remains useful for text analysis, keyword extraction, and lexical retrieval, BM25 and word embeddings offer alternative approaches for information retrieval and semantic search.
Ready to build on these NLP foundations and explore how they power modern AI applications? Explore the Generative AI programme by IIT Delhi, delivered through Varsity by InterviewBit, to deepen your understanding of NLP and discover how these concepts connect with broader generative AI techniques.
Frequently Asked Questions
Is TF-IDF a machine learning algorithm?
No. TF-IDF is a feature-weighting technique, not a predictive model by itself. It is commonly used to prepare text features for machine-learning algorithms.
What Is the Difference Between TF-IDF and Bag of Words?
Bag of words represents documents using term counts or occurrences. TF-IDF reweights those terms according to how widely they appear across the document collection.
Can TF-IDF Scores Be Negative?
Standard TF-IDF scores are non-negative when calculated from non-negative term frequencies and conventional IDF formulas. Other transformations or downstream operations may produce negative values.
What Happens When a Word Appears in Every Document?
Its IDF is zero under the basic unsmoothed formula because (\ln(N/N)=\ln(1)=0). Its TF-IDF score is therefore also zero.
Does TF-IDF Require Stop-Word Removal?
No. Stop-word removal is optional and depends on the task. Common terms may already receive low weights, but preprocessing choices should be evaluated for the intended application.
Does TF-IDF Treat Uppercase and Lowercase Words Differently?
By default, scikit-learn’s TfidfVectorizer converts text to lowercase before tokenisation. This behaviour can be changed through its configuration.
Can TF-IDF Be Used for Short Documents?
Yes, but short texts may contain fewer overlapping terms and less context, making their scores less informative for some tasks.
What Is the Difference Between TF-IDF and Cosine Similarity?
TF-IDF creates weighted document vectors, while cosine similarity measures the angle-based similarity between vectors. Cosine similarity can be used to compare TF-IDF representations.
Does TF-IDF Need Labelled Training Data?
No. TF-IDF can learn its vocabulary and weights from an unlabelled collection of documents. Labelled data may be needed later if those features are used to train a supervised model.
Should TF-IDF Be Used Alone for a RAG Application?
Not necessarily. TF-IDF can support lexical retrieval, but the best setup depends on the corpus and query types. Evaluate lexical, dense and hybrid retrieval rather than assuming one method is always sufficient.