Skip to content

Instantly share code, notes, and snippets.

@microcoder-py
Created January 31, 2022 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save microcoder-py/5699d848afb84072d55b67be3f244ddf to your computer and use it in GitHub Desktop.
Save microcoder-py/5699d848afb84072d55b67be3f244ddf to your computer and use it in GitHub Desktop.
# Make sure you have torch and sentence_transformers libraries installed
# 1 - Import Libraries & Install Files
import torch
from sentence_transformers import SentenceTransformer
from sentence_transformers import util
#We will find similarity for these two sentences
sentence1 = "This is a sentence"
sentence2 = "This is also a sentence"
#Download model
model = SentenceTransformer('all-MiniLM-L6-v2')
#Find sentence embeddings for sentences using SBERT model
embedding_sen1 = model.encode(sentence1)
embedding_sen2 = model.encode(sentence2)
#Find cosine distance between the sentences
cos_sim = util.cos_sim(embedding_sen1, embedding_sen2)
print("Cosine-Similarity:", cos_sim.numpy()[0][0])
print("Percentage Similarity: ", cos_sim.numpy()[0][0]*100, "%")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment