模型:

sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base

英文

sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base

这是将句子和段落映射到768维稠密向量空间的模型。可以用于聚类或语义搜索等任务。

用法(Sentence-Transformers)

安装了 sentence-transformers 后,使用这个模型非常简单:

pip install -U sentence-transformers

然后你可以这样使用模型:

from sentence_transformers import SentenceTransformer
sentences = ["This is an example sentence", "Each sentence is converted"]

model = SentenceTransformer('sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base')
embeddings = model.encode(sentences)
print(embeddings)

用法(HuggingFace Transformers)

如果没有 sentence-transformers ,可以这样使用模型:首先,将输入传递给Transformer模型,然后必须在上下文化的单词嵌入之上应用正确的池化操作。

from transformers import AutoTokenizer, AutoModel
import torch


def cls_pooling(model_output, attention_mask):
    return model_output[0][:,0]


# Sentences we want sentence embeddings for
sentences = ['This is an example sentence', 'Each sentence is converted']

# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base')
model = AutoModel.from_pretrained('sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base')

# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')

# Compute token embeddings
with torch.no_grad():
    model_output = model(**encoded_input)

# Perform pooling. In this case, max pooling.
sentence_embeddings = cls_pooling(model_output, encoded_input['attention_mask'])

print("Sentence embeddings:")
print(sentence_embeddings)

评估结果

有关该模型的自动评估,请参阅语句嵌入基准: https://seb.sbert.net

完整模型架构

SentenceTransformer(
  (0): Transformer({'max_seq_length': 509, 'do_lower_case': False}) with Transformer model: BertModel 
  (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': True, 'pooling_mode_mean_tokens': False, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False})
)

引用和作者

请参阅: DPR Model