python - 为什么TF-IDF的值和IDF_不一样?

标签 python scikit-learn tf-idf tfidfvectorizer

为什么向量化语料的值和通过idf_属性得到的值不一样? idf_ 属性不应该以它出现在语料库矢量化中的相同方式返回逆文档频率 (IDF) 吗?

from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ["This is very strange",
          "This is very nice"]
vectorizer = TfidfVectorizer()
corpus = vectorizer.fit_transform(corpus)

print(corpus)

语料库向量化:

  (0, 2)    0.6300993445179441
  (0, 4)    0.44832087319911734
  (0, 0)    0.44832087319911734
  (0, 3)    0.44832087319911734
  (1, 1)    0.6300993445179441
  (1, 4)    0.44832087319911734
  (1, 0)    0.44832087319911734
  (1, 3)    0.44832087319911734

词汇和idf_值:

print(dict(zip(vectorizer.vocabulary_, vectorizer.idf_)))

输出:

{'this': 1.0, 
 'is': 1.4054651081081644, 
 'very': 1.4054651081081644, 
 'strange': 1.0, 
 'nice': 1.0}

词汇索引:

print(vectorizer.vocabulary_)

输出:

{'this': 3, 
 'is': 0, 
 'very': 4, 
 'strange': 2, 
 'nice': 1}

为什么单词this的IDF值在语料库中是0.44,而通过idf_得到的是1.0 >?

最佳答案

这是因为 l2 归一化,它在 TfidfVectorizer() 中默认应用。 如果将 norm 参数设置为 None,您将获得与 idf_ 相同的值。


>>> vectorizer = TfidfVectorizer(norm=None)

#output

  (0, 2)    1.4054651081081644
  (0, 4)    1.0
  (0, 0)    1.0
  (0, 3)    1.0
  (1, 1)    1.4054651081081644
  (1, 4)    1.0
  (1, 0)    1.0
  (1, 3)    1.0

此外,您计算特征对应 idf 值的方法是错误的,因为 dict 不保留顺序。

您可以使用以下方法:

 >>>> print(dict(zip(vectorizer.get_feature_names(), vectorizer.idf_)))
      
     {'is': 1.0,
      'nice': 1.4054651081081644, 
      'strange': 1.4054651081081644, 
      'this': 1.0, 
      'very': 1.0}

关于python - 为什么TF-IDF的值和IDF_不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56653159/

相关文章:

python - 如何绘制文本 K 均值聚类的结果?

python - 如何获得最高 tf-idf 分数的前 n 个项 - 大稀疏矩阵

python - 如何加入两个 Pandas 数据框,使第二个表重复

python - Python 中的切片问题

python-3.x - 使用python3的简单nltk情感分析代码

python - 如何比较预测频率数据与实际频率数据?

python - 创建 TF-IDF 矩阵 Python 3.6

elasticsearch - 为什么 ElasticSearch 中的 "More Like This"不遵守单个术语的 TF-IDF 顺序?

python - 您如何查看交互式 Python 中的整个命令历史记录?

python - 从 ipython 导入