我可以优化这个 Word Mover 的距离查找功能吗?

Can I optimize this Word Mover's Distance look-up function?

我正在尝试使用 Python 中的 Gensim 的 Word2Vec 工具测量大量文本之间的 Word Mover 距离。我将每个文本与所有其他文本进行比较,因此我首先使用 itertools 创建成对组合,如 [1,2,3] -> [(1,2), (1,3), (2,3)]。为了记忆起见,我不会通过在大数据框中重复所有文本来进行组合,而是使用文本索引制作参考数据框 combinations,如下所示:

    0   1
0   0   1
1   0   2
2   0   3

然后在比较函数中,我使用这些索引在原始数据框中查找文本。该解决方案工作正常,但我想知道我是否能够使用大数据集。例如,我有一个 300.000 行的文本数据集,这在我的笔记本电脑上提供了大约 100 年的计算价值:

C2​(300000) = 300000​! / (2!(300000−2))!
           = 300000⋅299999​ / 2 * 1
           = 44999850000 combinations

有什么方法可以更好地优化它吗?

我现在的代码:

import multiprocessing
import itertools
import numpy as np
import pandas as pd
import dask.dataframe as dd
from dask.diagnostics import ProgressBar
from gensim.models.word2vec import Word2Vec
from gensim.corpora.wikicorpus import WikiCorpus

def get_distance(row):
    try: 
        sent1 = df.loc[row[0], 'text'].split()
        sent2 = df.loc[row[1], 'text'].split()
        return model.wv.wmdistance(sent1, sent2)  # Compute WMD
    except Exception as e:
        return np.nan

df = pd.read_csv('data.csv')

# I then set up the gensim model, let me know if you need that bit of code too.

# Make pairwise combination of all indices
combinations = pd.DataFrame(itertools.combinations(df.index, 2))

# To dask df and apply function
dcombinations = dd.from_pandas(combinations, npartitions= 2 * multiprocessing.cpu_count())
dcombinations['distance'] = dcombinations.apply(get_distance, axis=1)
with ProgressBar():
    combinations = dcombinations.compute()

您可以使用 wmd-relax 来提高性能。但是,您首先必须将模型转换为 spaCy 并按照其网页上的描述使用 SimilarityHook:

import spacy
import wmd

nlp = spacy.load('en_core_web_md')
nlp.add_pipe(wmd.WMD.SpacySimilarityHook(nlp), last=True)
doc1 = nlp("Politician speaks to the media in Illinois.")
doc2 = nlp("The president greets the press in Chicago.")
print(doc1.similarity(doc2))