首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python (TextBlob) TF-IDF计算

Python (TextBlob) TF-IDF计算
EN

Stack Overflow用户
提问于 2015-09-07 18:26:09
回答 2查看 3.5K关注 0票数 2

我研究了几种使用Python计算文档中单词的TF-IDF分数的方法。我选择使用TextBlob。

我得到了一个输出,然而,它们是负值。我知道这是不正确的(非负数(tf)除以正数(df)不会产生负值)。

我已经查看了这里发布的以下问题:TFIDF calculating confusion,但它没有任何帮助。

我是如何计算分数的:

代码语言:javascript
复制
 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)

然后我简单地打印出单词和他们的分数。

代码语言:javascript
复制
    "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计算不正确?

所有的帮助都将不胜感激。谢谢

EN

回答 2

Stack Overflow用户

发布于 2015-09-07 22:17:30

如果没有输入/输出示例,就很难找出原因。

一种可能是idf()方法,当word出现在每个blob中时,它返回一个负值。这是因为分母中的+1,我假设它是为了避免被零除。

一种可能的解决方法是显式检查零:

代码语言:javascript
复制
def idf(word, bloblist):
    x = n_containing(word, bloblist)
    return math.log(len(bloblist) / (x if x else 1))

注意:在这种情况下,一个单词恰好出现在一个blob中,或者根本没有出现在blob中,都将返回相同的值。还有其他的解决方案可以满足你的需求--只要记住不要取小数的log

票数 2
EN

Stack Overflow用户

发布于 2015-09-07 22:58:41

IDF得分应为非负。问题出在idf函数的实现中。

尝试这样做:

代码语言:javascript
复制
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_score
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32436427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档