【问题标题】:How to choose the Chi Squared threshold in feature selection特征选择中如何选择卡方阈值
【发布时间】:2020-07-07 17:15:36
【问题描述】:

关于这个:

NLP in Python: Obtain word names from SelectKBest after vectorizing

我找到了这段代码:

    import pandas as pd
    import numpy as np
    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.feature_selection import chi2

    THRESHOLD_CHI = 5 # or whatever you like. You may try with
     # for threshold_chi in [1,2,3,4,5,6,7,8,9,10] if you prefer
     # and measure the f1 scores

    X = df['text']
    y = df['labels']

    cv = CountVectorizer()
    cv_sparse_matrix = cv.fit_transform(X)
    cv_dense_matrix = cv_sparse_matrix.todense()

    chi2_stat, pval = chi2(cv_dense_matrix, y)

    chi2_reshaped = chi2_stat.reshape(1,-1)
    which_ones_to_keep = chi2_reshaped > THRESHOLD_CHI
    which_ones_to_keep = np.repeat(which_ones_to_keep ,axis=0,repeats=which_ones_to_keep.shape[1])

此代码计算卡方检验,并应将最佳特征保持在所选阈值内。 我的问题是如何选择卡方测试分数的阈值?

【问题讨论】:

    标签: python scikit-learn text-classification tf-idf feature-selection


    【解决方案1】:

    卡方没有特定的结果范围,因此很难事先确定阈值。通常你可以做的是根据变量的 p 值对变量进行排序,逻辑是 p 值越低越好,因为它们意味着特征和目标变量之间的相关性更高(我们要丢弃独立的特征,即不目标变量的预测变量)。在这种情况下,您无论如何都必须决定要保留多少特征,这是一个超参数,您可以手动调整,甚至可以使用网格搜索更好地调整。

    请注意,您可以避免手动执行选择,sklearn 已经实现了一个函数SelectKBest,可以根据卡方选择最佳 k 个特征,您可以按如下方式使用它:

    from sklearn.feature_selection import SelectKBest, chi2
    
    X_new = SelectKBest(chi2, k=2).fit_transform(X, y)
    

    但是,如果出于任何原因您只想依赖原始 chi2 值,您可以计算变量之间的最小值和最大值,然后将区间划分为 n 步以通过网格搜索进行测试。

    【讨论】:

      猜你喜欢
      • 2018-08-26
      • 1970-01-01
      • 2015-11-21
      • 2011-07-01
      • 2014-09-21
      • 2013-02-21
      • 1970-01-01
      相关资源
      最近更新 更多