我用Pickle方法(通过Bert-as-Service和Google的预训练模型)将Python词典存储为矢量文件,例如:
((key)Phrase:(value)Phrase_Vector_from_Bert =女人布:1.3237 -2.6354 1.7458 ....
但是我不知道像我使用Gensim Word2Vec一样,从Bert-as-Service模型的矢量文件中获取短语的相似性,因为后者配备了.similarity方法。
[请提供建议以使短语/关键词具有相似性或将其与我的python-Pickle-dictionary矢量文件聚类?
或者也许有更好的主意将关键字与Bert-as-Service聚类?
以下代码显示了如何获取短语/关键字的向量:
import Myutility
# the file Myutility includes the function save_model and load_model
import BertCommand
# the file Bertcommand includes the function to start Bert-as-service
client
WORD_PATH = 'E:/Works/testwords.txt'
WORD_FEATURE = 'E:/Works/word.google.vector'
word_vectors = {}
with open(WORD_PATH) as f:
lines = f.readlines()
for line in lines:
line = line.strip('\n')
if line:
word = line
print(line)
word_vectors[word]=None
for word in word_vectors:
try:
v = bc.encode([word])
word_vectors[word] = v
except:
pass
save_model(word_vectors,WORD_FEATURE)
如果我理解得很好,您还需要为每个短语提供一个载体。
然后,您可以简单地计算两个短语向量之间的余弦相似度。
有关详细信息和实现(手动实现和sklearn实现),我建议此链接:https://skipperkongen.dk/2018/09/19/cosine-similarity-in-python/