1. 程式人生 > >莫煩大大keras學習Mnist識別(4)-----RNN

莫煩大大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)