Skip to main content
 首页 » 编程设计

python之tfidf.transform() 函数没有返回正确的值

2024年10月01日14myhome

我正在尝试将 tfidf 向量化器拟合到某个文本语料库,然后使用相同的向量化器来查找新文本的 tfidf 值的总和。但是,总和值并不符合预期。下面是示例:

text = ["I am new to python and R , how can anyone help me","why is no one able to crack the python code without help"] 
tf= TfidfVectorizer(stop_words='english',ngram_range =(1,1)) 
tf.fit_transform(text) 
zip(tf.get_feature_names(),tf.idf_) 
 
[(u'able', 1.4054651081081644), 
 (u'code', 1.4054651081081644), 
 (u'crack', 1.4054651081081644), 
 (u'help', 1.0), 
 (u'new', 1.4054651081081644), 
 (u'python', 1.0)] 

现在,当我用新文本尝试相同的 tf 时:

new_text = "i am not able to code" 
np.sum(tf.transform([new_text])) 
1.4142135623730951 

我预计输出在 2.80 左右。任何关于此处可能出现问题的建议都将非常有帮助。

请您参考如下方法:

这是因为“l2 规范化”(TfidfVectorizer 中的默认设置)。 如您所料,transform() 的第一个结果是:

array([[ 1.40546511,  1.40546511,  0.        ,  0.        ,  0.        , 
     0.        ]]) 

但是现在标准化已经完成了。在此,上述向量除以除法器:

dividor = sqrt(sqr(1.40546511)+sqr(1.40546511)+sqr(0)+sqr(0)+sqr(0)+sqr(0)) 
        = sqrt(1.975332175+1.975332175+0+0+0+0) 
        = 1.98762782 

所以最后得到的数组是:

array([[ 0.70710678,  0.70710678,  0.        ,  0.        ,  0.        , 
     0.        ]]) 

然后您应用求和,其结果为 = 1.4142135623730951。

希望现在一切都清楚了。可以引用my answer here完成 TfidfVectorizer 的工作。