近期接手的一个项目就是深度学习文本分类,我选用的是keras深度学习框架,下面把处理过程给大家分享一下,首先是要加载数据,我的数据是在文档里面,首先读取csv文件选取字段。
def laod_csv():
print('正在加载数据...')
data = pd.read_csv(r'data\3_9.csv',encoding='gbk')
target_list = []
def func(f):
if f['小类'].values[0] not in target_list:
target_list.append(f['小类'].values[0])
f['数字小类类别'] = [target_list.index(f['小类'].values[0])] * len(f['小类'].values)
return f
data1 = data.groupby(['小类']).apply(func)
data1.sort_values(by='数字小类类别', inplace=True)
label = data1['数字小类类别'].values
target = []
for item in data1['反映内容'].values:
target.append(item.strip())
return target,label,target_list
之后配置网络结构
def build_netword(dict, catalogue=BINARY_FLAG, embedding_size=50, max_sequence_length=30):
model = krs.Sequential()
model.add(krs.layers.Embedding(len(dict.items()), embedding_size, input_length=max_sequence_length))
model.add(krs.layers.LSTM(256, dropout=0.5, recurrent_dropout=0.5)) #配置神经元个数以及dropout过拟合
model.add(krs.layers.Dense(97)) #最终类别有多少个
model.add(krs.layers.Activation("softmax")) #利用softmax激活函数
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"]) #配置损失函数,优化器,评估标准
return model
在多分类问题中我们都是用softmax激活函数,因为会对每一类都有一个预测概率,概率最大的一个即为最好的,在二分类中就用sigmoid激活函数,神经元个数也可以按照自己的模型进行调整,我最后个数为512个,越大的话拟合时间越久。
下面就是数据处理与训练:
# -*- coding: utf-8 -*-
# Created by Jinkey on 2018/1/4.
import tensorflow as tf
import jieba as jb
import numpy as np
import matplotlib.pyplot as plt
from keras.wrappers.scikit_learn import KerasClassifier
from keras.callbacks import TensorBoard
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from imblearn.over_sampling import SMOTE
import utils
import eda
import re
# titles = utils.load_data(catalogue=utils.MULTI_FLAG)
# target = utils.load_label(catalogue=utils.MULTI_FLAG)
a,b,target_list = utils.laod_csv()
#读取数据
with open('target_little.txt','r',encoding='gbk') as f:
titles = f.readlines()
with open('label_little.txt','r') as f:
label = f.readlines()
print('ok',len(titles),len(label))
#将label进行onehot编码
label = np.array(label)
encoder = utils.LabelEncoder()
encoder.fit(label)
encoded_target = encoder.transform(label)
label = utils.krs.utils.np_utils.to_categorical(encoded_target)
max_sequence_length = 30
embedding_size = 50
#去除无关词
def text_func(text):
t = text.replace('\n', '').lstrip('反映其是(保密)其在来电').replace('原编号','').replace('</s>','').replace('望', '').replace('请', '').replace('有关', '').replace('相关','').replace('部门', '').replace('帮助', '').replace('协调', '').replace('核实', '').replace('处理', '').replace('查处', '').replace('解答', '').replace('解释', '').replace('进行', '').replace('劝导', '').replace('教育', '').replace('能', '').replace('尽快','').replace('处理', '').replace('希望', '').replace('检测', '').replace('督促', '').replace('进行整改', '').replace(',', '').replace('。', '').replace(':', '').replace('调解', '').replace(' ', '').replace('(', '').replace(')', '').replace('“','').replace('”', '').replace('‘', '').replace('’', '').replace('、', '').replace('·', '').replace('下沙', '').replace('经济开发区','').replace('经济技术开发区', '').replace('告知会', '').replace('转告', '').replace('其表', '').replace('知晓', '').replace('调处', '')
return ''.join(re.findall('[\u4e00-\u9fa5]', t))
# 分词与去除停用词
def fenci_func(titles):
wos_list = []
with open('stop_word.txt','r',encoding='utf-8')as f:
word_list = f.readlines()
for items in titles:
wo_list = []
for item in jb.lcut(text_func(items)):
if item not in word_list:
wo_list.append(item)
wos_list.append(".".join(wo_list))
return wos_list
# word2vec 词袋化文本数据
vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_sequence_length, min_frequency=1)
text_processed = np.array(list(vocab_processor.fit_transform(fenci_func(titles))))
# 读取标签
dict = vocab_processor.vocabulary_._mapping
sorted_vocab = sorted(dict.items(), key = lambda x : x[1])
#过采样
# smote = SMOTE(ratio='auto',random_state=0,k_neighbors=2,m_neighbors=10,out_step=0.5,kind='regular',svm_estimator=None,n_jobs=1)
# text_processeds,labels = smote.fit_sample(text_processed,label)
# 配置网络结构
#有网格验证时
# model = KerasClassifier(build_fn=utils.build_netword,dict=dict, embedding_size=embedding_size, max_sequence_length=max_sequence_length, verbose=0)
#无网格验证时
model = utils.build_netword(, dict=dict, embedding_size=embedding_size, max_sequence_length=max_sequence_length)
#网格验证
# params = {"batch_size":[31,32,33],
# "epochs":[22,23,24]}
#
# clf = GridSearchCV(estimator=model,param_grid=params,n_jobs=1)
# grid_result = clf.fit(text_processed,label)
#
# print('Best: {} using {}'.format(grid_result.best_score_, grid_result.best_params_))
# means = grid_result.cv_results_['mean_test_score']
# stds = grid_result.cv_results_['std_test_score']
# params = grid_result.cv_results_['params']
#
# for mean, std, param in zip(means, stds, params):
# print("%f (%f) with: %r" % (mean, std, param))
#训练数据集打乱
per = np.random.permutation(text_processed.shape[0]) #打乱后的行号
text_processeds = text_processed[per, :] #获取打乱后的训练数据
labels = label[per]
#数据切分成训练集与测试集
X_train,X_test,Y_train,Y_test = train_test_split(text_processeds,labels,test_size=0.1)
# 训练模型
history = model.fit(X_train, Y_train, validation_split=0.1, batch_size=150, epochs=32, verbose=2)
# 绘制训练 & 验证的准确率值
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# 绘制训练 & 验证的损失值
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# 测试集计算准确率
score = model.evaluate(X_test,Y_test,verbose=0)
print('准确率为:',score)
# 保存模型
# model.save("text_class_end.h5")
# 加载预训练的模型
# model.load_weights("text_class_end.h5")
#
# # 预测样本
with open('testt.txt','r',encoding='utf-8') as f:
sen = f.readlines()
# sen_prosessed = np.array(list(vocab_processor.fit_transform(fenci_func(sen))))
# result = model.predict(sen_prosessed)
# for item in result:
# catalogue = list(item).index(max(item))
# sort_list = sorted(item,reverse=True)
# index1 = list(item).index(sort_list[0])
# index2 = list(item).index(sort_list[1])
# index3 = list(item).index(sort_list[2])
# print('catalogue',catalogue)
# print(sort_list[:3])
# print(target_list[index1],target_list[index2],target_list[index3])
处理过程首先将类别进行onehot编码,然后对文本数据进行分词去停用词与无用词,在进行词袋化,在此之前我已经对文本数据进行过一次处理,就是文本数据增强,在我的另一篇博客里,可以参考文本数据增强,之后就是模型训练,训练时我有用网格验证法来选择最优参数,但是时间太长了,最长的能训练一天,等不过来,所以建议一次不要设置太多的参数,模型训练时这四个参数validation_split=0.1, batch_size=150, epochs=32, verbose=2。validation_split是按多少比例分割训练集与验证集,这里其实就是网格验证,懂网格验证的应该知道,所以上面写的网格验证我训练时就用了一次之后在没用,知道有这个东西就行,batch_size是每次训练时选取多少数据,就是一批150条数据,epochs就是进行多少轮训练,verbose时显示不显示训练过程,为1时是显示,2是只显示每一批的loss及acc值,0是不显示。
后面也对训练过程中的loss值与acc值进行了画图,就可以很清楚的看到拟合情况。
模型训练完保存好之后,下次运行就不必运行fit代码,直接打开训练好的模型就行。
测试的时候用evaluate函数就可以了,出来的两个值一个是loss,一个就是准确率,
最后还可以进行预测,predict函数就可以,得出结果是一个列表,对应分到每一类的概率,你可以选择前几个或最大的,我选的是前三个。这是我做的所有事情。
最后我要在这跟大家讨论一个问题,就是模型在应用的时候,模型我是训练出来了,准确率有94%,还可以吧。问题是我现在有一条文本数据要判断其分类,按道理来说丢进predict进行了,但是文本数据要经过词向量化,但就是在这个词向量化的时候出现问题,因为一条数据进行词向量化是没有作用的,出来全部是0,多条的话是按照这几条进行词向量化的,在利用这些词向量判断结果很差,最后我想了想,找了一下word2vec原理,他是与你输入的文本数据有关,训练时是对训练集进行词向量化的,是在训练集中分词统计向量化的,而新来几条数据词向量化是对这些新的文本进行分词统计向量化的,所以这两者结果将会有很大的差异,导致分类结果很差,如果把新来的数据与训练集在一起训练一次的话,训练集词向量会变,这就要重新训练模型,这肯定不行,所以这就生成了我现在的问题,导致模型不能够应用起来。。。
(大佬们有没有懂我的意思,哈哈哈,如果有遇到过同样的问题或是解决方法欢迎前来讨饶,qq:1718066603,加好友是请注明是解决或讨论问题的,嘻嘻,真心希望问题能够得到解决)
788



被折叠的 条评论
为什么被折叠?



