gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:31:24 25 4
gpt4 key购买 nike

我有两个单词列表:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com