莫煩大大keras學習Mnist識別(4)-----RNN
阿新 • • 發佈:2018-12-17
一、步驟:
-
匯入包以及讀取資料
-
設定引數
-
資料預處理
-
構建模型
-
編譯模型
-
訓練以及測試模型
二、程式碼:
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 Sequentialfrom 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)