language: ja
license: apache-2.0
tags:
- sentence-transformers
- sentence-bert
- sentence-luke
- feature-extraction
- sentence-similarity
这是一个日语句子-LUKE模型。
基于与日文Sentence-BERT模型相同的数据集和配置训练而成。
在内部非公开数据集测试中,其定量精度与日语Sentence-BERT模型持平或高出约0.5个百分点,定性评估显示本模型表现更优。
模型使用了studio-ousia/luke-japanese-base-lite作为预训练基础。
运行推理需安装SentencePiece(pip install sentencepiece)。
使用方法
from transformers import MLukeTokenizer, LukeModel
import torch
class SentenceLukeJapanese:
def __init__(self, model_name_or_path, device=None):
self.tokenizer = MLukeTokenizer.from_pretrained(model_name_or_path)
self.model = LukeModel.from_pretrained(model_name_or_path)
self.model.eval()
if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
self.device = torch.device(device)
self.model.to(device)
def _mean_pooling(self, model_output, attention_mask):
token_embeddings = model_output[0]
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
@torch.no_grad()
def encode(self, sentences, batch_size=8):
all_embeddings = []
iterator = range(0, len(sentences), batch_size)
for batch_idx in iterator:
batch = sentences[batch_idx:batch_idx + batch_size]
encoded_input = self.tokenizer.batch_encode_plus(batch, padding="longest",
truncation=True, return_tensors="pt").to(self.device)
model_output = self.model(**encoded_input)
sentence_embeddings = self._mean_pooling(model_output, encoded_input["attention_mask"]).to('cpu')
all_embeddings.extend(sentence_embeddings)
return torch.stack(all_embeddings)
MODEL_NAME = "sonoisa/sentence-luke-japanese-base-lite"
model = SentenceLukeJapanese(MODEL_NAME)
sentences = ["失控的AI", "失控的人工智能"]
sentence_embeddings = model.encode(sentences, batch_size=8)
print("句子嵌入向量:", sentence_embeddings)