文本分类流程详细总结_keras
一、背景一、背景在进行深度学习的时候,需要进行模型的预处理和数据转换,这里记录一下内容和方法,方便以后的使用和查找。根据模型的过程,将会按照数据集的处理、标签转化、文本向量化、模型构建、添加评估内容等几个基础的方面进行介绍。二、内容介绍二、内容介绍2.1 数据的读取2.1 数据的读取数据的读取一般是直接使用pandas进行读取。这里需要注意的问题就是编码的问题,在进行操作的时候,往往会出现无法识别的编码,下面进行一个总结和一些情况的处理,有助于以后能够快速找到问题,同时给出知乎的。编码差距2.2 数据的洗涤2.2 数据的洗涤数据洗涤一般使用pandas中的apply的方法。下面给出字符替换的内容(参考Tokenizer源码中数据洗涤的方法),需要其他的内容直接在处理函数中增加即可。(:):def data_detail textstr-str ,filters=!#$%&()*+,-./:;?_|tn :for i in filters .(,)text replace i return text .()pf text=pf text apply data_detail 1.2.3.4.5.6.7.2.3 文本向量化2.3 文本向量化对于文本数据需要进行文本的向量化,像图像数据或者其他的数字数据不需要进行这一步操作,可以直接放入模型中进行训练。文本话的方法也是训练一个文本转化器,然后通过序列化的方法,将文本转成对于的id值,这一步操作可以使用内置方法,也可以自己建立一个词典,然后使用numpy将得到的结果向量化,就可以进行训练。#()tokenizer=Tokenizer num_words=MAX_NUM_WORDS#.()tokenizer fit_on_texts text_c#idTokenizeroov_tokenoov_token .()sequences=tokenizer texts_to_sequences texts#post0 (,)data=pad_sequences sequencesmaxlen=MAX_NUM_WORDSpadding=post 1.2.3.4.5.6.7.8.9.2.4 标签one-hot化2.4 标签one-hot化在进行训练的时候,需要将标签也转码,因此我们需要将其编程one-hot编码,这里也分为两种情况。第一是数字标签且不要求按照顺序排列,可以直接使用to_categorical转码。第二是非数字标签,或者要求从1或者0开始的,那就是需要使用到LabelEncoder()去训练一个标签编码器,然后进行标注,标注完成之后再使用to_categorical去编码,同时可以使用标签器将标签转成数据。下面介绍一下使用:#to_categorical label=to_categorical(x)#from sklearn import preprocessing#.()label_coder=preprocessing LabelEncoder#.()label_coder fit labels#.()result_tr=label_coder transform labels#one-hot ()labels=to_categorical result_tr 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.2.5 数据分割2.5 数据分割在训练的时候,需要对数据进行一个分割,或者是重排。可以先将标签以及数据都处理好再去分割,或者重排。#.from sklearn model_selection import train_test_split#import random#random_state ,(,)train_xtest_xtrain_ytest_y=train_test_split datalabelsrandom_state=42#(,):def none_shuffle x_1y_1state_random=42 (,)_array=list zip x_1y_1 .()random seed state_random .()random shuffle _array ,()x_y_=zip*_array .(,),.(,)return np array x_dtype=int32np array y_dtype=float32 ,(,)train_xtrain_y=none_shuffle train_xtrain_y 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.2.6 模型构建2.6 模型构建通过前面的处理,已经将数据准备完成,下面就将进行模型构建,模型构建的方式通常分为两种。第一个是使用Sequential然后用add的方法去叠加模型;另一个是使用Model将输入、输出指定,包括Input,和输出形式,这样就可以完成模型的构建。这两种方法的区别是:使用Sequential的可以直接在预测中调用方法预测,方法简单但是在扩展性上不好,多模型复杂结构是无法完成的。使用Model的方法需要使用np.max的方法获取最大输出值的位置,可以一层一层指定,拓展性高,可以完成复杂模型的叠加和处理。keraskerasTensorFlow.kerasbug#Sequential ()model=Sequential .(,)model add Embedding 400256 .(,)model add Bidirectional LSTM 256return_sequences=True .()model add Attention .()model add FM 256 .()model add Flatten .()model add Dropout 0.2 .(.),)model add Dense len label_coder classes_activation=softmax#Model MAX_LEN=400 (,)input_layer=Input shape=MAX_LEN (),)()layer=Embedding input_dim=len id2charoutput_dim=256input_layer (,)()layer=Bidirectional LSTM 256return_sequences=Truelayer ()()layer=Flattenlayer (.(),)()output_layer=Dense len df_train labeluniqueactivation=softmaxlayer (,)model=Model inputs=input_layeroutputs=output_layer .()model summary 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.2.7 模型训练2.7 模型训练模型训练通常需要一个指标或者优化,包括设置损失函数、评估函数等。#categorical_crossentropysoftmax#binary_crossentropysigmoid#optimizerkerasoptimizerscallbackskerascallbacksModelCheckpointEarlyStoppingTensorBoardReduceLROnPlateau metrics accuracy .(,(),()model compile loss=categorical_crossentropyoptimizer=adammetrics=accuracy recall_threshold 0.5precision_threshold 0.5#validation_data#.(,)history=model fit x_trainy_train ,batch_size=256 ,epochs=100 (,),validation_data=x_testy_test ,verbose=1 callbacks=callbacks)#modelinputs,.(,)history=model fitx_trainwordnet_trainkg_trainy_train 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.给出metrics的方法包括f1、召回率、精确率。(,):def F1_macro y_truey_pred#matthews_correlation .(.(,)y_pred_pos=K round K clip y_pred01 y_pred_neg=1-y_pred_pos .(.(,)y_pos=K round K clip y_true01 y_neg=1-y_pos .()tp=K sum y_pos*y_pred_pos .()tn=K sum y_neg*y_pred_neg .()fp=K sum y_neg*y_pred_pos .()fn=K sum y_pos*y_pred_neg ()numerator=tp*tn-fp*fn .()()()()denominator=K sqrttp+fp*tp+fn*tn+fp*tn+fn (.()return numerator/denominator+K epsilon ():def recall_threshold threshold=0.5 (,):def recall y_truey_pred Recall metric.Computes the recall over the whole batch using threshold_value.threshold_value=threshold#Adaptation of the round()used before to get the predictions.Clipping to make sure that the predicted raw values are between 0 and 1.(.(.(,),),.()y_pred=K cast K greater K clip y_pred01threshold_valueK floatx#Compute the number of true positives.Rounding in prevention to make sure we have an integer.(.(.(,)true_positives=K round K sum K clip y_true*y_pred01#Compute the number of positive targets.(.(,)possible_positives=K sum K clip y_true01 (.()recall_ratio=true_positives/possible_positives+K epsilon return recall_ratio return recall ():def precision_threshold threshold=0.5 (,):def precision y_truey_pred Precision metric.Computes the precision over the whole batch using threshold_value.threshold_value=threshold#Adaptation of the round()used before to get the predictions.Clipping to make sure that the predicted raw values are between 0 and 1.(.(.(,),),.()y_pre