【问题标题】:How to get top 10 words from each category in dataframe with 10,000+ entries?如何从具有 10,000 多个条目的数据框中的每个类别中获取前 10 个单词?
【发布时间】:2020-05-10 09:29:34
【问题描述】:

好的,我关注 https://medium.com/@phylypo/text-classification-with-scikit-learn-on-khmer-documents-1a395317d195 ,正在使用这样布局并命名为 result 的数据框:

target   type    post
    1      intj    "hello world shdjd"
    2      entp    "hello world fddf"
    16     estj   "hello world dsd"
    4      esfp    "hello world sfs"
    1      intj    "hello world ddfd"

每个帖子都是独一无二的,目标只是为 16 种类型或类别中的每一种分配编号 1-16。我想使用 sklearn 来查找 16 种类型中的每一种的最热门单词。

我知道您可以使用 TfidfTransformer 获取语料库的热门词并查看 Sklearn how to get the 10 words from each topic ,但我不知道这在数据帧中究竟是如何发挥作用的。

def get_top_n_words(corpus, n=None):
        vec = CountVectorizer().fit(corpus)
        bag_of_words = vec.transform(corpus)
        sum_words = bag_of_words.sum(axis=0)
        words_freq = [(word, sum_words[0, idx]) for word, idx in vec.vocabulary_.items()]
        words_freq = sorted(words_freq, key=lambda x: x[1], reverse=True)
        return words_freq[:n]
    
    print(get_top_n_words(result.post, 10))

这让我在所有帖子中排名前 10,但没有删除“this”或“and”等停用词,并且没有按类型分类。我该怎么做? p>

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    分类部分:

    你可以创建一个字典,将每个主题映射到他的数据,然后获取字典中每个主题的前n个单词,例如:

    # just for exmaple
    corpus_dict = {"topic1": "data1", "topic2": "data2"}
    # top n words dict
    top_n_words_dict = {}
    # iterate overall topics inside the corpus
    # inorder to get top n words for each topic
    for topic in corpus_dict.keys(): 
        # map the topic to the top n words in the topic
        top_n_words_dict[topic] = get_top_n_words(corpus_dict[topic], 10)
        # print for test purposes 
        print(f"Topic: {topic}, top 10 words: {top_n_words_dict[topic]}")
    

    不要专注于代码,专注于想法。

    停用词部分:

    你可以使用nltklib 获取所有英文停用词:

    import nltk
    
    # get set of english stop words
    stop_words = set(nltk.corpus.stopwords.words("english"))
    

    然后你可以在计算词频之前过滤你的词。

    【讨论】:

    • 对,但我的数据框有超过 10,000 个条目。对于 16 种类型中的每一种,我怎样才能有效地做到这一点?每种类型都有很多帖子
    • 在标记词时过滤它们。
    • 对,但这仍然不能回答我的问题。我不知道如何对每种类型的热门词进行排序 - 停用词真的不是主要问题。
    • 谢谢。但是您需要了解这个数据框有多大,并且字典不是一种有效/可行的方法。我需要一个能处理上万条帖子的方法
    猜你喜欢
    • 2020-08-26
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多