sonoisa commited on
Commit
aefe8ea
·
1 Parent(s): 9b8c7f6

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +70 -0
README.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: ja
3
+ license: cc-by-sa-4.0
4
+ tags:
5
+ - sentence-transformers
6
+ - sentence-bert
7
+ - sentence-luke
8
+ - feature-extraction
9
+ - sentence-similarity
10
+ ---
11
+
12
+ This is a Japanese sentence-LUKE model.
13
+
14
+ 日本語用Sentence-LUKEモデルです。
15
+
16
+ [日本語Sentence-BERTモデル](https://huggingface.co/sonoisa/sentence-bert-base-ja-mean-tokens-v2)と同一のデータセットと設定で学習しました。
17
+ 手元の非公開データセットでは、[日本語Sentence-BERTモデル](https://huggingface.co/sonoisa/sentence-bert-base-ja-mean-tokens-v2)と比べて定量的な精度が同等〜0.5pt程度高く、定性的な精度は本モデルの方が高い結果でした。
18
+
19
+ 事前学習済みモデルとして[studio-ousia/luke-japanese-base-lite](https://huggingface.co/studio-ousia/luke-japanese-base-lite)を利用させていただきました。
20
+
21
+
22
+ # 使い方
23
+
24
+ ```python
25
+ from transformers import MLukeTokenizer, LukeModel
26
+ import torch
27
+
28
+
29
+ class SentenceLukeJapanese:
30
+ def __init__(self, model_name_or_path, device=None):
31
+ self.tokenizer = MLukeTokenizer.from_pretrained(model_name_or_path)
32
+ self.model = LukeModel.from_pretrained(model_name_or_path)
33
+ self.model.eval()
34
+
35
+ if device is None:
36
+ device = "cuda" if torch.cuda.is_available() else "cpu"
37
+ self.device = torch.device(device)
38
+ self.model.to(device)
39
+
40
+ def _mean_pooling(self, model_output, attention_mask):
41
+ token_embeddings = model_output[0] #First element of model_output contains all token embeddings
42
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
43
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
44
+
45
+ @torch.no_grad()
46
+ def encode(self, sentences, batch_size=8):
47
+ all_embeddings = []
48
+ iterator = range(0, len(sentences), batch_size)
49
+ for batch_idx in iterator:
50
+ batch = sentences[batch_idx:batch_idx + batch_size]
51
+
52
+ encoded_input = self.tokenizer.batch_encode_plus(batch, padding="longest",
53
+ truncation=True, return_tensors="pt").to(self.device)
54
+ model_output = self.model(**encoded_input)
55
+ sentence_embeddings = self._mean_pooling(model_output, encoded_input["attention_mask"]).to('cpu')
56
+
57
+ all_embeddings.extend(sentence_embeddings)
58
+
59
+ return torch.stack(all_embeddings)
60
+
61
+
62
+ MODEL_NAME = "sonoisa/sentence-luke-japanese-base-lite"
63
+ model = SentenceLukeJapanese(MODEL_NAME)
64
+
65
+ sentences = ["暴走したAI", "暴走した人工知能"]
66
+ sentence_embeddings = model.encode(sentences, batch_size=8)
67
+
68
+ print("Sentence embeddings:", sentence_embeddings)
69
+ ```
70
+