我研究了几种使用Python计算文档中单词的TF-IDF分数的方法。我选择使用TextBlob。
我得到了一个输出,然而,它们是负值。我知道这是不正确的(非负数(tf)除以正数(df)不会产生负值)。
我已经查看了这里发布的以下问题:TFIDF calculating confusion,但它没有任何帮助。
我是如何计算分数的:
def tf(word, blob):
return blob.words.count(word) / len(blob.words)
def n_containing(word, bloblist):
return sum(1 for blob in bloblist if word in blob)
def idf(word, bloblist):
return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))
def tfidf(word, blob, bloblist):
return tf(word, blob) * idf(word, bloblist)然后我简单地打印出单词和他们的分数。
"hello, this is a test. a test is always good."
Top words in document
Word: good, TF-IDF: -0.06931
Word: this, TF-IDF: -0.06931
Word: always, TF-IDF: -0.06931
Word: hello, TF-IDF: -0.06931
Word: a, TF-IDF: -0.13863
Word: is, TF-IDF: -0.13863
Word: test, TF-IDF: -0.13863就我所知和所见所闻,可能是IDF计算不正确?
所有的帮助都将不胜感激。谢谢
发布于 2015-09-07 22:17:30
如果没有输入/输出示例,就很难找出原因。
一种可能是idf()方法,当word出现在每个blob中时,它返回一个负值。这是因为分母中的+1,我假设它是为了避免被零除。
一种可能的解决方法是显式检查零:
def idf(word, bloblist):
x = n_containing(word, bloblist)
return math.log(len(bloblist) / (x if x else 1))注意:在这种情况下,一个单词恰好出现在一个blob中,或者根本没有出现在blob中,都将返回相同的值。还有其他的解决方案可以满足你的需求--只要记住不要取小数的log。
发布于 2015-09-07 22:58:41
IDF得分应为非负。问题出在idf函数的实现中。
尝试这样做:
from __future__ import division
from textblob import TextBlob
import math
def tf(word, blob):
return blob.words.count(word) / len(blob.words)
def n_containing(word, bloblist):
return 1 + sum(1 for blob in bloblist if word in blob)
def idf(word, bloblist):
return math.log(float(1+len(bloblist)) / float(n_containing(word,bloblist)))
def tfidf(word, blob, bloblist):
return tf(word, blob) * idf(word, bloblist)
text = 'tf–idf, short for term frequency–inverse document frequency'
text2 = 'is a numerical statistic that is intended to reflect how important'
text3 = 'a word is to a document in a collection or corpus'
blob = TextBlob(text)
blob2 = TextBlob(text2)
blob3 = TextBlob(text3)
bloblist = [blob, blob2, blob3]
tf_score = tf('short', blob)
idf_score = idf('short', bloblist)
tfidf_score = tfidf('short', blob, bloblist)
print tf_score, idf_score, tfidf_scorehttps://stackoverflow.com/questions/32436427
复制相似问题