网络诈骗分类模型的搭建

import matplotlib.pyplot as plt  
import numpy as np  
import pandas as pd 
import re
import jieba
import jieba.analyse as analyse 
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer  
from keras.models import Sequential  
from keras.layers import Dense,Flatten 
from keras.layers import Embedding

data = pd.read_table('/home/jovyan/data_practice/data/text/data.txt',encoding='UTF-8') #读取txt文件
data.tail() #查看数据

data = data.dropna() #删除缺失值
data.isnull().sum() #检查是否删干净

#定义删除字母,数字,汉字以外的所有符号的函数
def remove_punctuation(line):
    line = str(line) #转化为字符型
    if line.strip()=='':
        return ''
    rule = re.compile(u"[^a-zA-Z0-9\u4E00-\u9FA5]") #匹配其他字符
    line = rule.sub('',line) #将匹配到的字符替换为空
    return line

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

#加载停用词
stopwords = stopwordslist('/home/jovyan/data_practice/data/text/stopwords.txt')

data['content_clean'] = data['content'].apply(remove_punctuation) #对content列调用定义的remove_punctuation函数

#将删除掉不需要字符后的内容进行分词,并过滤停用词,停用词是在语言处理中不需要的语气词,符号等
data['cut_content'] = data['content_clean'].apply(lambda x: " ".join([w for w in list(jieba.cut(x)) if w not in stopwords])) #去除停用词

# 设置最频繁使用的50000个词
max_words = 2000 #50000
# 每条cut_review最大的长度
max_len = 150 #250
# 设置Embeddingceng层的维度
embedding_dim = 200
 
tokenizer = Tokenizer(num_words=max_words) #分词,即文本拆分为标记的过程
tokenizer.fit_on_texts(data['cut_content'].values) #用以训练的文本列表
word_index = tokenizer.word_index #将单词(字符串)映射为它们的排名或者索引
print('共有 %s 个不相同的词语.' % len(word_index))

from tensorflow.keras.preprocessing import sequence

X = tokenizer.texts_to_sequences(data['cut_content'].values) #
#填充X,让X的各个列的长度统一

X = sequence.pad_sequences(X, maxlen=max_len) #截取为相同长度的序列
 
#多类标签的onehot展开
Y = pd.get_dummies(data['label']).values #对标签进行独热编码category
print(X.shape)
print(Y.shape)

#拆分数据集,取80%留作训练和测试,20%用作验证
X_train = X[:int(len(X)*0.8)]
X_test = X[int(len(X)*0.8):]
Y_train = Y[:int(len(Y)*0.8)]
Y_test = Y[int(len(Y)*0.8):]
 

from keras.layers import Dropout, Dense, LSTM,GRU, SpatialDropout1D#, sparse_categorical_crossentropy
#定义模型
#神经网络非常容易过拟合,可以通过减少层数,减少神经元个数等方法调节模型
model = Sequential() #设置神经网络序列
model.add(Embedding(input_dim=max_words, output_dim=embedding_dim)) #embedding层,设置输入输出维度
model.add(SpatialDropout1D(0.5))
model.add(GRU(100, dropout=0.5, recurrent_dropout=0.3, return_sequences=True)) #GRU层,丢弃30%。若后面还需要接GRU层,则return_sequences=True
model.add(GRU(50, dropout=0.5, recurrent_dropout=0.3)) #GRU层,丢弃30%
model.add(Dense(9, activation='softmax'))

#配置模型
model.compile(loss='categorical_crossentropy', #损失函数
              optimizer='RMSProp', #优化器
              metrics=['accuracy'] #评估指标
             )

#导入
from keras.callbacks import EarlyStopping
monitor = EarlyStopping(monitor='val_acc', min_delta=0.1, patience=4, verbose=1, mode='auto')

epochs = 10  #5
batch_size = 400 #64
#训练模型
history = model.fit(X_train, #训练集
                    Y_train, #标签
                    epochs=100 , #训练轮数
                    batch_size=20, #每次训练抽取样本数
#                    callbacks = [monitor],
                    validation_split=0.5, #测试集比例
                    #validation_data=(X_test,Y_test) #测试集
                   )

model.summary() #模型结构
 

#绘制损失值和准确率曲线
import matplotlib.pyplot as plt  
plt.title('Loss')
plt.plot(history.history['loss'], label='train') #训练集损失
plt.plot(history.history['val_loss'], label='test') #测试集损失
plt.legend()
plt.show()

plt.title('Accuracy')
plt.plot(history.history['accuracy'], label='train') #训练集准确率
plt.plot(history.history['val_accuracy'], label='test') #测试集准确率
plt.legend()
plt.show()

#loss acc
model.evaluate(X_test,Y_test) #验证集评估

#保存模型  
#from keras.utils import plot_model  

model.save('model_GRU.h5')  #  生成模型文件 'my_model.h5'

#加载模型 
from keras.models import load_model 

model2 = load_model('model_GRU.h5') #加载储存的模型

#验证集标签预测
y_pred = model2.predict(X_test) #对验证集进行预测,预测结果为概率
y_pred = y_pred.argmax(axis = 1) #每行最大值的索引,即概率最大的索引也是标签
y_pred

Y_test.argmax(axis=1)

import seaborn as sns
from sklearn.metrics import  confusion_matrix
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号

conf_mat = confusion_matrix(Y_test.argmax(axis=1) , y_pred) #混淆矩阵
fig = plt.figure(figsize=(10,8)) #设置图像大小
sns.heatmap(conf_mat, annot=True, fmt='d') #绘制热度图
plt.ylabel('实际结果',fontsize=18)
plt.xlabel('预测结果',fontsize=18)
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值