shahrukhx01 commited on
Commit
645947d
1 Parent(s): 908eb0a

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +70 -0
README.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - fuzzy-matching
4
+ - fuzzy-search
5
+ - entity-resolution
6
+ - record-linking
7
+ - structured-data-search
8
+ ---
9
+ A Siamese BERT architecture trained at character levels tokens for embedding based Fuzzy matching.
10
+ ```python
11
+ import torch
12
+ from transformers import AutoTokenizer, AutoModel
13
+ from torch import Tensor, device
14
+
15
+ def cos_sim(a: Tensor, b: Tensor):
16
+ """
17
+ borrowed from sentence transformers repo
18
+ Computes the cosine similarity cos_sim(a[i], b[j]) for all i and j.
19
+ :return: Matrix with res[i][j] = cos_sim(a[i], b[j])
20
+ """
21
+ if not isinstance(a, torch.Tensor):
22
+ a = torch.tensor(a)
23
+
24
+ if not isinstance(b, torch.Tensor):
25
+ b = torch.tensor(b)
26
+
27
+ if len(a.shape) == 1:
28
+ a = a.unsqueeze(0)
29
+
30
+ if len(b.shape) == 1:
31
+ b = b.unsqueeze(0)
32
+
33
+ a_norm = torch.nn.functional.normalize(a, p=2, dim=1)
34
+ b_norm = torch.nn.functional.normalize(b, p=2, dim=1)
35
+ return torch.mm(a_norm, b_norm.transpose(0, 1))
36
+
37
+
38
+ #Mean Pooling - Take attention mask into account for correct averaging
39
+ def mean_pooling(model_output, attention_mask):
40
+ token_embeddings = model_output[0] #First element of model_output contains all token embeddings
41
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
42
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
43
+
44
+
45
+ # Words we want fuzzy embeddings for
46
+ word1 = "fuzzformer"
47
+ word1 = " ".join([char for char in word1]) ## divide the word to char level to fuzzy match
48
+ word2 = "fizzformer"
49
+ word2 = " ".join([char for char in word2]) ## divide the word to char level to fuzzy match
50
+ words = [word1, word2]
51
+ # Load model from HuggingFace Hub
52
+ tokenizer = AutoTokenizer.from_pretrained('shahrukhx01/Fuzzformer')
53
+ model = AutoModel.from_pretrained('shahrukhx01/Fuzzformer')
54
+
55
+ # Tokenize sentences
56
+ encoded_input = tokenizer(words, padding=True, truncation=True, return_tensors='pt')
57
+
58
+ # Compute token embeddings
59
+ with torch.no_grad():
60
+ model_output = model(**encoded_input)
61
+
62
+ # Perform pooling. In this case, max pooling.
63
+ fuzzy_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
64
+
65
+ print("Fuzzy Match score:")
66
+ print(cos_sim(fuzzy_embeddings[0], fuzzy_embeddings[1]))
67
+ ```
68
+
69
+ ## ACKNOWLEDGEMENT
70
+ A big thank you to [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) as their implementation really expedited the implementation of Fuzzformer.