模型:
sentence-transformers/facebook-dpr-ctx_encoder-multiset-base
这是一个将句子和段落映射到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-ctx_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-ctx_encoder-multiset-base') model = AutoModel.from_pretrained('sentence-transformers/facebook-dpr-ctx_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