#%%
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 shape: (60000, 28, 28) ndarray
# y_train shape: (60000,)
# x_test shape: (10000, 28, 28)
# y_test shape: (10000,)
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#%%
# 归一化
x_train = x_train / 255.
x_test = x_test / 255.
#%%
# to one-hot
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,
# 输入 (row, col)
input_shape=(time_steps, input_size)))
# 输出10个类别
model.add(Dense(10, activation='softmax'))
#%%
# 优化器 学习率1e-4
adam = Adam(lr=1e-4)
#%%
# 编译模型
model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])
#%%
# 训练
model.fit(x_train, y_train, batch_size=64, epochs=10)
#%%
# 模型评价
loss, accuracy = model.evaluate(x_test, y_test)
#%%
print(loss)
print(accuracy)
TensorFlow Keras RNN
于 2021-12-22 22:04:55 首次发布