模型:

sentence-transformers/msmarco-MiniLM-L6-cos-v5

英文

msmarco-MiniLM-L6-cos-v5

这是一种模型:它将句子和段落映射到一个384维的稠密向量空间,并设计用于语义搜索。它是在来自 MS MARCO Passages dataset 的50万个(查询,答案)对上进行训练的。有关语义搜索的介绍,请参阅: SBERT.net - Semantic Search

用法(Sentence-Transformers)

当您安装了 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-L6-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)

用法(HuggingFace Transformers)

如果没有 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-L6-cos-v5")
model = AutoModel.from_pretrained("sentence-transformers/msmarco-MiniLM-L6-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 384
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",
}