1.通过sklearn.feature_selection中的SelectKBest类,可以从numpy.array中提取特征,以下以卡方分布为例,从文本中进行特征抽取,得到选取的具体分词和所有分词对分类贡献度的评分;

from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
  1. 首先是语料准备,需要准备两个输入内容:已分词的文本list_doc(里面的每一条是一个str字符串格式的、以空格分割的分词结果)、每条文本的标签label_doc;可使用jieba或pyltp;

    #用于pyltp分词
    def get_cut(sentence):
     from pyltp import Segmentor
     LTP_DATA_DIR = 'E:/Program Files/workspace/ltp_data_v3.4.0'  # ltp模型目录的路径
     cws_model_path = os.path.join(LTP_DATA_DIR, 'cws.model')  # 分词模型路径,模型名称为`cws.model`
     segmentor = Segmentor()  # 初始化实例
     segmentor.load(cws_model_path)  # 加载模型
    
     #读取停用词
     with open(os.path.join(LTP_DATA_DIR, 'stopwords.txt'), 'r', encoding="UTF-8") as text_file:
         stop_word = text_file.readlines()
     stop_word = [item.strip() for item in stop_word]
    
     words_cut = []
     for element in sentence:
         temp = list(segmentor.segment(element))
         new_temp = list(filter(lambda x: len(x)>1, temp))
         new_temp = [item for item in new_temp if item not in stop_word]
         words_cut.append(' '.join(new_temp))
    
     segmentor.release()  # 释放模型
    
     return words_cut
  2. 使用klearn.feature_extraction.text进行词频统计,得到词汇表和词频矩阵,以下函数参数为list_doc,返回词频矩阵和对应的特征词;

    def get_count_vect(corpus):
     from sklearn.feature_extraction.text import CountVectorizer
     #将文本中的词语转换为词频矩阵 矩阵元素a[i][j] 表示j词在i类文本下的词频
     count_vector = CountVectorizer(min_df=1, max_df=1.0, token_pattern='\\b\\w+\\b')
     #matrix词频的稀疏矩阵表示。括号中的第一个元素表示的是行数,第二个元素表示的是列数。
     matrix= count_vector.fit_transform(corpus)
     #对应列的特征词
     feature_names = count_vector.get_feature_names()
    # =============================================================================
    #     #toarray为完整矩阵表示,与matrix是一个东西
    #     feature_array = matrix.toarray()
    # =============================================================================
     return matrix,feature_names
  3. 主函数:

    if __name__=="__main__":
    # 获取文本和标签
    sentence,label = get_sentence_label('某文档.xls')
    # 文本分词
    words_list = get_cut(sentence)
    # 获取词频和特征名(分词名)
    matrix,feature_names = text_tools.get_count_vect(words_list)
    
    from sklearn.feature_selection import SelectKBest
    from sklearn.feature_selection import chi2
    import pandas as pd
    # 新建模型,传入chi2表示使用卡方分布选取特征
    model = SelectKBest(chi2, k=20)#选择k个最佳特征
    # fit和transform一步到位,注意这里需要将词频统计得到的稀疏矩阵转为完整矩阵表示
    # select_feature为经选取过滤后的词频矩阵,可用于文本分类
    select_feature = model.fit_transform(matrix.toarray(), label)
    
    result_temp = []
    # 获取所选特征,model.get_support(True)返回原始输入矩阵(方阵)中,选取的下标,
    # result_temp为经过选取后的分词特征
    for index in model.get_support(True):
       result_temp.append(feature_names[index])
    # 获取所有特征(分词)对label分类的贡献度评分,将其存为excel
    feature_name_score = pd.DataFrame()
    feature_name_score['name'] = feature_names
    feature_name_score['score'] = model.scores_
    feature_name_score.to_excel('feature_name_score.xlsx')
    # 可通过score曲线决定选取多少个特征;
    # 也可直接将select_feature用于分类训练、测试后用测试得分后反过来得到应选取哪些特征
  4. 其他sklearn特征选取例子:
    https://link.zhihu.com/?target=https%3A//www.programcreek.com/python/example/93974/sklearn.feature_selection.SelectKBest