Intermediate level · Module 2: Feature Extraction and TF-IDF · Lesson 3 of 3
Document Similarity with Cosine Similarity
Learners compare documents using cosine similarity on TF-IDF vectors to find duplicates and related documents, a building block for search and recommendation.
In this lesson you will
- Compute cosine similarity between documents
- Use similarity to find duplicates and related documents
Key concepts
vector space modelcosine similaritycosine_similaritynear-duplicatessimilarity threshold
The lesson
Each TF-IDF vector is a point in a space with one dimension per term. Cosine similarity measures the angle between two vectors: 1 means the same direction (very similar wording), 0 means no shared terms.
sklearn.metrics.pairwise.cosine_similarity(X) returns a matrix of similarities between all documents. Pairs above a threshold, such as 0.8, are likely near-duplicates. This is useful for cleaning a corpus where the same notice was published several times.
TF-IDF similarity only sees shared words. 'Fees' and 'payment' are different terms, so related documents with different wording look unrelated. Word embeddings, in the next module, address this.
Step by step
- Compute the similarity matrix for the project corpus.
- List the ten most similar pairs and inspect them.
- Choose a duplicate threshold and remove duplicates.
- Find two related documents that TF-IDF misses and explain why.
Practice activity
Deduplicate the project corpus with cosine similarity and document the threshold chosen.
Expected result: A deduplicated corpus, a justified threshold and an example of TF-IDF's vocabulary limitation.
Check your understanding
-
What does a cosine similarity of 0 mean for TF-IDF vectors?
Show answer
The documents share no weighted terms.
-
Why can TF-IDF miss related documents?
Show answer
It only matches identical terms, not words with similar meanings.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.