shivanis14
commited on
Commit
•
b54b44d
1
Parent(s):
75a7d9b
Create calc_cosine_similarity.py
Browse files- calc_cosine_similarity.py +21 -0
calc_cosine_similarity.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sentence_transformers import SentenceTransformer, util
|
2 |
+
import torch
|
3 |
+
|
4 |
+
def find_cosine_similarity(text1, text2):
|
5 |
+
# Load the pre-trained model
|
6 |
+
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
7 |
+
|
8 |
+
# Define your texts
|
9 |
+
text1 = "This is a sample text."
|
10 |
+
text2 = "This text is an example."
|
11 |
+
|
12 |
+
# Encode the texts to get their embeddings
|
13 |
+
embedding1 = model.encode(text1, convert_to_tensor=True)
|
14 |
+
embedding2 = model.encode(text2, convert_to_tensor=True)
|
15 |
+
|
16 |
+
# Compute cosine similarity
|
17 |
+
cosine_sim = util.pytorch_cos_sim(embedding1, embedding2)
|
18 |
+
|
19 |
+
# Print the cosine similarity score
|
20 |
+
#print(f"Cosine Similarity: {cosine_sim.item()}")
|
21 |
+
return cosine_sim.item()
|