Keras RNN运用于手写数字识别

Keras RNN运用于手写数字识别

导入相关的包

import numpy as np
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
from keras.layers.recurrent import SimpleRNN,LSTM,GRU

载入数据

直接从keras下载可能会比较慢,这里事先准备好了数据集

链接:https://pan.baidu.com/s/1kbDiH-nnbgmTRdaZM6c80g
提取码:sg2k

#载入数据
# (x_train,y_train),(x_test,y_test) = mnist.load_data() 
#自己准备好数据集,并存放在当前目录的文件夹下
path = 'mnist.npz'
def downloadmnist(path):
    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()
    return (x_train,y_train),(x_test,y_test)
(x_train,y_train),(x_test,y_test) = downloadmnist(path)
#(60000,28,28)
x_train = x_train/255.0
x_test = x_test/255.0
#换one hot 格式
y_train = np_utils.to_categorical(y_train,num_classes=10)
y_test = np_utils.to_categorical(y_test,num_classes=10)

模型构建

input_size = 28  #数据长度,一行28个像素
time_step = 28   #序列长度 一共有28行
cell_size = 50 #隐藏层个数
#模型构建
model = Sequential()
#循环神经网络
model.add(SimpleRNN(units=cell_size,input_shape=(time_step,input_size)))
model.add(Dense(units=10,activation='softmax'))
adam = Adam(lr = 0.001)
model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['accuracy'])

训练模型

#训练模型
model.fit(x_train,y_train,batch_size=32,epochs=10)

评估模型

#评估模型
test_loss,test_accuracy = model.evaluate(x_test,y_test)
print('test_loss:',test_loss)
print('test_accuracy:',test_accuracy)

train_loss,train_accuracy = model.evaluate(x_train,y_train)
print('train_loss:',train_loss)
print('train_accuracy:',train_accuracy)

预测结果

test_loss: 0.1555712076753378
test_accuracy: 0.9553999900817871
60000/60000 [==============================] - 3s 43us/step
train_loss: 0.13748281036193172
train_accuracy: 0.9602000117301941

你可能感兴趣的:(深度学习)