模型:
sentence-transformers/msmarco-MiniLM-L12-cos-v5
任务:
句子相似度预印本库:
arxiv:1908.10084这是一个模型:它将句子和段落映射到一个768维的稠密向量空间,并且专门设计用于语义搜索。它是在来自 MS MARCO Passages dataset 的50万个(查询,答案)对上进行训练的。如果想了解语义搜索的介绍,请查看: SBERT.net - Semantic Search
安装了 sentence-transformers 后,使用这个模型变得很容易:
pip install -U sentence-transformers
然后可以像这样使用该模型:
from sentence_transformers import SentenceTransformer, util query = "How many people live in London?" docs = ["Around 9 Million people live in London", "London is known for its financial district"] #Load the model model = SentenceTransformer('sentence-transformers/msmarco-MiniLM-L12-cos-v5') #Encode query and documents query_emb = model.encode(query) doc_emb = model.encode(docs) #Compute dot score between query and all document embeddings scores = util.dot_score(query_emb, doc_emb)[0].cpu().tolist() #Combine docs & scores doc_score_pairs = list(zip(docs, scores)) #Sort by decreasing score doc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True) #Output passages & scores for doc, score in doc_score_pairs: print(score, doc)
没有安装 sentence-transformers ,您可以像这样使用该模型:首先,将输入传递给变换器模型,然后必须在上下文化的单词嵌入之上应用正确的汇聚操作。
from transformers import AutoTokenizer, AutoModel import torch import torch.nn.functional as F #Mean Pooling - Take average of all tokens def mean_pooling(model_output, attention_mask): token_embeddings = model_output.last_hidden_state #First element of model_output contains all token embeddings 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) #Encode text def encode(texts): # Tokenize sentences encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors='pt') # Compute token embeddings with torch.no_grad(): model_output = model(**encoded_input, return_dict=True) # Perform pooling embeddings = mean_pooling(model_output, encoded_input['attention_mask']) # Normalize embeddings embeddings = F.normalize(embeddings, p=2, dim=1) return embeddings # Sentences we want sentence embeddings for query = "How many people live in London?" docs = ["Around 9 Million people live in London", "London is known for its financial district"] # Load model from HuggingFace Hub tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/msmarco-MiniLM-L12-cos-v5") model = AutoModel.from_pretrained("sentence-transformers/msmarco-MiniLM-L12-cos-v5") #Encode query and docs query_emb = encode(query) doc_emb = encode(docs) #Compute dot score between query and all document embeddings scores = torch.mm(query_emb, doc_emb.transpose(0, 1))[0].cpu().tolist() #Combine docs & scores doc_score_pairs = list(zip(docs, scores)) #Sort by decreasing score doc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True) #Output passages & scores for doc, score in doc_score_pairs: print(score, doc)
以下是关于如何使用此模型的一些技术细节:
Setting | Value |
---|---|
Dimensions | 768 |
Produces normalized embeddings | Yes |
Pooling-Method | Mean pooling |
Suitable score functions | dot-product ( util.dot_score ), cosine-similarity ( util.cos_sim ), or euclidean distance |
注意:使用sentence-transformers加载时,该模型会产生长度为1的归一化嵌入。在这种情况下,点积和余弦相似度是等价的。由于点积更快,所以它更受推荐。欧氏距离与点积成正比,也可以使用。
该模型由 sentence-transformers 进行训练。
如果您发现该模型有帮助,请随意引用我们的出版物 Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks :
@inproceedings{reimers-2019-sentence-bert, title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks", author = "Reimers, Nils and Gurevych, Iryna", booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing", month = "11", year = "2019", publisher = "Association for Computational Linguistics", url = "http://arxiv.org/abs/1908.10084", }