莫烦大大keras学习Mnist识别(4)-----RNN

一、步骤:

  1. 导入包以及读取数据

  2. 设置参数

  3. 数据预处理

  4. 构建模型

  5. 编译模型

  6. 训练以及测试模型

二、代码:

1、导入包以及读取数据

#导入包
import numpy as np
np.random.seed(1337)  #设置之后每次执行代码,产生的随机数都一样

from tensorflow.examples.tutorials.mnist import input_data
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import SimpleRNN , Activation , Dense
from keras.optimizers import Adam

#读取数据
mnist = input_data.read_data_sets('E:\jupyter\TensorFlow\MNIST_data',one_hot = True)
X_train = mnist.train.images
Y_train = mnist.train.labels
X_test = mnist.test.images
Y_test = mnist.test.labels

2、设置参数

#设置参数
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

3、数据预处理

#数据预处理
X_train = X_train.reshape(-1,28,28)/255
X_test = X_test.reshape(-1,28,28)/255

4、构建模型

#构建模型
model = Sequential()

#RNN层
model.add(SimpleRNN(
    batch_input_shape =(None,time_steps,input_size), # 输入维度
    output_dim = cell_size, #输出维度
))

#输出层
model.add(Dense(output_size))
model.add(Activation('softmax'))

5、训练模型以及测试

#训练模型
for step in range(4001):
    
    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:
        loss , acc = model.evaluate(X_test,Y_test,batch_size =Y_test.shape[0])
        print(loss,',',acc)

猜你喜欢

转载自www.cnblogs.com/Lee-yl/p/10131543.html