【问题标题】:How to know the words associated with a specific class in NLP model?如何知道 NLP 模型中与特定类相关的单词?
【发布时间】:2020-10-11 06:13:02
【问题描述】:

我已经使用逻辑回归算法和 TF-IDF 矢量化器为“消费者投诉分类”训练了 NLP 模型。我想知道我的模型与特定类相关联的词。我正在寻找这样的东西 -
Class 1 = ["帮助我的模型识别输入文本属于此类的单词列表"]

【问题讨论】:

    标签: scikit-learn nlp logistic-regression tf-idf multiclass-classification


    【解决方案1】:

    我想你需要的更像是与一个类相关的最重要的单词(或更好的tokens)。因为通常所有标记都会以一种或另一种方式与所有类“关联”。所以我会用以下方法回答你的问题:

    假设您由TfidfVectorizer 生成的标记(或单词)存储在X_train 中,标签在y_train 中,并且您训练了如下模型:

    from sklearn.linear_model import LogisticRegression
    from sklearn.feature_extraction.text import TfidfVectorizer
    
    vectorizer = TfidfVectorizer()
    X_train = vectorizer.fit_transform(corpus)
    
    clf = LogisticRegression()
    clf.fit(X_train, y_train)
    

    LogisticRegressioncoef_ 属性的形状为 (n_classes, n_features),用于多类问题,包含为每个令牌和每个类计算的系数。这意味着,通过根据类对其进行索引,可以访问用于该特定类的系数,例如coef_[0] 代表 0 类,coef_[1] 代表 1 类,依此类推。

    只需将标记名称与系数重新关联,并根据它们的值对它们进行排序。然后,您将获得每个班级最重要的令牌。获取0 类最重要标记的示例:

    import pandas as pd
    
    important_tokens = pd.DataFrame(
        data=clf.coef_[0],
        index=vectorizer.get_feature_names(),
        columns=['coefficient']
    ).sort_values(ascending=False)
    

    important_tokens 中的标记现在根据它们对0 类的重要性进行排序,并且可以通过索引值轻松提取。例如,要将 n 个最重要的特征作为一个列表:important_tokens.head(n).index.values

    如果您想要其他类最重要的标记,只需根据需要替换coef_ 属性的索引即可。

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 2019-04-26
      • 2012-10-30
      • 2020-12-21
      相关资源
      最近更新 更多