zoukankan      html  css  js  c++  java
  • 机器学习入门-文本数据-构造Tf-idf词袋模型(词频和逆文档频率) 1.TfidfVectorizer(构造tf-idf词袋模型)

    TF-idf模型:TF表示的是词频:即这个词在一篇文档中出现的频率

                         idf表示的是逆文档频率, 即log(文档的个数/1+出现该词的文档个数)  可以看出出现该词的文档个数越小,表示这个词越稀有,在这篇文档中也是越重要的

                         TF-idf: 表示TF*idf, 即词频*逆文档频率

    词袋模型不仅考虑了一个词的词频,同时考虑了这个词在整个语料库中的重要性

    代码:

    第一步:使用DataFrame格式处理数据,同时数组化数据

    第二步:定义函数,进行分词和停用词的去除,并使用‘ ’连接去除停用词后的列表

    第三步:使用np.vectorizer向量化函数,同时调用函数进行分词和停用词的去除

    第四步:使用TfidfVectorizer函数,构造TF-idf的词袋模型

    复制代码
    import pandas as pd
    import numpy as np
    import re
    import nltk #pip install nltk
    
    
    corpus = ['The sky is blue and beautiful.',
              'Love this blue and beautiful sky!',
              'The quick brown fox jumps over the lazy dog.',
              'The brown fox is quick and the blue dog is lazy!',
              'The sky is very blue and the sky is very beautiful today',
              'The dog is lazy but the brown fox is quick!'
    ]
    
    labels = ['weather', 'weather', 'animals', 'animals', 'weather', 'animals']
    
    # 第一步:构建DataFrame格式数据
    corpus = np.array(corpus)
    corpus_df = pd.DataFrame({'Document': corpus, 'categoray': labels})
    
    # 第二步:构建函数进行分词和停用词的去除
    # 载入英文的停用词表
    stopwords = nltk.corpus.stopwords.words('english')
    # 建立词分割模型
    cut_model = nltk.WordPunctTokenizer()
    # 定义分词和停用词去除的函数
    def Normalize_corpus(doc):
        # 去除字符串中结尾的标点符号
        doc = re.sub(r'[^a-zA-Z0-9s]', '', string=doc)
        # 是字符串变小写格式
        doc = doc.lower()
        # 去除字符串两边的空格
        doc = doc.strip()
        # 进行分词操作
        tokens = cut_model.tokenize(doc)
        # 使用停止用词表去除停用词
        doc = [token for token in tokens if token not in stopwords]
        # 将去除停用词后的字符串使用' '连接,为了接下来的词袋模型做准备
        doc = ' '.join(doc)
    
        return doc
    
    # 第三步:向量化函数和调用函数
    # 向量化函数,当输入一个列表时,列表里的数将被一个一个输入,最后返回也是一个个列表的输出
    Normalize_corpus = np.vectorize(Normalize_corpus)
    # 调用函数进行分词和去除停用词
    corpus_norm = Normalize_corpus(corpus)
    
    # 第四步:使用TfidVectorizer进行TF-idf词袋模型的构建
    from sklearn.feature_extraction.text import TfidfVectorizer
    
    Tf = TfidfVectorizer(use_idf=True)
    Tf.fit(corpus_norm)
    vocs = Tf.get_feature_names()
    corpus_array = Tf.transform(corpus_norm).toarray()
    corpus_norm_df = pd.DataFrame(corpus_array, columns=vocs)
    print(corpus_norm_df.head())
    复制代码

  • 相关阅读:
    在 .NET 3.5 中序列化和反序列化 JSON Kevin
    .NET 3.5 获取不全Cookie的问题 Kevin
    C#反序列化JSON数组对象 Kevin
    使用ConfigurationManager类 读写配置文件 Kevin
    C# post数据时 出现如下错误: System.Net.WebException: 远程服务器返回错误: (417) Expectation Failed 的解决办法 Kevin
    .NET 关于反序列化 JSON 对象数组的问题 Kevin
    为什么调用thread.Abort(),线程不会马上停止 Kevin
    vs2005调用迅雷完美解决方案 Kevin
    .NET 复杂的 DataBinding 接受 IList 或 IListSource 作为数据源 Kevin
    找不到DataContract属性! Kevin
  • 原文地址:https://www.cnblogs.com/liuys635/p/12436128.html
Copyright © 2011-2022 走看看