python - 如何估计特定文档的查询的重要性?

标签 python machine-learning nlp artificial-intelligence information-retrieval

我有两个单词列表:

q = ['hi', 'how', 'are', 'you']

doc1 = ['hi', 'there', 'guys']

doc2 = ['how', 'is', 'it', 'going']

是否有任何方法可以计算 qdoc1doc2 之间的“相关性”或重要性分数?我的直觉告诉我可以通过 IDF 做到这一点。因此,这是 idf 的实现:

def IDF(term,allDocs):
    docsWithTheTerm = 0
     for doc in allDocs:
            if term.lower() in allDocs[doc].lower().split():
                docsWithTheTerm = docsWithTheTerm + 1
            if docsWithTheTerm > 0:
                return 1.0 + log(float(len(allDocs)) / docsWithTheTerm)
            else:
                return 1.0

但是,这并没有给我本身带来“相关性分数”之类的东西。 IDF 是获得相关性分数的正确方法吗?在 IDF 的情况下,衡量给定文档的查询重要性的方法不正确,我怎样才能获得“相关性分数”之类的东西?

最佳答案

使用tf-idf的前提是强调文本中出现的较罕见的单词:前提是关注过于常见的单词将无法确定哪些单词有意义,哪些单词没有意义。

在您的示例中,以下是如何在 Python 中实现 tf-idf:

doc1 = ['hi', 'there', 'guys']
doc2 = ['how', 'is', 'it', 'going']
doc1=str(doc1)
doc2=str(doc2)

stringdata=doc1+doc2
stringdata

import re
text2=re.sub('[^A-Za-z]+', ' ', stringdata)

from nltk.tokenize import word_tokenize
print(word_tokenize(text2))
text3=word_tokenize(text2)

这些单词已被标记化,如下所示:

['hi', 'there', 'guys', 'how', 'is', 'it', 'going']

然后,生成一个矩阵:

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
matrix = vectorizer.fit_transform(text3).todense()

这是矩阵输出:

matrix([[0., 0., 1., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 1.],
        [0., 1., 0., 0., 0., 0., 0.],
        [0., 0., 0., 1., 0., 0., 0.],
        [0., 0., 0., 0., 1., 0., 0.],
        [0., 0., 0., 0., 0., 1., 0.],
        [1., 0., 0., 0., 0., 0., 0.]])

但是,为了理解这个矩阵,我们现在希望存储为 pandas 数据框,词频按升序排列:

import pandas as pd

# transform the matrix to a pandas df
matrix = pd.DataFrame(matrix, columns=vectorizer.get_feature_names())
# sum over each document (axis=0)
top_words = matrix.sum(axis=0).sort_values(ascending=True)

这是我们的想法:

going    1.0
guys     1.0
hi       1.0
how      1.0
is       1.0
it       1.0
there    1.0
dtype: float64

在此示例中,单词几乎没有上下文 - 所有三个句子都是常见的介绍。因此,tf-idf 不一定会揭示任何有意义的内容,但例如在包含 1000 多个单词的文本的上下文中,tf-idf 在确定单词之间的重要性方面非常有用。例如您可能会认为文本中出现 20-100 次的单词很少 - 但出现的频率足以值得重视。

在这种特殊情况下,人们可以通过确定查询中的单词在相关文档中出现的次数(特别是 tf-idf 标记为重要的单词)来获得相关性分数。

关于python - 如何估计特定文档的查询的重要性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56419706/

相关文章:

python - 查找 2 个大写字母之前的 n 个以大写字母开头的单词(正则表达式)

python - 平铺 map 和 Sprite : am I doing it the right way?

machine-learning - 多语言文本垃圾邮件检测

python - 为新语言构建词性标注器

python - 识别文本中的重要单词和短语

python - MacOS X 上的 pip install lxml 给出错误 : command 'cc' failed

python - 显式类型的 Python 版本?

python - 如何显示 Elasticsearch 的具体答案?

java - 为什么在 WEKA 中读取此 ARFF 文件时会出现过早的 EOF?

python - spaCy 和 scikit-learn 向量化器