Python实现Keras搭建神经网络训练RNN分类模型

# RNN Classifier example

import numpy as np
# for reproducibility
np.random.seed(1337)
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import SimpleRNN, Dense, Activation
from keras.optimizers import Adam

# same as the height of the image
# 图片的高
TIME_STEPS = 28
# same as the width of the image
# 图片的行
INPUT_SIZE = 28
# 每批训练多少图片
BATCH_SIZE = 50
BATCH_INDEX = 0
OUTPUT_SIZE = 10
CELL_SIZE = 50
LR = 0.001

# download the mnist to the path if it is the first time to be called
# X shape (60,000 28x28), y
path='./mnist.npz'
f = np.load(path)
X_train, y_train = f['x_train'], f['y_train']
X_test, y_test = f['x_test'], f['y_test']
f.close()

# data pre-processing
# normalize
# 如果这里参数-1看不懂,参考:
# https://blog.csdn.net/weixin_45798684/article/details/106521618
X_train = X_train.reshape(-1, 28, 28) / 255
X_test = X_test.reshape(-1, 28, 28) / 255
y_train = np_utils.to_categorical(y_train, num_classes = 10)
y_test = np_utils.to_categorical(y_test, num_classes = 10)

# build RNN model
model = Sequential()

# RNN cell
model.add(SimpleRNN(
    batch_input_shape=(BATCH_SIZE, TIME_STEPS, INPUT_SIZE),
    output_dim = CELL_SIZE
))

# output layer
model.add(Dense(OUTPUT_SIZE))
model.add(Activation('softmax'))

# 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_SIZE+BATCH_INDEX, :, :]
    Y_batch = y_train[BATCH_INDEX: BATCH_SIZE+BATCH_INDEX, :]
    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=BATCH_SIZE, verbose=False)
        print('test cost:', cost, 'test accuracy:', accuracy)

运行结果:

Using TensorFlow backend.

test cost: 2.4057365703582763 test accuracy: 0.03909999877214432
test cost: 0.6252244361490011 test accuracy: 0.8118000030517578
test cost: 0.44355646131560206 test accuracy: 0.8684999942779541
test cost: 0.37015392679721115 test accuracy: 0.8921999931335449
test cost: 0.3447978501021862 test accuracy: 0.8998000025749207
test cost: 0.28056879829615355 test accuracy: 0.9178000092506409
test cost: 0.30827772413380444 test accuracy: 0.9107999801635742
test cost: 0.23811150034889578 test accuracy: 0.9301999807357788
test cost: 0.20896761409472675 test accuracy: 0.9404000043869019

你可能感兴趣的:(知识增加,深度学习)