意大利语上下文/语义搜索中的BERT问题



我使用BERT模型在意大利语中进行上下文搜索,但它不理解句子的上下文含义并返回错误的结果。

在下面的示例代码中,当我比较"牛奶和巧克力口味"时用两种其他类型的牛奶和一种巧克力所以它与巧克力的相似性很高。它应该返回与其他牛奶高度相似的结果。

有没有人可以建议我对下面的代码进行任何改进,以便它可以返回语义结果?

代码:

!python -m spacy download it_core_news_lg
!pip install sentence-transformers

import scipy
import numpy as np
from sentence_transformers import models, SentenceTransformer
model = SentenceTransformer('distiluse-base-multilingual-cased') # workes with Arabic, Chinese, Dutch, English, French, German, Italian, Korean, Polish, Portuguese, Russian, Spanish, Turkish
corpus = [
"Alpro, Cioccolato bevanda a base di soia 1 ltr", #Alpro, Chocolate soy drink 1 ltr(soya milk)
"Milka  cioccolato al latte 100 g", #Milka milk chocolate 100 g
"Danone, HiPRO 25g Proteine gusto cioccolato 330 ml", #Danone, HiPRO 25g Protein chocolate flavor 330 ml(milk with chocolate flabor)
]
corpus_embeddings = model.encode(corpus)

queries = [
'latte al cioccolato', #milk with chocolate flavor,
]
query_embeddings = model.encode(queries)

# Calculate Cosine similarity of query against each sentence i
closest_n = 10
for query, query_embedding in zip(queries, query_embeddings):
distances = scipy.spatial.distance.cdist([query_embedding], corpus_embeddings, "cosine")[0]
results = zip(range(len(distances)), distances)
results = sorted(results, key=lambda x: x[1])
print("n======================n")
print("Query:", query)
print("nTop 10 most similar sentences in corpus:")
for idx, distance in results[0:closest_n]:
print(corpus[idx].strip(), "(Score: %.4f)" % (1-distance))

输出:

======================
Query: latte al cioccolato
Top 10 most similar sentences in corpus:
Milka  cioccolato al latte 100 g (Score: 0.7714)
Alpro, Cioccolato bevanda a base di soia 1 ltr (Score: 0.5586)
Danone, HiPRO 25g Proteine gusto cioccolato 330 ml (Score: 0.4569)

问题不在于你的代码,而在于模型性能不足。

你可以做一些事情。首先,你可以尝试通用句子编码器(USE)。从我的经验来看,他们的嵌入稍微好一点,至少在英语中是这样。

第二,您可以尝试不同的模型,例如sentence-transformers/xlm-r-distilroberta-base-paraphrase-v1。它是基于ROBERTa的,可能会提供更好的性能。

现在您可以将来自多个模型的嵌入组合在一起(只需连接表示)。在某些情况下,它是有用的,但代价是更繁重的计算。

最后您可以创建自己的模型。众所周知,单语言模型的性能明显优于多语言模型。您可以按照指南训练自己的意大利模型。

最新更新