Python
tf-idf
cosine similarity
document similarity
text analysis

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.

Practice ML system design

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:

TF(t,d)=ft,dNd\text{TF}(t, d) = \frac{f_{t,d}}{N_d} Where:

  • ft,df_{t,d} is the number of times term tt appears in document dd.
  • NdN_d is the total number of terms in document dd.

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:

IDF(t,D)=log(D1+dD:td)\text{IDF}(t, D) = \log\left(\frac{|D|}{1 + |{d \in D : t \in d}|}\right) Where:

  • D|D| is the total number of documents.
  • dD:td|{d \in D : t \in d}| is the number of documents containing the term tt.

TF-IDF

Combining both measures provides the TF-IDF score:

TF-IDF(t,d,D)=TF(t,d)×IDF(t,D)\text{TF-IDF}(t, d, D) = \text{TF}(t, d) \times \text{IDF}(t, D) 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:

Cosine Similarity(A,B)=ABA×B\text{Cosine Similarity}(A, B) = \frac{A \cdot B}{||A|| \times ||B||} Where:

  • ABA \cdot B is the dot product of vector AA and vector BB.
  • A||A|| and B||B|| are the magnitudes of vectors AA and BB 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.

python
1from sklearn.feature_extraction.text import TfidfVectorizer
2from sklearn.metrics.pairwise import cosine_similarity
3
4# Sample documents
5documents = [
6    "The sky is blue and the sun is shining.",
7    "The weather is cold but the sky is clear.",
8    "Rain is falling and the sky is gray.",
9    "Cold days bring lots of rain."
10]
11
12# Compute TF-IDF
13tfidf_vectorizer = TfidfVectorizer()
14tfidf_matrix = tfidf_vectorizer.fit_transform(documents)
15
16# Compute Cosine Similarity
17cosine_sim = cosine_similarity(tfidf_matrix, tfidf_matrix)
18
19# Displaying the cosine similarity
20print(cosine_sim)

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 PairCosine Similarity
Document 1 & Document 11.000
Document 1 & Document 20.409
Document 1 & Document 30.259
Document 1 & Document 40.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

ConceptExplanation
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-IDFCombines TF and IDF to assign weights to terms in documents.
Cosine SimilarityMeasures 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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Practice ML system design

All Rights Reserved.