【发布时间】:2020-04-03 16:30:32
【问题描述】:
我正在尝试使用 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()
【问题讨论】:
标签: python python-multiprocessing dask gensim wmd