【问题标题】:How to find important words using TfIdfVectorizer?如何使用 TfIdfVectorizer 查找重要单词?
【发布时间】:2021-05-11 10:33:37
【问题描述】:

考虑下面的例子。代表文件的重要词是“Bob”和“Sara”。但是对于max_features,输出往往会显示频繁出现的单词。当语料库很大时,情况会变得更糟。我们怎么才能只得到重要的词?

from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd


corpus = [
    'hi, my name is Bob.',
    'hi, my name is Sara.'
]

vectorizer = TfidfVectorizer(max_features=2)
X = vectorizer.fit_transform(corpus).todense()


df = pd.DataFrame(X, columns=vectorizer.get_feature_names())

输出:

,hi,is
0,0.7071067811865475,0.7071067811865475
1,0.7071067811865475,0.7071067811865475

【问题讨论】:

    标签: python scikit-learn nlp tf-idf tfidfvectorizer


    【解决方案1】:

    如果增加 max_features:

    vectorizer = TfidfVectorizer(max_features=10)
    X = vectorizer.fit_transform(corpus).todense()
    df = pd.DataFrame(X, columns=vectorizer.get_feature_names())
    print(df)
       bob       hi       is       my     name      sara 
    0  0.574962  0.40909  0.40909  0.40909  0.40909  0.000000 
    1  0.000000  0.40909  0.40909  0.40909  0.40909  0.574962
    

    您可以看到 sara 和 bob 非常重要,因为它们的 tfidf 较高,而另一个较小且相等,这很有意义,因为在两个句子中都重复了。

    请注意,如 here。如max_features: “如果不是无,则构建一个仅考虑按语料库中的词频排序的最高 max_features 的词汇表。”所以它可能会像以前的情况一样删除更有用的词。

    也许您可能对max_dfmin_df 选项更感兴趣:

    vectorizer = TfidfVectorizer(max_df=0.5)
    X = vectorizer.fit_transform(corpus).todense()
    df = pd.DataFrame(X, columns=vectorizer.get_feature_names())
    print(df)
       bob  sara
    0  1.0   0.0
    1  0.0   1.0
    

    也许最好尝试不同的方法,直到您了解正在发生的事情。

    从另一个角度来看,删除一些停用词也可能很好。

    【讨论】:

    • 谢谢。那么下面的陈述会引出这10个重要特征吗? "max_features=10, max_df=0.5"
    • 视情况而定。你应该玩一下,直到你掌握为止。我将功能增加到最大,以查看外观。因为问题是如此之小,您实际上可以全部使用它们。
    • 我明白了。但是如果语料库非常大并且看不到差异怎么办。有没有办法以高可靠性做到这一点?
    • 我会阻止单词并删除停用词。在那之后,我会尝试看看我可以在计算能力和时间方面引入多少功能。之后,我将删除其中的一些。可能使用 max_df。
    • 谢谢,有道理。所以你不推荐max_features参数吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2022-08-17
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多