5分鐘 NLP系列—SentenceTransformers 庫介紹

SentenceTransformers 是一個可以用於句子、文字和影象嵌入的Python庫。可以為 100 多種語言計算文字的嵌入並且可以輕鬆地將它們用於語義文字相似性、語義搜尋和同義詞挖掘等常見任務。

5分鐘 NLP系列—SentenceTransformers 庫介紹

該框架基於 PyTorch 和 Transformers,並提供了大量針對各種任務的預訓練模型。還可以很容易根據自己的模型進行微調。

閱讀論文 Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks,深入瞭解模型的訓練方式。在本文中,我們將看到該庫的一些可能用例的程式碼示例。模型訓練將在後面的文章中介紹。

安裝

在深入研究程式碼之前,使用pip安裝sentencetransformer庫。

pip install -U sentence-transformers

獲得嵌入向量

第一個例子是如何獲得句子嵌入。sentencetransformer使它變得非常簡單:只需要匯入庫、載入模型,並呼叫encode方法。

from sentence_transformers import SentenceTransformer

# Download model

model = SentenceTransformer(‘paraphrase-MiniLM-L6-v2’)

# The sentences we‘d like to encode

sentences = [’Python is an interpreted high-level general-purpose programming language。‘,

’Python is dynamically-typed and garbage-collected。‘,

’The quick brown fox jumps over the lazy dog。‘]

# Get embeddings of sentences

embeddings = model。encode(sentences)

# Print the embeddings

for sentence, embedding in zip(sentences, embeddings):

print(“Sentence:”, sentence)

print(“Embedding:”, embedding)

print(“”)

# Sentence: Python is an interpreted high-level general-purpose programming language。

# Embedding: [-1。17965914e-01 -4。57159936e-01 -5。87313235e-01 -2。72477478e-01 。。。

# 。。。

語義文字相似度

一旦我們有了句子的嵌入,我們就可以使用util模組中的cos_sim函式來計算它們的餘弦相似度。

from sentence_transformers import SentenceTransformer, util

# Download model

model = SentenceTransformer(’paraphrase-MiniLM-L6-v2‘)

# The sentences we’d like to compute similarity about

sentences = [‘Python is an interpreted high-level general-purpose programming language。’,

‘Python is dynamically-typed and garbage-collected。’,

‘The quick brown fox jumps over the lazy dog。’]

# Get embeddings of sentences

embeddings = model。encode(sentences)

# Compute similarities

sim = util。cos_sim(embeddings[0], embeddings[1])

print(“”。format(sim。tolist()[0][0])) # 0。6445

sim = util。cos_sim(embeddings[0], embeddings[2])

print(“”。format(sim。tolist()[0][0])) # 0。0365

語義搜尋

語義搜尋透過理解搜尋查詢的內容來提高搜尋的準確性,而不是僅僅依賴於詞彙匹配。這是利用嵌入之間的相似性完成的。

語義搜尋是將語料庫中的所有條目嵌入到向量空間中。在搜尋時,查詢也會被嵌入到相同的向量空間中,並從語料庫中找到最接近的嵌入。

5分鐘 NLP系列—SentenceTransformers 庫介紹

向量空間中語義搜尋的例子。

語義搜尋可以使用util模組的semantic_search函式來執行,該函式處理語料庫中文件的嵌入和查詢的嵌入。

from sentence_transformers import SentenceTransformer, util

# Download model

model = SentenceTransformer(‘paraphrase-MiniLM-L6-v2’)

# Corpus of documents and their embeddings

corpus = [‘Python is an interpreted high-level general-purpose programming language。’,

‘Python is dynamically-typed and garbage-collected。’,

‘The quick brown fox jumps over the lazy dog。’]

corpus_embeddings = model。encode(corpus)

# Queries and their embeddings

queries = [“What is Python?”, “What did the fox do?”]

queries_embeddings = model。encode(queries)

# Find the top-2 corpus documents matching each query

hits = util。semantic_search(queries_embeddings, corpus_embeddings, top_k=2)

# Print results of first query

print(f“Query: ”)

for hit in hits[0]:

print(corpus[hit[‘corpus_id’]], “(Score: {:。4f})”。format(hit[‘score’]))

# Query: What is Python?

# Python is an interpreted high-level general-purpose programming language。 (Score: 0。6759)

# Python is dynamically-typed and garbage-collected。 (Score: 0。6219)

# Print results of second query

print(f“Query: ”)

for hit in hits[1]:

print(corpus[hit[‘corpus_id’]], “(Score: {:。4f})”。format(hit[‘score’]))

# Query: What did the fox do?

# The quick brown fox jumps over the lazy dog。 (Score: 0。3816)

# Python is dynamically-typed and garbage-collected。 (Score: 0。0713)

為了充分利用語義搜尋,必須區分對稱和非對稱語義搜尋,因為它會嚴重影響要使用的模型的選擇。

Paraphrase Mining

Paraphrase Mining是在大量句子中尋找釋義的任務,即具有非常相似含義的文字。

這可以使用 util 模組的 paraphrase_mining 函式來實現。

from sentence_transformers import SentenceTransformer, util

# Download model

model = SentenceTransformer(‘all-MiniLM-L6-v2’)

# List of sentences

sentences = [‘The cat sits outside’,

‘A man is playing guitar’,

‘I love pasta’,

‘The new movie is awesome’,

‘The cat plays in the garden’,

‘A woman watches TV’,

‘The new movie is so great’,

‘Do you like pizza?’]

# Look for paraphrases

paraphrases = util。paraphrase_mining(model, sentences)

# Print paraphrases

print(“Top 5 paraphrases”)

for paraphrase in paraphrases[0:5]:

score, i, j = paraphrase

print(“Score {:。4f} —— {} —— {}”。format(score, sentences[i], sentences[j]))

# Top 5 paraphrases

# Score 0。8939 —— The new movie is awesome —— The new movie is so great

# Score 0。6788 —— The cat sits outside —— The cat plays in the garden

# Score 0。5096 —— I love pasta —— Do you like pizza?

# Score 0。2560 —— I love pasta —— The new movie is so great

# Score 0。2440 —— I love pasta —— The new movie is awesome

圖片搜尋

SentenceTransformers 提供允許將影象和文字嵌入到同一向量空間,透過這中模型可以找到相似的影象以及實現影象搜尋,即使用文字搜尋影象,反之亦然。

5分鐘 NLP系列—SentenceTransformers 庫介紹

同一向量空間中的文字和影象示例。

要執行影象搜尋,需要載入像 CLIP 這樣的模型,並使用其encode 方法對影象和文字進行編碼。

from sentence_transformers import SentenceTransformer, util

from PIL import Image

# Load CLIP model

model = SentenceTransformer(‘clip-ViT-B-32’)

# Encode an image

img_emb = model。encode(Image。open(‘two_dogs_in_snow。jpg’))

# Encode text descriptions

text_emb = model。encode([‘Two dogs in the snow’, ‘A cat on a table’, ‘A picture of London at night’])

# Compute cosine similarities

cos_scores = util。cos_sim(img_emb, text_emb)

print(cos_scores)

多模態模型獲得的嵌入也允許執行影象相似性等任務。

其他任務

1、對於問答檢索等複雜的搜尋任務,可以透過使用 Retrieve & Re-Rank 顯著改進語義搜尋。

Retrieve & Re-Rank 架構

2、SentenceTransformers 可以以不同的方式用於對小或大的句子集進行聚類。

5分鐘 NLP系列—SentenceTransformers 庫介紹

對文件進行主題建模示例

最後 SentenceTransformers的官網:https://www。sbert。net/

作者:Fabio Chiusano

MORE

kaggle比賽交流和組隊

加我的微信,邀你進群

5分鐘 NLP系列—SentenceTransformers 庫介紹

喜歡就關注一下吧:

點個

在看

你最好看!