【问题标题】:Gensim for similaritiesGensim 的相似之处
【发布时间】:2020-11-28 02:05:49
【问题描述】:

我在 pandas 中有一个组织描述和项目名称的数据框,如下所示:

列是df['org_name']df['org_description']df['proj_title']。我想为每个项目(每一行)添加一列,其中包含组织描述和项目标题之间的相似度分数。

我正在尝试使用gensimhttps://radimrehurek.com/gensim/auto_examples/core/run_similarity_queries.html。但是,我不确定如何根据我的用例调整本教程,因为在本教程中我们得到了一个新查询 doc = "Human computer interaction",然后将其与语料库中的文档单独进行比较。不确定在哪里做出这个选择 (sims?vec_lsi?)

但我只希望数据框df 的给定行中的两个项目的相似度得分,而不是其中一个与整个语料库的相似度得分,对于每一行,然后将其作为一列附加到df。我该怎么做?

【问题讨论】:

  • 附加的教程是使用 LSI(潜在语义索引)查询语料库(文本集合)。如果你想执行 doc-doc 相似性,有更合适的算法来做到这一点。
  • @thorntonc 如果更好,请随时用不同的算法更新/替换您的答案。例如,我发现了这个:stackoverflow.com/questions/22433884/…。可能所有需要的只是在这里应用这些功能的某种方式吗? (例如,参见 'eng.mrgh' 的帖子)

标签: python


【解决方案1】:

这是对 Gensim LSI 教程的改编,其中描述表示句子的语料库,标题是针对它进行的查询。

from gensim.models import LsiModel
from collections import defaultdict
from gensim import corpora

def desc_title_sim(desc, title):
    # remove common words and tokenize
    stoplist = set('for a of the and to in'.split())  # add a longer stoplist here
    sents = desc.split('.')  # crude sentence tokenizer
    texts = [
        [word for word in sent.lower().split() if word not in stoplist]
        for sent in sents
    ]

    # remove words that appear only once
    frequency = defaultdict(int)
    for text in texts:
        for token in text:
            frequency[token] += 1

    texts = [
        [token for token in text if frequency[token] > 1]
        for text in texts
    ]

    dictionary = corpora.Dictionary(texts)
    corpus = [dictionary.doc2bow(text) for text in texts]

    lsi = LsiModel(corpus, id2word=dictionary, num_topics=2)

    vec_bow = dictionary.doc2bow(title.lower().split())
    vec_lsi = lsi[vec_bow]  # convert the query to LSI space
    return vec_lsi

逐行应用函数以获得相似度:

df['sim'] = df.apply(lambda row: desc_title_sim(row['org_description'], row['proj_title']), axis=1)

新创建的 sim 列将填充类似的值

[(0, 0.4618210045327158), (1, 0.07002766527900064)]

【讨论】:

  • 谢谢!但是,我希望语料库保持不变(我认为)——它将代表完整的描述和标题集(不标记为句子)。所以对于documents,我将吸收df['org_description']df['proj_title'] 的所有元素。我会使用它作为向量空间的基础,并使用每个向量来获得给定描述和标题之间的相似性。
  • 这个算法不是正确的方法吗?如果没有,你会怎么做? (也就是说,我想要 doc-doc 相似度,但是为了将相似度分数相互比较,我认为必须计算 doc-doc 相似度,而不必每次都更改轴——所以 documents 必须保持不变. 而且一个文档中没有足够的文本/信息来构成一个语料库进行比较)
  • @Mobeus Zoom 这些是一些优点,我没有看到任何使用这些参数的 Gensim 文档/示例,我会尝试更深入地搜索文档以修改我的答案或寻找替代方案文档-文档相似度的方法。
  • 是的,请随时提出替代方案。我在上面指出的链接(stackoverflow.com/questions/22433884/…)可能很有希望?但我对 Gensim 一点也不熟悉,你可能知道
猜你喜欢
  • 1970-01-01
  • 2015-10-27
  • 2015-10-10
  • 1970-01-01
  • 2014-03-20
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
相关资源
最近更新 更多