【问题标题】:show feature names after feature selection选择特征后显示特征名称
【发布时间】:2012-12-17 11:41:23
【问题描述】:

我需要为文本构建一个分类器,现在我正在使用 TfidfVectorizer 和 SelectKBest 来选择特征,如下所示:

vectorizer = TfidfVectorizer(sublinear_tf = True, max_df = 0.5, stop_words = 'english',charset_error='strict')

X_train_features = vectorizer.fit_transform(data_train.data)
y_train_labels = data_train.target;

ch2 = SelectKBest(chi2, k = 1000)
X_train_features = ch2.fit_transform(X_train_features, y_train_labels)

我想在选择 k 个最佳特征后打印出所选特征名称(文本),有什么办法吗?我只需要打印出选定的功能名称,也许我应该改用 CountVectorizer?

【问题讨论】:

    标签: machine-learning scikit-learn


    【解决方案1】:

    以下应该有效:

    np.asarray(vectorizer.get_feature_names())[ch2.get_support()]
    

    【讨论】:

      【解决方案2】:

      为了扩展@ogrisel 的答案,返回的特征列表在矢量化后的顺序相同。下面的代码将为您提供一个排名靠前的特征列表,该列表根据其 Chi-2 分数以降序排列(连同相应的 p 值):

      top_ranked_features = sorted(enumerate(ch2.scores_),key=lambda x:x[1], reverse=True)[:1000]
      top_ranked_features_indices = map(list,zip(*top_ranked_features))[0]
      for feature_pvalue in zip(np.asarray(train_vectorizer.get_feature_names())[top_ranked_features_indices],ch2.pvalues_[top_ranked_features_indices]):
              print feature_pvalue
      

      【讨论】:

        猜你喜欢
        • 2017-02-10
        • 2017-06-03
        • 2020-07-27
        • 2014-09-20
        • 2020-08-13
        • 1970-01-01
        • 2018-04-07
        • 2016-01-27
        • 1970-01-01
        相关资源
        最近更新 更多