import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from keras.layers.recurrent import SimpleRNN
from keras.optimizers import Adam
#数据长度-一行有28个像素
input_size=28
#序列长度-一共有28行
time_steps=28
#隐藏层cell个数
cell_size=50
#载入数据
(x_train,y_train),(x_test,y_test)=mnist.load_data()
#打印知形状是(60000,28,28),如果是(60000,784)就要先展开
x_train=x_train/255.0#shape0就是60000,-1自动计算28*28
x_test=x_test/255.0
#换one hot格式:把输出训练成10个类
y_train=np_utils.to_categorical(y_train,num_classes=10)
y_test=np_utils.to_categorical(y_test,num_classes=10)
#定义顺序模型
model=Sequential()
#循环神经网络
model.add(SimpleRNN(
units=cell_size,#输出
input_shape=(time_steps,input_size),#输入
))
#输出层
model.add(Dense(10,activation='softmax'))#上面的3136与当前1024是全连接的
#定义优化器
adam=Adam(lr=1e-4)
#优化策略,损失估计,目标质量
model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['accuracy'])
#训练模型,每次训练32组数据,共需60000/32次训练,这叫一个周期,一共训练3个周期
model.fit(x_train,y_train,batch_size=64,epochs=1)
#评估模型
loss,accuracy=model.evaluate(x_test,y_test)
print('\ntest loss',loss)
print('accuracy',accuracy)
loss,accuracy=model.evaluate(x_train,y_train)
print('\ntest loss',loss)
print('accuracy',accuracy)