Python tf-idf-cosine to find document similarity
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Understanding document similarity is crucial in various applications, including search engines, recommendation systems, and content clustering. One of the popular techniques to determine the similarity between text documents is by leveraging TF-IDF and cosine similarity. In this article, we'll dive into these concepts and demonstrate how to implement them in Python.
What is TF-IDF?
TF-IDF stands for Term Frequency-Inverse Document Frequency. It is a numerical statistic that reflects the importance of a word in a document relative to a collection of documents, also known as a corpus.
Term Frequency (TF)
Term Frequency measures how frequently a word appears in a document. It's calculated using the formula:
Where:
- is the number of times term appears in document .
- is the total number of terms in document .
Inverse Document Frequency (IDF)
Inverse Document Frequency measures how important a term is universally across documents. Words like "is", "and", "the" may frequently appear, but it might not hold much importance. IDF is calculated as:
Where:
- is the total number of documents.
- is the number of documents containing the term .
TF-IDF
Combining both measures provides the TF-IDF score:
TF-IDF assigns more weight to rare words in a document.
Cosine Similarity
Cosine similarity measures the cosine of the angle between two vectors. When used in document similarity, these vectors are typically the TF-IDF vectors representing documents. The formula for cosine similarity is:
Where:
- is the dot product of vector and vector .
- and are the magnitudes of vectors and respectively.
A cosine similarity of 1 indicates identical documents, while 0 indicates no similarity.
Implementing TF-IDF and Cosine Similarity in Python
We'll use the sklearn library in Python to compute TF-IDF values and to calculate cosine similarity between documents.
Understanding the Output
Running the above code will give us a similarity matrix. Let's consider only the results for Document 1 against others:
| Document Pair | Cosine Similarity |
| Document 1 & Document 1 | 1.000 |
| Document 1 & Document 2 | 0.409 |
| Document 1 & Document 3 | 0.259 |
| Document 1 & Document 4 | 0.220 |
The diagonal values are always 1, because each document is identical to itself.
Summary
Using TF-IDF combined with cosine similarity is an effective method to measure document similarity, particularly in text mining and NLP applications. This technique helps address the challenges posed by common words, enabling more accurate analyses of document contents.
Key Points
| Concept | Explanation |
| Term Frequency (TF) | Measures the frequency of a term in a single document. |
| Inverse Document Frequency (IDF) | Evaluates the importance of a term across a corpus. |
| TF-IDF | Combines TF and IDF to assign weights to terms in documents. |
| Cosine Similarity | Measures the cosine of the angle between two document vectors. |
TF-IDF and cosine similarity, combined, provide a robust framework for comparing text documents, critical for modern search algorithms and recommendation engines.
Related reading
- Rasa NLU Confidence \`Score\` Computation
- Recommended way to embed PDF in HTML?
- Regular expression matching a multiline block of text
- Remove ✅, \U0001F525, ✈ , ♛ and other such emojis/images/signs from Java strings
- Python threading. How do I lock a thread?
- Python threads all executing on a single core
- Remove a prefix from a string
- Remove accents/diacritics in a string in JavaScript
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.