【问题标题】:Document similarity with Word Mover Distance and Bert-EmbeddingWord Mover Distance 和 Bert-Embedding 的文档相似度
【发布时间】:2019-08-02 04:00:51
【问题描述】:

我正在尝试使用基于Google's BERT 的词嵌入来计算两个任意文档的文档相似度(最近邻)。 为了从 Bert 获得词嵌入,我使用bert-as-a-service。 文档相似度应基于 Word-Mover-Distance 与 python wmd-relax 包。

我之前的尝试是针对来自wmd-relax github repo 的本教程:https://github.com/src-d/wmd-relax/blob/master/spacy_example.py

import numpy as np
import spacy
import requests
from wmd import WMD
from collections import Counter
from bert_serving.client import BertClient

# Wikipedia titles
titles = ["Germany", "Spain", "Google", "Apple"]

# Standard model from spacy
nlp = spacy.load("en_vectors_web_lg")

# Fetch wiki articles and prepare as specy document
documents_spacy = {}
print('Create spacy document')
for title in titles:
    print("... fetching", title)
    pages = requests.get(
        "https://en.wikipedia.org/w/api.php?action=query&format=json&titles=%s"
        "&prop=extracts&explaintext" % title).json()["query"]["pages"]
    text = nlp(next(iter(pages.values()))["extract"])
    tokens = [t for t in text if t.is_alpha and not t.is_stop]
    words = Counter(t.text for t in tokens)
    orths = {t.text: t.orth for t in tokens}
    sorted_words = sorted(words)
    documents_spacy[title] = (title, [orths[t] for t in sorted_words],
                              np.array([words[t] for t in sorted_words],
                                       dtype=np.float32))


# This is the original embedding class with the model from spacy
class SpacyEmbeddings(object):
    def __getitem__(self, item):
        return nlp.vocab[item].vector


# Bert Embeddings using bert-as-as-service
class BertEmbeddings:
    def __init__(self, ip='localhost', port=5555, port_out=5556):
        self.server = BertClient(ip=ip, port=port, port_out=port_out)

    def __getitem__(self, item):
        text = nlp.vocab[item].text
        emb = self.server.encode([text])
        return emb


# Get the nearest neighbor of one of the atricles
calc_bert = WMD(BertEmbeddings(), documents_spacy)
calc_bert.nearest_neighbors(titles[0])

很遗憾,由于距离计算中的尺寸不匹配,计算失败: ValueError: shapes (812,1,768) and (768,1,812) not aligned: 768 (dim 2) != 1 (dim 1)

【问题讨论】:

    标签: python nlp similarity word-embedding


    【解决方案1】:

    bert-as-service 输出的形状为 (batch_size, sequence_len, embedding_dimension。在您的情况下,sequence_len 为 1,因为您正在合并结果。

    现在,您可以使用numpy.ndarraytranspose 方法转置另一个以与之匹配。

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 2020-04-22
      • 2020-07-09
      • 1970-01-01
      • 2019-10-31
      • 2014-02-25
      • 1970-01-01
      • 2020-07-30
      • 2015-07-02
      相关资源
      最近更新 更多