Views
No views yet
1from scipy.spatial.distance import cosine
2from sentence_transformers import SentenceTransformer
3
4# Load the model
5model = SentenceTransformer("johngiorgi/declutr-small")
6
7# Prepare some text to embed
8texts = [
9 "A smiling costumed woman is holding an umbrella.",
10 "A happy woman in a fairy costume holds an umbrella.",
11]
12
13# Embed the text
14embeddings = model.encode(texts)
15
16# Compute a semantic similarity via the cosine distance
17semantic_sim = 1 - cosine(embeddings[0], embeddings[1])1import torch
2from scipy.spatial.distance import cosine
3from transformers import AutoModel, AutoTokenizer
4
5# Load the model
6tokenizer = AutoTokenizer.from_pretrained("johngiorgi/declutr-small")
7model = AutoModel.from_pretrained("johngiorgi/declutr-small")
8
9# Prepare some text to embed
10text = [
11 "A smiling costumed woman is holding an umbrella.",
12 "A happy woman in a fairy costume holds an umbrella.",
13]
14inputs = tokenizer(text, padding=True, truncation=True, return_tensors="pt")
15
16# Embed the text
17with torch.no_grad():
18 sequence_output = model(**inputs)[0]
19
20# Mean pool the token-level embeddings to get sentence-level embeddings
21embeddings = torch.sum(
22 sequence_output * inputs["attention_mask"].unsqueeze(-1), dim=1
23) / torch.clamp(torch.sum(inputs["attention_mask"], dim=1, keepdims=True), min=1e-9)
24
25# Compute a semantic similarity via the cosine distance
26semantic_sim = 1 - cosine(embeddings[0], embeddings[1])1@inproceedings{giorgi-etal-2021-declutr,
2 title = {{D}e{CLUTR}: Deep Contrastive Learning for Unsupervised Textual Representations},
3 author = {Giorgi, John and Nitski, Osvald and Wang, Bo and Bader, Gary},
4 year = 2021,
5 month = aug,
6 booktitle = {Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers)},
7 publisher = {Association for Computational Linguistics},
8 address = {Online},
9 pages = {879--895},
10 doi = {10.18653/v1/2021.acl-long.72},
11 url = {https://aclanthology.org/2021.acl-long.72}
12}
13