【问题标题】:TfIdf vectorizer returning positive values for absent wordsTfIdf 矢量化器为缺失的单词返回正值
【发布时间】:2018-10-08 18:28:05
【问题描述】:

我正在使用 sklearn 中的 TfIdf 矢量化器对语料库进行矢量化。语料库很大,但数据或多或少是这样的:

index speaker text
1     Bob     'this is sample text'
2     Dick    'also some sample words but different ones'
3     Jane    'stuff goes here that did not go above'
4     Mary    'my name is mary and my text is not being analyzed'

我想了解前三个说话者的单词 TfIdf 值是如何按说话者分解的。所以我有:

from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer(stop_words=stemmed_stops)
word_vec = vec.fit_transform(df.loc[['Bob', 'Dick', 'Jane'], 'text'])

在对语料库进行矢量化之后,我创建了一个包含 TfIdf 值的数据框,其列是词汇表:

speaker_vocab = pd.DataFrame(word_vec.toarray(), index=['Bob', 'Dick', 'Jane'], columns = vec.vocabulary_)

这给出了一个如下所示的数据框:

    this  sample   that  my  text ...
Bob  0.5    0.3  0.0   0.0   0.5

问题在于,从不使用某些术语的说话者会得到这些术语的正 TfIdf 值。例如,如果我查看 Jane 的单词,我会得到:

In: df.loc['Jane'].sort_values(ascending=False)
Out:
sample 0.32
goes .14
text .11

这似乎发生在所有说话者身上,而且从来没有出现在他们的行中的词是肯定的。正值不同,但它们仍然是正值。

一般来说,向量化器是否有理由为不在同一说话人行中的单词返回正值?

【问题讨论】:

  • 请在'stems'列显示数据
  • @VivekKumar 就这个问题而言,stems 是我的错字。我刚刚删除了涉及这个问题的整个代码部分。感谢举报

标签: pandas scikit-learn tf-idf


【解决方案1】:

您在

中使用了错误的列参数
speaker_vocab = pd.DataFrame(word_vec.toarray(), 
                             index=['Bob', 'Dick', 'Jane'], 
                             columns = vec.vocabulary_)

根据documentation

词汇_:字典

A mapping of terms to feature indices.

字典可以以任意顺序返回项目。所以这个dict 可能(将)不会以与word_vec 中返回的数据相同的顺序给出名称。

要按确切顺序获取名称,请使用vec.get_feature_names()

speaker_vocab = pd.DataFrame(word_vec.toarray(), 
                             index=['Bob', 'Dick', 'Jane'], 
                             columns = vec.get_feature_names())

之后你会得到正确的输出。

speaker_vocab.loc['Jane'].sort_values(ascending=False)

#Output:
stuff        0.5
goes         0.5
go           0.5
above        0.5
words        0.0
this         0.0
text         0.0
sample       0.0
ones         0.0

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2018-06-04
    • 2017-05-03
    • 2017-12-11
    • 2019-06-09
    • 2021-02-03
    • 2021-01-23
    • 2018-06-17
    • 2015-04-08
    相关资源
    最近更新 更多