zoukankan      html  css  js  c++  java
  • 使用scikit-learn进行自然语言处理——文档特征提取(基于词袋模型bag-of-words) 计算tf-idf

    首先python环境已经安装了numpy, scipy, sklearn, jieba

    # coding=utf-8
    """
    @desc: 
    """
    from scipy import sparse
    from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
    from jieba import cut
    
    # 用jieba进行中文分词
    import jieba
    
    '''
    corpus是一个列表,每篇文章是该列表的一个字符串类型的元素,word_separator是文章分词后使用该分隔符分割每个单词
    '''
    
    
    def word_cut_chinese(corpus, word_separator):
        word_cut_results = list()
        for document in corpus:
            word_cut_results.append(word_separator.join(jieba.cut(document)))
        # 可再加一步去停用词
        return word_cut_results
    
    # ---------------使用以上函数处理----------------------------------------
    
    
    WORD_SEPARATOR = ' '
    corpus = ['我第一次学习自然语言处理,真的有点慌真的好着急',
              '不要紧张一切都会好的']
    train_data = word_cut_chinese(corpus, WORD_SEPARATOR)
    print('word_cuted_corpus is :', train_data)
    # word_cuted_corpus is : ['我 第一次 学习 自然语言 处理 , 真的 有点 慌 真的 好 着急', '不要 紧张 一切 都 会 好 的']
    
    print('--------分词结果-------')
    for doc in train_data:
        print(doc)
    
    
    # 用sklearn构建bag of words
    from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
    count_vectorizer = CountVectorizer()
    # 训练语料库,得到一个scipy的稀疏矩阵count_matrix
    count_matrix = count_vectorizer.fit_transform(train_data)
    print(u"矩阵的稀疏表示count_matrix is:", '
    ',count_matrix)
    # count_matrix is: 含义:第0篇文档的编号为7的词在第0篇文档中出现的的频次是1
    #    (0, 7)    1
    #    (0, 3)    1
    
    # 得到稠密矩阵
    print(u"稠密矩阵count_matrix_todense  is:", '
    ', count_matrix.todense())
    
    # 查看整个语料库的tokens
    tokens = count_vectorizer.vocabulary_
    print('可以得到token字典,tokens is:', '
    ', tokens)
    
    # 通过单词查找id
    print(u'真的这个词的索引是:',count_vectorizer.vocabulary_.get('真的'))
    # 通过id查找单词
    print(tokens.items())
    # filter函数过滤字典的每一项
    print(u'索引为5的词语是',list(filter(lambda x: x[1] == 5, tokens.items()))[0][0])
    
    '''可以使用训练语料生成的词典为新的语料生成特征矩阵'''
    
    # 应用到新的语料
    corpus_new=['我真的很喜欢你']
    word_cuted_corpus_new=word_cut_chinese(corpus_new,WORD_SEPARATOR)
    matrix_new = count_vectorizer.transform(word_cuted_corpus_new)
    print(matrix_new.toarray())
    
    '''使用sklearn计算tf-idf矩阵'''
    tf_idf_transformer = TfidfTransformer()
    tf_idf_matrix = tf_idf_transformer.fit_transform(count_matrix)
    print('-------tf-idf矩阵密集表示----')
    print(tf_idf_matrix.todense())
    
    print('-------tf-idf矩阵稀疏表示----')
    print(tf_idf_matrix)

    ref: https://blog.csdn.net/chansonzhang/article/details/84023654?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight

  • 相关阅读:
    PostgreSQL中的partition-wise join
    Partition-wise join
    外观模式 门面模式 Facade 结构型 设计模式(十三)
    桥接模式 桥梁模式 bridge 结构型 设计模式(十二)
    组合模式 合成模式 COMPOSITE 结构型 设计模式(十一)
    创建型设计模式对比总结 设计模式(八)
    原型模式 prototype 创建型 设计模式(七)
    单例模式 创建型 设计模式(六)
    建造者模式 生成器模式 创建型 设计模式(五)
    抽象工厂模式 创建型 设计模式(四)
  • 原文地址:https://www.cnblogs.com/yoyowin/p/13524818.html
Copyright © 2011-2022 走看看