• 13-垃圾邮件分类2


    1.读取

    def read_dataset():
         file_path = r'C:Userslucas-lywPycharmProjectshelloSMSSpamCollection'
         sms = open(file_path, encoding='utf-8')
         sms_data = []
         sms_label = []
         csv_reader = csv.reader(sms, delimiter='	')
         for line in csv_reader:
            sms_label.append(line[0])  # 提取出标签
            sms_data.append(preprocessing(line[1]))  
         sms.close()
    

    2.数据预处理

    # 根据词性,生成还原参数pos
    # 预处理
    def get_wordnet_pos(treebank_tag):
         if treebank_tag.startswith('J'):
            return nltk.corpus.wordnet.ADJ
         elif treebank_tag.startswith('V'):
            return nltk.corpus.wordnet.VERB
         elif treebank_tag.startswith('N'):
             return nltk.corpus.wordnet.NOUN
         elif treebank_tag.startswith('R'):
            return nltk.corpus.wordnet.ADV
         else:
           return nltk.corpus.wordnet.NOUN
    
    def preprocessing(text):
         tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]
         stops = stopwords.words('english')
         tokens = [token for token in tokens if token not in stops]  # 去除停用词
         tokens = [token.lower() for token in tokens if len(token) >= 3]  # 大小写,短词
         lmtzr = WordNetLemmatizer()
         tag = nltk.pos_tag(tokens)  # 词性
         # 词性还原
         tokens = [lmtzr.lemmatize(token, pos=get_wordnet_pos(tag[i][1])) for i, token in enumerate(tokens)]
         preprocessed_text = ' '.join(tokens)
         return preprocessed_text
    

    3.数据划分—训练集和测试集数据划分

    from sklearn.model_selection import train_test_split

    x_train,x_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=0, stratify=y_train)

    4.文本特征提取

    sklearn.feature_extraction.text.CountVectorizer

    https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html?highlight=sklearn%20feature_extraction%20text%20tfidfvectorizer

    sklearn.feature_extraction.text.TfidfVectorizer

    https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html?highlight=sklearn%20feature_extraction%20text%20tfidfvectorizer#sklearn.feature_extraction.text.TfidfVectorizer

    from sklearn.feature_extraction.text import TfidfVectorizer

    tfidf2 = TfidfVectorizer()

    观察邮件与向量的关系

    向量还原为邮件

    # 转化为向量
    from sklearn.feature_extraction.text import TfidfVectorizer
    tfidf2 = TfidfVectorizer()
    X_train = tfidf2.fit_transform(x_train)
    X_test = tfidf2.transform(x_test)
    X_train.toarray()  # 转换成数组
    
    # 向量还原成邮件
    import numpy as np
    print("第一封邮件:", X_train.toarray()[0])
    a = np.flatnonzero(X_train.toarray()[0])  # 该函数输入一个矩阵,返回扁平化后矩阵中非零元素的位置(index)
    print("非零元素的位置:", a)
    print("非零元素的值:", X_train.toarray()[0][a])
    b = tfidf2.vocabulary_  # 生成词汇表
    key_list =[]
    for key, value in b.items():
        if value in a:
            key_list.append(key)  # key非0元素对应的单词
    print("非零元素对应的单词:", key_list)
    print("向量化之前的邮件:", X_train[0])
    

      

    4.模型选择

    from sklearn.naive_bayes import GaussianNB

    from sklearn.naive_bayes import MultinomialNB

    说明为什么选择这个模型?

    def mnb_model(x_train, x_test, y_train, y_test):
        mnb = MultinomialNB()
        mnb.fit(x_train, y_train)
        ypre_mnb = mnb.predict(x_test)
        print("预测的准确率:", sum(ypre_mnb == y_test) / len(y_test))
        return ypre_mnb
    

      

    5.模型评价:混淆矩阵,分类报告

    from sklearn.metrics import confusion_matrix

    confusion_matrix = confusion_matrix(y_test, y_predict)

    说明混淆矩阵的含义

    from sklearn.metrics import classification_report

    说明准确率、精确率、召回率、F值分别代表的意义 

    # 混淆矩阵、分类报告
    from sklearn.metrics import confusion_matrix
    from sklearn.metrics import classification_report
    cm = confusion_matrix(y_test, ypre_mnb)
    cr = classification_report(y_test, ypre_mnb)
    print("混淆矩阵:
    ", cm)
    print("分类报告:", cr)
    print("模型准确率:", (cm[0][0]+cm[1][1])/np.sum(cm))
    

     

     

     混淆矩阵:

    TP(True Positive):将正类预测为正类数,真实为0,预测也为0

    FN(False Negative):将正类预测为负类数,真实为0,预测为1

    FP(False Positive):将负类预测为正类数, 真实为1,预测为0

    TN(True Negative):将负类预测为负类数,真实为1,预测也为1

     准确率:对于给定的测试数据集,分类器正确分类的样本数与总样本数之比。(TP + TN) / 总样本

    精确率:针对预测结果,在被所有预测为正的样本中实际为正样本的概率。TP / (TP + FP)

    召回率:在实际为正的样本中被预测为正样本的概率。TP / (TP + FN)

    F值:同时考虑精确率和召回率,让两者同时达到最高,取得平衡。F值=正确率 * 召回率  * 2 / (正确率 + 召回率 )

    6.比较与总结

    如果用CountVectorizer进行文本特征生成,与TfidfVectorizer相比,效果如何?

  • 相关阅读:
    Ruby入门——简介&基本概述
    Ruby入门——数组
    测试之路——现阶段&下一阶段
    Ruby入门——环境准备
    Ruby入门——哈希表
    Linux常用命令<按字母排序...>之D,E,F
    多态界面的子控件控制
    随笔
    多态界面的数据显示
    app开发快速理解——webview网页显示
  • 原文地址:https://www.cnblogs.com/lywkkk/p/12970066.html
Copyright © 2020-2023  润新知