模型:
sentence-transformers/facebook-dpr-question_encoder-multiset-base
此模型是 DPR Model 到 sentence-transformers 的一个转换版本:它将句子和段落映射到一个768维的稠密向量空间,可用于聚类或语义搜索等任务。
安装 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-question_encoder-multiset-base') embeddings = model.encode(sentences) print(embeddings)
如果没有 sentence-transformers ,您可以像这样使用该模型:首先,通过变换器模型传递您的输入,然后必须在上下文化的词嵌入之上应用合适的汇聚操作。
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-question_encoder-multiset-base') model = AutoModel.from_pretrained('sentence-transformers/facebook-dpr-question_encoder-multiset-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 .