深度学习——keras训练RNN模型

若如初见. 提交于 2019-11-28 02:29:55

深度学习——keras训练RNN模型

RNN原理:(Recurrent Neural Networks)循环神经网络。它在隐藏层的各个神经元之间是有相互作用的,能够处理那些输入之间前后有关联的问题。在 RNN 中,前一时刻的输出会和下一时刻的输入一起传递下去,相当于一个随时间推移的数据流。和前馈神经网络不同的是,RNN 可以接收序列化的数据作为输入,也可以返回序列化值作为输出,对时间序列上的变化进行建模。由于样本出现的时间顺序对于自然语言处理、语音识别、手写体识别等应用非常重要,故RNN模型在该领域内广泛被认可。

用 RNN 训练语言模型生成文本


训练代码详解:

思路整理:我们使用RNN对datasets.mnist数据进行分类,将图像28×28的分辨率理解为一个(信息行数×时间节点)序列数据,建立RNN_cell分类训练,并计算误差、精度。

  • 导入相关模块(module):
import numpy as np
np.random.seed(1337)  # for reproducibility

from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import SimpleRNN, Activation, Dense
from keras.optimizers import Adam
  • 参数初始化:
TIME_STEPS = 28     # same as the height of the image
INPUT_SIZE = 28     # same as the width of the image
BATCH_SIZE = 50
BATCH_INDEX = 0
OUTPUT_SIZE = 10
CELL_SIZE = 50
LR = 0.001

OUTPUT_SIZE:输出的数据归类结果的长度,用10维的0-1序列表示,例如(0,0,0,1,0,0,0,0,0,0)表示4。

  • 加载数据集:
# download the mnist to the path '~/.keras/datasets/' if it is the first time to be called
# X shape (60,000 28x28), y shape (10,000, )
(X_train, y_train), (X_test, y_test) = mnist.load_data()
  • 数据预处理(归一化):
# data pre-processing
X_train = X_train.reshape(-1, 28, 28) / 255.      # normalize
X_test = X_test.reshape(-1, 28, 28) / 255.        # normalize
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)

训练数据要进行归一化处理,因为原始数据是8bit灰度图像所以需要除以255。

  • 构建RNN模型(序列化):
# build RNN model
model = Sequential()
  • 添加RNN层:

输入为训练数据,输出数据大小由CELL_SIZE定义。

# RNN cell
model.add(SimpleRNN(
    # for batch_input_shape, if using tensorflow as the backend, we have to put None for the batch_size.
    # Otherwise, model.evaluate() will get error.
    batch_input_shape=(None, TIME_STEPS, INPUT_SIZE),       # Or: input_dim=INPUT_SIZE, input_length=TIME_STEPS,
    output_dim=CELL_SIZE,
    unroll=True,
))
  • 添加输出层:
# output layer
model.add(Dense(OUTPUT_SIZE))
model.add(Activation('softmax'))
  • 设置优化器、loss函数与metrics方法
# optimizer
adam = Adam(LR)
model.compile(optimizer=adam,
              loss='categorical_crossentropy',
              metrics=['accuracy'])
  • 开始训练:
# training
for step in range(4001):
    # data shape = (batch_num, steps, inputs/outputs)
    X_batch = X_train[BATCH_INDEX: BATCH_INDEX+BATCH_SIZE, :, :]
    Y_batch = y_train[BATCH_INDEX: BATCH_INDEX+BATCH_SIZE, :]
    cost = model.train_on_batch(X_batch, Y_batch)
    BATCH_INDEX += BATCH_SIZE
    BATCH_INDEX = 0 if BATCH_INDEX >= X_train.shape[0] else BATCH_INDEX
  • 输出正确分类的误差与精确度:
if step % 500 == 0:
        cost, accuracy = model.evaluate(X_test, y_test, batch_size=y_test.shape[0], verbose=False)
        print('test cost: ', cost, 'test accuracy: ', accuracy)

训练操作:

参照上一篇AutoEncoder模型训练方法,运行7-RNN_Classifier_example.py,运行结果为:

这里写图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!