【问题标题】:Best way to retrieve top tokens in TF-IDF models在 TF-IDF 模型中检索顶级令牌的最佳方法
【发布时间】:2020-10-01 07:39:38
【问题描述】:

如何从具有以下组件的 SciKit-learn 管道中获取最重要令牌的概览:

multinb = Pipeline([('vect', CountVectorizer()),
           ('tfidf', TfidfTransformer()),
           ('clf', MultinomialNB()),
          ])

multinb.fit(X_train, y_train)

寻找一个简单的 sn-p 来可视化/绘制总体上权重最高的令牌 X)

【问题讨论】:

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


    【解决方案1】:

    提取MultinomialNBcoef_怎么样:

    import pandas as pd
    
    
    multinb = Pipeline([('vect', CountVectorizer()),
               ('tfidf', TfidfTransformer()),
               ('clf', MultinomialNB()),
              ])
    
    multinb.fit(X_train, y_train)
    
    token_imp = pd.DataFrame(
        data=multinb['clf'].coef_[0],
        index=multinb['vect'].get_feature_names(),
        columns=['coefficient']
    ).sort_values(by='coefficient', ascending=False)
    
    print(token_imp)
    

    这将为您提供降序的功能重要性。由于token_imp 是一个数据框,您也可以使用token_imp.head(n) 查看n 个最重要的特征,并使用token_imp.plot.bar() 将它们可视化

    【讨论】:

    • ValueError: 传递值的形状是 (1, 1234),索引意味着 (1234, 1)
    • 对不起,我忘了索引coef_,因为它返回了一个形状数组(n_classes,n_features)。更新了答案。
    • ).sort_values(by="coefficient",ascending=False)
    猜你喜欢
    • 2020-05-28
    • 2017-07-01
    • 2017-04-01
    • 2018-12-18
    • 2018-03-23
    • 2014-06-24
    • 1970-01-01
    • 2020-06-23
    • 2018-08-22
    相关资源
    最近更新 更多