【问题标题】:How to Quickly Remove Similar Strings?如何快速删除相似的字符串?
【发布时间】:2020-11-13 14:25:10
【问题描述】:

现在,我有一个包含大约 70,000 条推文的数据集,我正在尝试删除过于相似的推文。我决定使用大于 0.9 的 Levenshtein 比率作为过于相似的推文的阈值。但是,我当前的代码本质上是将每条推文与其他每条推文进行比较,给我 O(N^2),这非常慢。运行需要超过 12 个小时,这实在是太多了。我尝试并行化它,这就是我现在正在运行的,但我不知道这是否会将它加速到可接受的程度。有什么方法可以在 O(N) 中完成吗?

import json
import multiprocessing as mp
from pathlib import Path

import Levenshtein

def check_ratio(similar_removed, try_tweet):
    for tweet in similar_removed:
        if Levenshtein.ratio(try_tweet, tweet[1]) > 0.9:
            return 1
    return 0

def main():
    path = Path('C:/Data/Python/JobLoss')
    orig_data = []
    with open(path / 'Processed.json') as f:
        data = json.load(f)
        for tweet in data:
            orig_data.append(tweet[2])
    pool = mp.Pool(mp.cpu_count())
    similar_removed = []
    similar_removed.append((0, orig_data[0]))
    for i in range(1, len(orig_data)):
        print('%s / %s' % (i, len(orig_data)))
        too_similar = 0
        try_tweet = orig_data[i]
        too_similar = pool.apply(check_ratio, args=(similar_removed, try_tweet))
        if not too_similar:
            similar_removed.append((i, try_tweet))
    pool.close()
    final = [data[ind[0]] for ind in similar_removed]
    with open(path / 'ProcessedSimilarRemoved.json', 'w') as f:
            json.dump(final, f)

if __name__ == '__main__':
    main()

【问题讨论】:

  • 您是否考虑过在您的数据上训练一个词到 vec 模型,然后过滤掉嵌入空间中彼此相邻的推文?
  • 对于两个过于相似的字符串,你要同时丢弃它们吗?
  • Clustering a long list of strings (words) into similarity groups - (stats.stackexchange) - 有很多书籍和论文。
  • @user2589273 - 您的建议有参考吗?
  • @wwii 只是其中之一

标签: python string performance levenshtein-distance tweets


【解决方案1】:

我最终使用了this 问题的顶级答案中描述的方法,该方法使用 LSH 进行次线性时间查询,给出了次二次的总体复杂度;足够快满足我的需要。本质上,您使用 k-shingling 将每条推文变成一个集合,然后使用 min hash lsh 快速将相似的集合存储在一起。然后,无需将每条推文与其他每条推文进行比较,您只需在其桶中查找匹配项,这使得该方法比在所有对上使用 Levenshtein 比率快得多。

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-24
    • 1970-01-01
    • 2015-02-07
    相关资源
    最近更新 更多