基于中文垃圾短信数据集的经典文本分类算法实现

news2024/9/27 23:30:22

垃圾短信的泛滥给人们的日常生活带来了严重干扰,其中诈骗短信更是威胁到人们的信息与财产安全。因此,研究如何构建一种自动拦截过滤垃圾短信的机制有较强的实际应用价值。本文基于中文垃圾短信数据集,分别对比了朴素贝叶斯、逻辑回归、随机森林、SVM、LSTM、BiLSTM、BERT七种文本分类算法的垃圾短信分类效果。

1. 数据集设置与分析

统计发现,给定数据集包含正常短信679,365条,垃圾短信75,478条,垃圾短信数量约占短信总数的10%。将数据集按7:3的比例随机拆分为训练集与测试集。训练集与测试集的数据分布如下表所示:

类别训练集测试集
正常短信(正类)475,560203,805
垃圾短信(负类)52,83022,648
总计528,390226,453

另外,绘制训练集中正常短信与垃圾短信的词云图,可以对正常短信与垃圾短信的文本特征有较为直观的认识。从正常短信出现频率最高的前500词中随机选取的200个词的词云图如下图所示:

正常短信的词云图

从垃圾短信出现频率最高的前500词中随机选取的200个词的词云图如下图所示:

垃圾短信的词云图

可以发现:正常短信和垃圾短信在频繁词项上的区别是比较明显的。正常短信多与人们的日常生活相关,包含个人情感(如:“哈哈哈”、“宝宝”)、时事新闻(如:“记者”、“发布”)、衣食住行(如:“飞机”、“医疗”)等。而垃圾短信多与广告营销相关,包含促销力度(如“元起”、“钜”、“超值”、“最低”)、时间紧迫性(如:“赶紧”、“机会”)、促销手段(如:“抽奖”、“话费”)、时令节日(如:“妇女节”、“三月”)等。

2. 算法实现

基于上述数据集,本文从传统的机器学习方法中选择了朴素贝叶斯、逻辑回归、随机森林、SVM分类模型,从深度学习方法中选择了LSTM、BiLSTM以及预训练模型BERT进行对比实验。七种文本分类算法的优缺点总结如下表所示:

算法优点缺点
朴素贝叶斯有着坚实的数学理论基础;实现简单;学习与预测的效率都较高。实际往往不能满足特征条件独立性,在特征之间的相关性较大时分类效果不好;预设的先验概率分布的影响分类效果;在类别不平衡的数据上表现不佳。
逻辑回归实现简单;训练速度快。对于非线性的样本数据难以建模拟合;在特征空间很大时,性能不好;临界值不易确定,容易欠拟合。
随机森林训练可以高度并行化,在大数据集上训练速度有优势;能够处理高维度数据;能给出各个特征属性对输出的重要性评分。在噪声较大的情况下容易发生过拟合。
SVM可以处理线性与非线性的数据;具有较良好的泛化推广能力。参数调节与核函数选择较多地依赖于经验,具有一定的随意性。
LSTM结合词序信息。只能结合正向的词序信息。
BiLSTM结合上下文信息。模型收敛需要较长的训练时间。
BERT捕捉上下文信息的能力更强。预训练的[MASK]标记造成预训练与微调阶段的不匹配,影响模型效果;模型收敛需要更多时间。

下面依次介绍各文本分类算法的实现细节。

2.1 朴素贝叶斯

首先使用结巴分词工具将短信文本分词,去除停用词;然后抽取unigram和bigram特征,使用TF-IDF编码将分词后的短信文本向量化;最后训练朴素贝叶斯分类器。模型使用scikit-learn中的MultinomialNB,参数使用默认参数。其中,假设特征的先验概率分布为多项式分布,采用拉普拉斯平滑,所有的样本类别输出都有相同的类别先验概率。

代码如下:

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
import jieba
import re
from time import time
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.metrics import classification_report
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

#读取停用词列表
def stopwordslist(filepath):  
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]  
    return stopwords  

if __name__ == '__main__':
    #读取训练集数据
    print("Loading train dataset ...")
    t = time()
    train_data = pd.read_csv('train.csv', names=['labels', 'text'], sep='\t')
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    #读取测试集数据
    print("Loading test dataset ...")
    t = time()
    test_data = pd.read_csv('test.csv', names=['labels', 'text'], sep='\t')
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Total number of labeled documents(train): %d ." % len(train_data))
    print("Total number of labeled documents(test): %d ." % len(test_data))
 
    X_train = train_data['text']
    X_test = test_data['text']

    y_train  = train_data['labels']
    y_test = test_data['labels']
    
    #计算训练集中每个类别的标注数量
    d = {'labels':train_data['labels'].value_counts().index, 'count': train_data['labels'].value_counts()}
    df_label = pd.DataFrame(data=d).reset_index(drop=True)
    print(df_label)
    
    #加载停用词
    print("Loading stopwords ...")
    t = time()
    stopwords = stopwordslist("stopwords.txt")
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    #分词,并过滤停用词
    print("Starting word segmentation on train dataset...")
    t = time()
    X_train = X_train.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Starting word segmentation on test dataset...")
    t = time()
    X_test = X_test.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    #生成TF-IDF词向量
    print("Vectorizing train dataset...")
    t = time()
    tfidf = TfidfVectorizer(norm='l2', ngram_range=(1, 2))
    X_train = tfidf.fit_transform(X_train)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Vectorizing test dataset...")
    t = time()
    X_test = tfidf.transform(X_test)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    print(X_train.shape)
    print(X_test.shape)
    print('-----------------------------')
    print(X_train)
    print('-----------------------------')
    print(X_test)

    #训练模型
    print("Training model...")
    t = time()
    model = MultinomialNB()
    model.fit(X_train, y_train)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Predicting test dataset...")
    t = time()
    y_pred = model.predict(X_test)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))

    #生成混淆矩阵
    conf_mat = confusion_matrix(y_test, y_pred)
    print(conf_mat)

    print('accuracy %s' % accuracy_score(y_pred, y_test))
    print(classification_report(y_test, y_pred, digits=4))

2.2 逻辑回归

文本向量化方式与朴素贝叶斯相同。模型使用scikit-learn中的LogisticRegression,参数使用默认参数。其中,惩罚系数设置为1,正则化参数使用L2正则化,终止迭代的阈值为0.0001。

代码如下:

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
import jieba
import re
from time import time
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.metrics import classification_report
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

#读取停用词列表
def stopwordslist(filepath):  
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]  
    return stopwords  

if __name__ == '__main__':
    #读取训练集数据
    print("Loading train dataset ...")
    t = time()
    train_data = pd.read_csv('train.csv', names=['labels', 'text'], sep='\t')
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    #读取测试集数据
    print("Loading test dataset ...")
    t = time()
    test_data = pd.read_csv('test.csv', names=['labels', 'text'], sep='\t')
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Total number of labeled documents(train): %d ." % len(train_data))
    print("Total number of labeled documents(test): %d ." % len(test_data))
 
    X_train = train_data['text']
    X_test = test_data['text']

    y_train  = train_data['labels']
    y_test = test_data['labels']
    
    #计算训练集中每个类别的标注数量
    d = {'labels':train_data['labels'].value_counts().index, 'count': train_data['labels'].value_counts()}
    df_label = pd.DataFrame(data=d).reset_index(drop=True)
    print(df_label)
    
    #加载停用词
    print("Loading stopwords ...")
    t = time()
    stopwords = stopwordslist("stopwords.txt")
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    #分词,并过滤停用词
    print("Starting word segmentation on train dataset...")
    t = time()
    X_train = X_train.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Starting word segmentation on test dataset...")
    t = time()
    X_test = X_test.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    #生成TF-IDF词向量
    print("Vectorizing train dataset...")
    t = time()
    tfidf = TfidfVectorizer(norm='l2', ngram_range=(1, 2))
    X_train = tfidf.fit_transform(X_train)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Vectorizing test dataset...")
    t = time()
    X_test = tfidf.transform(X_test)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    print(X_train.shape)
    print(X_test.shape)
    print('-----------------------------')
    print(X_train)
    print('-----------------------------')
    print(X_test)

    #训练模型
    print("Training model...")
    t = time()
    model = LogisticRegression(random_state=0)
    model.fit(X_train, y_train)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Predicting test dataset...")
    t = time()
    y_pred = model.predict(X_test)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))

    #生成混淆矩阵
    conf_mat = confusion_matrix(y_test, y_pred)
    print(conf_mat)

    print('accuracy %s' % accuracy_score(y_pred, y_test))
    print(classification_report(y_test, y_pred, digits=4))

2.3 随机森林

文本向量化方式与朴素贝叶斯相同。模型使用scikit-learn中的RandomForestClassifier,参数使用默认参数。其中,决策树的最大个数为100,不采用袋外样本来评估模型的好坏,CART树做划分时对特征的评价标准为基尼系数。

代码如下:

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
import jieba
import re
from time import time
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.metrics import classification_report
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

#读取停用词列表
def stopwordslist(filepath):  
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]  
    return stopwords  

if __name__ == '__main__':
    #读取训练集数据
    print("Loading train dataset ...")
    t = time()
    train_data = pd.read_csv('train.csv', names=['labels', 'text'], sep='\t')
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    #读取测试集数据
    print("Loading test dataset ...")
    t = time()
    test_data = pd.read_csv('test.csv', names=['labels', 'text'], sep='\t')
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Total number of labeled documents(train): %d ." % len(train_data))
    print("Total number of labeled documents(test): %d ." % len(test_data))
 
    X_train = train_data['text']
    X_test = test_data['text']

    y_train  = train_data['labels']
    y_test = test_data['labels']
    
    #计算训练集中每个类别的标注数量
    d = {'labels':train_data['labels'].value_counts().index, 'count': train_data['labels'].value_counts()}
    df_label = pd.DataFrame(data=d).reset_index(drop=True)
    print(df_label)
    
    #加载停用词
    print("Loading stopwords ...")
    t = time()
    stopwords = stopwordslist("stopwords.txt")
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    #分词,并过滤停用词
    print("Starting word segmentation on train dataset...")
    t = time()
    X_train = X_train.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Starting word segmentation on test dataset...")
    t = time()
    X_test = X_test.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    #生成TF-IDF词向量
    print("Vectorizing train dataset...")
    t = time()
    tfidf = TfidfVectorizer(norm='l2', ngram_range=(1, 2))
    X_train = tfidf.fit_transform(X_train)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Vectorizing test dataset...")
    t = time()
    X_test = tfidf.transform(X_test)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    print(X_train.shape)
    print(X_test.shape)
    print('-----------------------------')
    print(X_train)
    print('-----------------------------')
    print(X_test)

    #训练模型
    print("Training model...")
    t = time()
    model = RandomForestClassifier()
    model.fit(X_train, y_train)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Predicting test dataset...")
    t = time()
    y_pred = model.predict(X_test)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))

    #生成混淆矩阵
    conf_mat = confusion_matrix(y_test, y_pred)
    print(conf_mat)

    print('accuracy %s' % accuracy_score(y_pred, y_test))
    print(classification_report(y_test, y_pred, digits=4))

2.4 SVM

文本向量化方式与朴素贝叶斯相同。模型使用scikit-learn中的LinearSVC,参数使用默认参数。其中,SVM的核函数选用线性核函数,惩罚系数设置为1,正则化参数使用L2正则化,采用对偶形式优化算法,最大迭代次数为1000,终止迭代的阈值为0.0001。

代码如下:

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
import jieba
import re
from time import time
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.metrics import classification_report
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

#读取停用词列表
def stopwordslist(filepath):  
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]  
    return stopwords  

if __name__ == '__main__':
    #读取训练集数据
    print("Loading train dataset ...")
    t = time()
    train_data = pd.read_csv('train.csv', names=['labels', 'text'], sep='\t')
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    #读取测试集数据
    print("Loading test dataset ...")
    t = time()
    test_data = pd.read_csv('test.csv', names=['labels', 'text'], sep='\t')
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Total number of labeled documents(train): %d ." % len(train_data))
    print("Total number of labeled documents(test): %d ." % len(test_data))
 
    X_train = train_data['text']
    X_test = test_data['text']

    y_train  = train_data['labels']
    y_test = test_data['labels']
    
    #计算训练集中每个类别的标注数量
    d = {'labels':train_data['labels'].value_counts().index, 'count': train_data['labels'].value_counts()}
    df_label = pd.DataFrame(data=d).reset_index(drop=True)
    print(df_label)
    
    #加载停用词
    print("Loading stopwords ...")
    t = time()
    stopwords = stopwordslist("stopwords.txt")
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    #分词,并过滤停用词
    print("Starting word segmentation on train dataset...")
    t = time()
    X_train = X_train.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Starting word segmentation on test dataset...")
    t = time()
    X_test = X_test.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    #生成TF-IDF词向量
    print("Vectorizing train dataset...")
    t = time()
    tfidf = TfidfVectorizer(norm='l2', ngram_range=(1, 2))
    X_train = tfidf.fit_transform(X_train)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Vectorizing test dataset...")
    t = time()
    X_test = tfidf.transform(X_test)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    print(X_train.shape)
    print(X_test.shape)
    print('-----------------------------')
    print(X_train)
    print('-----------------------------')
    print(X_test)

    #训练模型
    print("Training model...")
    t = time()
    model = LinearSVC()
    model.fit(X_train, y_train)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    print("Predicting test dataset...")
    t = time()
    y_pred = model.predict(X_test)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))

    #生成混淆矩阵
    conf_mat = confusion_matrix(y_test, y_pred)
    print(conf_mat)

    print('accuracy %s' % accuracy_score(y_pred, y_test))
    print(classification_report(y_test, y_pred, digits=4))

2.5 LSTM

首先使用结巴分词工具将短信文本分词,去除停用词;然后设置保留的最大词数为最频繁出现的前50,000,序列的最大长度为100,使用200维的腾讯词向量将所有的论文标题转化为词嵌入层的权重矩阵。然后对词嵌入层的输出执行SpatialDropout1D,以0.2的比例随机将1D特征映射置零。之后输入到LSTM层,LSTM层的神经元个数为300。最后通过一个全连接层,利用softmax函数输出分类。损失函数使用交叉熵损失函数,设置batch大小为64,训练10个epoch。

代码如下:

# -*- coding: utf-8 -*-

import pandas as pd
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import jieba
import re
from time import time
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.metrics import classification_report
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from keras.utils.np_utils import to_categorical
from keras.callbacks import EarlyStopping
from keras.layers import Dropout
from gensim.models import KeyedVectors
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

#读取停用词列表
def stopwordslist(filepath):  
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]  
    return stopwords  

if __name__ == '__main__':
    #读取训练集数据
    train_data = pd.read_csv('train.csv', names=['labels', 'text'], sep='\t')
    #读取测试集数据
    test_data = pd.read_csv('test.csv', names=['labels', 'text'], sep='\t')
    
    print("Total number of labeled documents(train): %d ." % len(train_data))
    print("Total number of labeled documents(test): %d ." % len(test_data))
    
    X_train = train_data['text']
    X_test = test_data['text']

    y_train  = train_data['labels']
    y_test = test_data['labels']
    
    #计算训练集中每个类别的标注数量
    d = {'labels':train_data['labels'].value_counts().index, 'count': train_data['labels'].value_counts()}
    df_label = pd.DataFrame(data=d).reset_index(drop=True)
    print(df_label)
    #加载停用词
    stopwords = stopwordslist("stopwords.txt")
    #分词,并过滤停用词
    X_train = X_train.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    X_test = X_test.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    
    # 设置最频繁使用的50000个词(在texts_to_matrix是会取前MAX_NB_WORDS,会取前MAX_NB_WORDS列)
    MAX_NB_WORDS = 50000
    # 每个标题最大的长度
    MAX_SEQUENCE_LENGTH = 100
    # 设置Embeddingceng层的维度
    EMBEDDING_DIM = 200

    tokenizer = Tokenizer(num_words=MAX_NB_WORDS, filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~', lower=True)
    tokenizer.fit_on_texts(X_train)
    word_index = tokenizer.word_index
    print('There are %s different words.' % len(word_index))
    
    X_train = tokenizer.texts_to_sequences(X_train)
    X_test = tokenizer.texts_to_sequences(X_test)
    
    #填充X,让X的各个列的长度统一
    X_train = pad_sequences(X_train, maxlen=MAX_SEQUENCE_LENGTH)
    X_test = pad_sequences(X_test, maxlen=MAX_SEQUENCE_LENGTH)
    #多类标签的onehot展开
    y_train = pd.get_dummies(y_train).values
    y_test = pd.get_dummies(y_test).values
    
    print(X_train.shape,y_train.shape)
    print(X_test.shape,y_test.shape)
    
    #加载tencent词向量
    wv_from_text = KeyedVectors.load_word2vec_format('tencent.txt', binary=False, unicode_errors='ignore')
    embedding_matrix = np.zeros((MAX_NB_WORDS, EMBEDDING_DIM))
    for word, i in word_index.items():
        if i > MAX_NB_WORDS:
            continue
        try:
            embedding_matrix[i] = wv_from_text.wv.get_vector(word)
        except:
            continue
    del wv_from_text
    #定义模型
    print("Training model...")
    t = time()
    model = Sequential()
    model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X_train.shape[1], weights = [embedding_matrix], trainable = False))
    model.add(SpatialDropout1D(0.2))
    model.add(LSTM(300, dropout=0.2, recurrent_dropout=0.2))
    model.add(Dense(2, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())
    
    epochs = 10
    batch_size = 64

    history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size,validation_split=0.1,
                    callbacks=[EarlyStopping(monitor='val_loss', patience=3, min_delta=0.0001)])
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    
    accr = model.evaluate(X_test,y_test)
    print('Test set\n  Loss: {:0.3f}\n  Accuracy: {:0.3f}'.format(accr[0],accr[1]))
    
    print("Predicting test dataset...")
    t = time()
    y_pred = model.predict(X_test)
    print("Done in {0} seconds\n".format(round(time() - t, 2)))
    y_pred = y_pred.argmax(axis = 1)
    y_test = y_test.argmax(axis = 1)


    #生成混淆矩阵
    conf_mat = confusion_matrix(y_test, y_pred)
    print(conf_mat)

    print('accuracy %s' % accuracy_score(y_pred, y_test))
    print(classification_report(y_test, y_pred, digits=4))

2.6 BiLSTM

与LSTM的参数设置基本一致,只是将单向的LSTM改为双向的,训练60个epoch。

代码如下:

# -*- coding: utf-8 -*-

import pandas as pd
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import jieba
import re
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.metrics import classification_report
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D, Bidirectional
from keras.utils.np_utils import to_categorical
from keras.callbacks import EarlyStopping
from keras.layers import Dropout
from gensim.models import KeyedVectors
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

#读取停用词列表
def stopwordslist(filepath):  
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]  
    return stopwords  

if __name__ == '__main__':
    #读取训练集数据
    train_data = pd.read_csv('train.csv', names=['labels', 'text'], sep='\t')
    #读取测试集数据
    test_data = pd.read_csv('test.csv', names=['labels', 'text'], sep='\t')
    
    print("Total number of labeled documents(train): %d ." % len(train_data))
    print("Total number of labeled documents(test): %d ." % len(test_data))
    
    X_train = train_data['text']
    X_test = test_data['text']

    y_train  = train_data['labels']
    y_test = test_data['labels']
    
    #计算训练集中每个类别的标注数量
    d = {'labels':train_data['labels'].value_counts().index, 'count': train_data['labels'].value_counts()}
    df_label = pd.DataFrame(data=d).reset_index(drop=True)
    print(df_label)
    #加载停用词
    stopwords = stopwordslist("stopwords.txt")
    #分词,并过滤停用词
    X_train = X_train.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    X_test = X_test.apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords]))
    
    # 设置最频繁使用的50000个词(在texts_to_matrix是会取前MAX_NB_WORDS,会取前MAX_NB_WORDS列)
    MAX_NB_WORDS = 50000
    # 每个标题最大的长度
    MAX_SEQUENCE_LENGTH = 100
    # 设置Embeddingceng层的维度
    EMBEDDING_DIM = 200

    tokenizer = Tokenizer(num_words=MAX_NB_WORDS, filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~', lower=True)
    tokenizer.fit_on_texts(X_train)
    word_index = tokenizer.word_index
    print('There are %s different words.' % len(word_index))
    
    X_train = tokenizer.texts_to_sequences(X_train)
    X_test = tokenizer.texts_to_sequences(X_test)
    
    #填充X,让X的各个列的长度统一
    X_train = pad_sequences(X_train, maxlen=MAX_SEQUENCE_LENGTH)
    X_test = pad_sequences(X_test, maxlen=MAX_SEQUENCE_LENGTH)
    #多类标签的onehot展开
    y_train = pd.get_dummies(y_train).values
    y_test = pd.get_dummies(y_test).values
    
    print(X_train.shape,y_train.shape)
    print(X_test.shape,y_test.shape)
    
    #加载tencent词向量
    wv_from_text = KeyedVectors.load_word2vec_format('tencent.txt', binary=False, unicode_errors='ignore')
    embedding_matrix = np.zeros((MAX_NB_WORDS, EMBEDDING_DIM))
    for word, i in word_index.items():
        if i > MAX_NB_WORDS:
            continue
        try:
            embedding_matrix[i] = wv_from_text.wv.get_vector(word)
        except:
            continue
    del wv_from_text
    #定义模型
    model = Sequential()
    model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X_train.shape[1], weights = [embedding_matrix], trainable = False))
    model.add(SpatialDropout1D(0.2))
    model.add(Bidirectional(LSTM(300)))
    model.add(Dense(2, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())
    
    epochs = 10
    batch_size = 64

    history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size,validation_split=0.1,
                    callbacks=[EarlyStopping(monitor='val_loss', patience=3, min_delta=0.0001)])
                    
    accr = model.evaluate(X_test,y_test)
    print('Test set\n  Loss: {:0.3f}\n  Accuracy: {:0.3f}'.format(accr[0],accr[1]))
    
    y_pred = model.predict(X_test)
    y_pred = y_pred.argmax(axis = 1)
    y_test = y_test.argmax(axis = 1)


    #生成混淆矩阵
    conf_mat = confusion_matrix(y_test, y_pred)
    print(conf_mat)

    print('accuracy %s' % accuracy_score(y_pred, y_test))
    print(classification_report(y_test, y_pred, digits=4))

2.7 BERT

使用BERT-Base-Chinese预训练模型在训练集上进行微调,设置学习率为1e-5,序列的最大长度为128,batch大小设置为8,训练2个epoch。

代码如下:

import pandas as pd
from simpletransformers.model import TransformerModel
from sklearn.metrics import f1_score, accuracy_score

def f1_multiclass(labels, preds):
      return f1_score(labels, preds, average='micro')

if __name__ == '__main__':
    #读取训练集数据
    train_data = pd.read_csv('train.csv', names=['labels', 'text'], sep='\t')
    #读取测试集数据
    test_data = pd.read_csv('test.csv', names=['labels', 'text'], sep='\t')
    
    print("Total number of labeled papers(train): %d ." % len(train_data))
    print("Total number of labeled papers(test): %d ." % len(test_data))
    #构建模型
    #bert-base-chinese
    model = TransformerModel('bert', 'bert-base-chinese', num_labels=2, args={'learning_rate':1e-5, 'num_train_epochs': 2, 
'reprocess_input_data': True, 'overwrite_output_dir': True, 'fp16': False})
    #bert-base-multilingual 前两个参数换成: 'bert', 'bert-base-multilingual-cased'
    #roberta 前两个参数换成: 'roberta', 'roberta-base'
    #xlmroberta 前两个参数换成: 'xlmroberta', 'xlm-roberta-base'

    #模型训练
    model.train_model(train_data)
    result, model_outputs, wrong_predictions = model.eval_model(test_data, f1=f1_multiclass, acc=accuracy_score)

3. 结果对比

为定量分析算法效果,假设正常短信为正样本,数量为P(Positive);垃圾短信为负样本,数量为N(Negative);文本分类算法正确分类样本数为T(True);错误分类样本数为F(False)。因此,真正(True positive, TP)表示正常短信被正确分类的数量;假正(False positive, FP)表示垃圾短信被误认为正常短信的数量;真负(True negative, TN)表示垃圾短信被正确分类的数量;假负(False negative, FN)表示正常短信被误认为垃圾短信的数量。在此基础上,实验中使用如下五个评估指标:

(1)精确率加权平均(Precision-weighted),计算如下:
Precision-weighted = ( P r e c i s i o n P ∗ P + P r e c i s i o n N ∗ N ) / ( P + N ) =(Precision_P*P+Precision_N*N)/(P+N) =(PrecisionPP+PrecisionNN)/(P+N)
其中 P r e c i s i o n P = T P / ( T P + F P ) Precision_P=TP/(TP+FP) PrecisionP=TP/(TP+FP) P r e c i s i o n N = T N / ( T N + F N ) Precision_N=TN/(TN+FN) PrecisionN=TN/(TN+FN)

(2)召回率加权平均(Recall-weighted),计算如下:
Recall-weighted = ( R e c a l l P ∗ P + R e c a l l N ∗ N ) / ( P + N ) =(Recall_P*P+Recall_N*N)/(P+N) =(RecallPP+RecallNN)/(P+N)
其中 R e c a l l P = T P / ( T P + F N ) Recall_P=TP/(TP+FN) RecallP=TP/(TP+FN) R e c a l l N = T N / ( T N + F P ) Recall_N=TN/(TN+FP) RecallN=TN/(TN+FP)

(3)F1值加权平均(F1-score-weighted),计算如下:
F1-score-weighted = ( F 1 P ∗ P + F 1 N ∗ N ) / ( P + N ) =(F1_P*P+F1_N*N)/(P+N) =(F1PP+F1NN)/(P+N)
其中,
F 1 P = 2 ∗ P r e c i s i o n P ∗ R e c a l l P / ( P r e c i s i o n P + R e c a l l P ) F1_P=2*Precision_P*Recall_P/(Precision_P+Recall_P) F1P=2PrecisionPRecallP/(PrecisionP+RecallP)
F 1 N = 2 ∗ P r e c i s i o n N ∗ R e c a l l N / ( P r e c i s i o n N + R e c a l l N ) F1_N=2*Precision_N*Recall_N/(Precision_N+Recall_N) F1N=2PrecisionNRecallN/(PrecisionN+RecallN)

(4)假负率(False negative rate, FNR),计算如下:
FNR = F N / ( T P + F N ) =FN/(TP+FN) =FN/(TP+FN),即被预测为垃圾短信的正常短信数量/正常短信实际的数量。

(5)真负率(True negative rate, TNR),计算如下:
TNR = T N / ( T N + F P ) =TN/(TN+FP) =TN/(TN+FP),即垃圾短信的正确识别数量/垃圾短信实际的数量,亦为垃圾短信的召回率。

针对垃圾短信分类的场景,我们希望一个好的文本分类算法使得精确率加权平均、召回率加权平均、F1值加权平均、真负率要尽可能的高,即垃圾短信的正确拦截率高;同时,必须保证假负率尽可能的低,即正常短信被误认为是垃圾短信的比率低。这是因为:对于用户来说,“正常短信被误认为是垃圾短信”比“垃圾短信被误认为是正常短信”更不可容忍;对于运营商来说,宁可放过部分垃圾短信,也要保障用户的正常使用。

模型精确率加权平均召回率加权平均F1值加权平均假负率真负率
朴素贝叶斯0.97640.97610.97480.00100.7700
逻辑回归0.98860.98870.98870.00610.9414
随机森林0.98090.98080.98000.00120.8181
SVM0.99250.99240.99240.00520.9713
LSTM0.99630.99630.99630.00150.9771
BiLSTM0.99640.99640.99640.00090.9720
BERT0.99910.99910.99910.00020.9926

上表给出了七种文本分类算法的实验结果。可以发现:

第一,BERT具有最高的F1值加权平均和真负率,同时具有最低的假负率,垃圾短信的过滤效果最好。分析原因是BERT经过大规模通用语料上的预训练,对文本特征的捕捉能力更强。

第二,BiLSTM与LSTM的F1值加权平均接近,因此模型整体的分类效果接近,但二者的假负率与真负率存在差异:从假负率来看,BiLSTM的正常短信错误识别率更低;从真负率来看,LSTM的垃圾短信正确拦截率更高。

第三,SVM与逻辑回归的F1值加权平均比较接近,但相较而言,SVM的效果更好一些:SVM在精确率加权平均、召回率加权平均、F1值加权平均、假负率、真负率这五个指标上均比逻辑回归略胜一筹。分析原因可能是:SVM仅考虑支持向量,也就是和分类最相关的少数样本点;而逻辑回归考虑所有样本点,因此逻辑回归对异常值与数据分布的不平衡更敏感,分类效果受到影响。

第四,朴素贝叶斯与随机森林在F1值加权平均和真负率上表现较差。分析原因可能是:正负例数据的不平衡对二者的模型效果造成影响,模型在正常短信数据上有些过拟合。此外,朴素贝叶斯的条件独立性假设在实际中不满足,这在一定程度上影响分类效果。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1408103.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

数据结构——排序算法代码实现、包含注释易理解可运行(C语言,持续更新中~~)

一、排序 1.1 直接插入排序 1.1.1 思想 插入排序的核心操作是将待排序元素与已排序序列中的元素进行比较&#xff0c;并找到合适的位置进行插入。这个过程可以通过不断地将元素向右移动来实现。 插入排序的优势在于对于小规模或基本有序的数组&#xff0c;它的性能非常好。…

【经验分享】豆瓣小组的文章/帖子怎么删除?

#豆瓣小组的文章/帖子怎么删除&#xff1f;# 第一步&#xff1a; 手机登录豆瓣app ↓ 点右下角“我” ↓ 然后在页面点击我的小组 ↓ 点我发布的 ↓ ↓ 再任意点开一个帖子 ↓ 在文章和帖子的右上角有一个笔状的图标&#xff0c;切记不是右上角的横三点… ↓ ↓ 最后点下边的…

odoo 一日一技 owl Registry示例 在用户菜单增加开发者模式开关

# 示例介绍 在Odoo中&#xff0c;开发者模式是一个非常有用的工具&#xff0c;它允许开发人员对系统进行调试。如果每次都要去设置中打开调试模式将非常麻烦&#xff0c;上篇文章讲述了如何使用 owl registry&#xff0c;这篇我们来进行实操。 本文将介绍如何在Odoo的用户菜单…

令人感动的创富故事编号001:27岁Python程序员年入$600万+

27岁Python程序员年入$600万 27岁的你&#xff0c;在做什么&#xff1f; 为家庭生计而努力搬砖&#xff0c;辛勤工作&#xff1f; 还是放弃挣扎&#xff0c;选择躺平呢&#xff1f; 当我们还在为未来道路感到困惑之际&#xff0c;年仅27岁的Reilly已经迈向了财富自由的大门…

Socket 文件描述符

文件描述符的作用是什么&#xff1f; 每一个进程都有一个数据结构 task_struct&#xff0c;该结构体里有一个指向「文件描述符数组」的成员指针。该数组里列出这个进程打开的所有文件的文件描述符。数组的下标是文件描述符&#xff0c;是一个整数&#xff0c;而数组的内容是一…

用VR技术让党建“活起来”,打造党建知识科普新体验

随着现在工作、生活的信息化、网络化持续加深&#xff0c;传统的党建科普对年轻党员的吸引力日益降低&#xff0c;不管是面授讲课还是实地观摩的方式&#xff0c;都会受到时间和空间上的限制。因此&#xff0c;VR数字党建的出现为党建知识科普提供了新的可能&#xff0c;VR党建…

STM32 USB CDC协议的应用与优化技巧

STM32微控制器提供了使用USB CDC&#xff08;Communications Device Class&#xff09;协议来实现虚拟串口通信的功能。USB CDC协议可以将STM32设备模拟为一个虚拟串口设备&#xff0c;并通过USB接口与计算机进行通信。在本文中&#xff0c;我们将介绍USB CDC协议的应用与优化技…

elment-plus如何引入scss文件实现自定义主题色

elment-plus如何引入scss文件实现自定义主题色&#xff01;如果您想修改elementPlus的默认主题色调&#xff0c;使用自定义的色调&#xff0c;可以考虑使用官方提供的解决办法。 第一步你需要在项目内安装sass插件包。 npm i sass -D 如图&#xff0c;安装完成后&#xff0c;你…

[pytorch入门] 6. 神经网络

基本介绍 torch.nn&#xff1a; Containers&#xff1a;基本骨架Convolution Layers&#xff1a; 卷积层Pooling layers&#xff1a;池化层Non-linear Activations (weighted sum, nonlinearity)&#xff1a;非线性激活Normalization Layers&#xff1a;正则化层 Container…

边缘计算及相关产品历史发展

边缘计算及相关产品历史发展 背景边缘计算的历史CDN&#xff08;Content Delivery Network&#xff09;Cloudlet雾计算MEC&#xff08;Multi-Access Edge Computing&#xff0c;MEC&#xff09; 边缘计算的现状云计算厂商硬件厂商软件基金会 背景 最近&#xff0c;公司部分业务…

基于springboot+vue的社区医院信息平台系统(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战 主要内容&#xff1a;毕业设计(Javaweb项目|小程序等)、简历模板、学习资料、面试题库、技术咨询 文末联系获取 研究背景…

阿赵UE学习笔记——解决UE资源不能正常显示缩略图的问题

阿赵UE学习笔记目录 大家好&#xff0c;我是阿赵。   这里分享一个虚幻引擎使用小技巧。在使用虚幻引擎的过程中&#xff0c;经常会遇到有些资源在重新打开项目的时候&#xff0c;会看不到缩略图&#xff0c;而是显示默认资源的图标&#xff1a; 这个时候&#xff0c;第一种…

应用app的服务器如何增加高并发

增强服务器的高并发能力是现代网络应用非常关键的需求。面对用户数量的不断增长和数据量的膨胀&#xff0c;服务器必须能够处理大量并发请求。以下是一些提高服务器高并发能力的常用方法和具体实施细节&#xff1a; 优化服务器和操作系统配置 服务器和操作系统的默认配置不一定…

快速上手的AI工具-文心一言绘画达人

前言 大家好&#xff0c;现在AI技术的发展&#xff0c;它已经渗透到我们生活的各个层面。对于普通人来说&#xff0c;理解并有效利用AI技术不仅能增强个人竞争力&#xff0c;还能在日常生活中带来便利。无论是提高工作效率&#xff0c;还是优化日常任务&#xff0c;AI工具都可…

【模拟通信】AM、FM等的调制解调

调制相关的概念 调制&#xff1a;控制载波的参数&#xff0c;使载波参数随调制信号的规律变化 已调信号&#xff1a;受调载波&#xff0c;含有调制信号的全部特征 调制的作用: 提高发射效率多路复用&#xff0c;提高信道利用率提高系统抗干扰能力 两种调制方式 线性调制&a…

网络协议与攻击模拟_08DHCP协议

技术学习要了解某项技术能干什么&#xff1f;它的详细内容&#xff1f;发展走向&#xff1f; 一、DHCP协议 1、DHCP基本概念 dhcp动态主机配置协议&#xff0c;广泛应用于局域网内部 主要是为客户机提供TCP/IP 参数&#xff08;IP地址、子网掩码、网关、DNS等&#xff09;…

STL第四讲

第四讲 万用Hash Function 左侧的是设计为类并重载调用运算符&#xff0c;右侧是一般函数的形势&#xff1b; 但是右侧形势在创建容器时更麻烦&#xff1b; 具体例子&#xff1a; 第三种形势&#xff1a;struct hash 偏特化形式 tuple 自C03引入&#xff1b; 关于源码解读的…

Linux服务器系统修改SSH端口教程

修改端口号是通过修改SSH的配置文件实现的&#xff0c;在服务器终端先激活root用户&#xff0c;然后输入&#xff1a; vim /etc/ssh/sshd_config找到#Port 22这个位置 键盘按i进入编辑模式 删除掉Port 22前面的#&#xff0c;然后键盘按一下回车键&#xff08;如果没有#可不必…

软件产品为什么要测试才能上线?测试可以发现所有bug吗?

在现如今信息时代&#xff0c;软件产品已经成为人们生活中不可或缺的一部分。无论是在工作中还是在娱乐休闲时&#xff0c;我们都需要依赖各种软件来完成各种任务。然而&#xff0c;你是否注意到了身边的软件产品都是经过严格的测试才能上线的呢?那么为什么软件产品必须要经过…

JS之歌词滚动案例

让我为大家带来一个歌词滚动的案例吧&#xff01; 详细的介绍都在代码块中 我很希望大家可以自己动手尝试一下&#xff0c;如果需要晴天的mp3音频文件可以私信我 上代码&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset&quo…