system HF staff commited on
Commit
a8db58d
1 Parent(s): 861f11c

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +29 -0
README.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ```python
2
+ import torch
3
+ from scipy.spatial.distance import cosine
4
+
5
+ from transformers import AutoModel, AutoTokenizer
6
+
7
+ # Load the model
8
+ tokenizer = AutoTokenizer.from_pretrained("johngiorgi/declutr-small")
9
+ model = AutoModel.from_pretrained("johngiorgi/declutr-small")
10
+
11
+ # Prepare some text to embed
12
+ text = [
13
+ "A smiling costumed woman is holding an umbrella.",
14
+ "A happy woman in a fairy costume holds an umbrella.",
15
+ ]
16
+ inputs = tokenizer(text, padding=True, truncation=True, return_tensors="pt")
17
+
18
+ # Embed the text
19
+ with torch.no_grad():
20
+ sequence_output, _ = model(**inputs, output_hidden_states=False)
21
+
22
+ # Mean pool the token-level embeddings to get sentence-level embeddings
23
+ embeddings = torch.sum(
24
+ sequence_output * inputs["attention_mask"].unsqueeze(-1), dim=1
25
+ ) / torch.clamp(torch.sum(inputs["attention_mask"], dim=1, keepdims=True), min=1e-9)
26
+
27
+ # Compute a semantic similarity via the cosine distance
28
+ semantic_sim = 1 - cosine(embeddings[0], embeddings[1])
29
+ ```