当前位置:   article > 正文

CNN-文本分类任务实战

CNN-文本分类任务实战

一、了解

 

CNN文本分类实战

1:文本数据预处理,必须都是相同长度,相同向量维度

2:构建卷积模型,注意卷积核大小的设计

3:将卷积后的特征图池化为一个特征

4:将多种特征拼接在一起,准备完成分类任务

二、实战

第一步,导入库

  1. import warnings
  2. warnings.filterwarnings('ignore')
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import tensorflow as tf
  6. from tensorflow import keras
  7. from tensorflow.keras import layers
  8. from tensorflow.keras.preprocessing.sequence import pad_sequences

 第二步,设置参数并加载数据

  1. num_features = 3000 # 语料库单词数
  2. sequence_length = 300 # 评论最大长度
  3. embedding_dimension = 100 # 词嵌入向量维度
  4. (x_train, y_train), (x_test, y_test) = keras.datasets.imdb.load_data(num_words=num_features)
  5. print(x_train.shape)
  6. print(y_train.shape)
  7. print(x_test.shape)
  8. print(y_test.shape)
  9. print(x_train[0])

第三步,规定文本长度

  1. x_train = pad_sequences(x_train, maxlen=sequence_length)
  2. x_test = pad_sequences(x_test,maxlen=sequence_length)
  3. print(x_train.shape)
  4. print(x_test.shape)
  5. print(y_train.shape)
  6. print(y_test.shape)

第四步,搭建卷积过程函数

  1. #多种卷积核
  2. filter_size = [3,4,5]
  3. def convolution():
  4. inn = layers.Input(shape=(sequence_length,embedding_dimension,1)) # 3维的
  5. cnns = []
  6. for size in filter_size:
  7. conv = layers.Conv2D(filters=64,
  8. kernel_size=(size,embedding_dimension),
  9. strides=1,padding='valid',
  10. activation='relu')(inn)
  11. #需要将多种卷积后的特征图池化为一个特征
  12. pool = layers.MaxPool2D(pool_size=(sequence_length - size + 1, 1),padding='valid')(conv)
  13. cnns.append(pool)
  14. #将得到的特征拼接在一起
  15. outt = layers.concatenate(cnns)
  16. model = keras.Model(inputs=inn,outputs=outt)
  17. return model

第五步,构建网络模型

  1. def cnn_mulfilter():
  2. model = keras.Sequential([
  3. # 将 num_features 个不同的词,映射成词向量
  4. # 并且这是需要训练的词嵌入矩阵embedding
  5. layers.Embedding(input_dim=num_features,
  6. output_dim=embedding_dimension,
  7. input_length=sequence_length),
  8. # 因为卷积层的输入需要是三维的,所以要调整
  9. layers.Reshape((sequence_length, embedding_dimension, 1)),
  10. convolution(),
  11. layers.Flatten(),
  12. layers.Dense(10, activation='relu'),
  13. layers.Dropout(0.2),
  14. layers.Dense(1, activation=tf.nn.sigmoid)
  15. ])
  16. model.compile(optimizer=tf.optimizers.Adam(),
  17. loss=tf.losses.BinaryCrossentropy(),
  18. metrics=['accuracy'])
  19. return model
  20. model = cnn_mulfilter()
  21. model.summary()

部分运行结果:

  1. Model: "sequential"
  2. _________________________________________________________________
  3. Layer (type) Output Shape Param #
  4. =================================================================
  5. embedding_1 (Embedding) (None, 300, 100) 300000
  6. _________________________________________________________________
  7. reshape_1 (Reshape) (None, 300, 100, 1) 0
  8. _________________________________________________________________
  9. model (Functional) (None, 1, 1, 192) 76992

计算过程如下:

1。Embedding层,参数个数为需要更新的 E 词向量矩阵,即参数个数为

单词种类数 num_features * 词向量维度embedding_dimension = 3000 * 100 = 300000

其输出维度则为 batch,sequence_length,embedding_dimension = None,300,100

2。model (Functional) 层,经过 3,4,5 三个核卷积,卷积后的输出维度为

  1. 300 - 3 + 1 = 298300 - 4 + 1 = 297300 - 5 + 1 = 296
  2. 即 (298164),(297164),(296164
  3. 之后经过池化,变成
  4. 1164),(1164),(1164
  5. 再经过拼接,变成
  6. 1164*3=11192

故其输出维度则为 batch,1,1,192= None,1,1,192,

其参数个数为 (3 * 100 + 1)64 + (4 * 100 + 1)64 + (5 * 100 + 1)*64 = 76992

第六步,训练模型与评估

  1. history = model.fit(x_train, y_train, batch_size=64, epochs=5, validation_split=0.1)
  2. model.evaluate(x_test,y_test)

第七步,显示迭代过程

  1. plt.plot(history.history['accuracy'])
  2. plt.plot(history.history['val_accuracy'])
  3. plt.legend(['training','valiation'],loc='upper left')
  4. plt.show()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/242707
推荐阅读