RNN-LSTM网络模型预测结果
Show me the code
导包
# 顺序模型
from keras import Sequential
# 网络模型,RNN模型
from keras.layers import Dense, LSTM
# 优化器
from keras.optimizers import Adam
# one hot
from keras import utils
import numpy as np
import matplotlib.pyplot as plt
数据获取模块
# 定义获取MINST数据的函数
# 返回mnist归一化以后的数据
def get_minst(file_path= "./mnist.npz"):
# 导入并预处理手写字符集数据,注释的这一行有vpn的朋友可以很快下载
# 没有vpn请下载mnist.npz文件
# (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
with np.load(file_path) as f:
x_train, y_train, x_test, y_test =
f["x_train"], f["y_train"], f["x_test"], f["y_test"]
# 转化为浮点类型
x_train = x_train.astype("float64")
x_test = x_test.astype("float64")
# 将图像除以255进行像素值归一化
x_train /= 255
x_test /= 255
# 将y_train与y_test转化为“one hot”形式
y_train = utils.to_categorical(y_train)
y_test = utils.to_categorical(y_test)
# 打印显示原始数据维度
print("原始数据大小:")
print("x_train的大小为:", x_train.shape)
print("y_train的大小为:", y_train.shape)
print("x_test的大小为:", x_test.shape)
print("y_test的大小为:", y_test.shape)
return x_train, y_train, x_test, y_test
RNN-LSTM网络定义
# 定义RNN网络模型,cell_size是RNN网络的block数
def RNN_for_minst(x_train, y_train,
x_test, y_test,
n_steps, n_features, cell_size= 50):
# 定义模型
model = Sequential()
model.add(LSTM(units=cell_size, input_shape= (n_steps, n_features)))
model.add(Dense(units= 10, activation= "softmax"))
# 定义优化器
adam = Adam()
# 整合模型
model.compile(optimizer= adam,
loss= "categorical_crossentropy",
metrics=["accuracy"])
# 开始训练
print("\n开始训练")
model.fit(x_train, y_train,
batch_size= round(x_train.shape[0] * 0.01),
epochs= 10)
# 评价模型
print("\n评价模型:")
final_loss, final_accuracy = model.evaluate(x_test, y_test)
print("loss= ", final_loss)
print("accuracy= ", final_accuracy)
return model
测试模块
# 选取一副测试集图像进行测试
def test_RNN_model(model, x_test, n_steps, n_features):
# 选取一个测试集合图像的序号
dex = np.random.randint(0, x_test.shape[0] - 1)
# 获得该序号的图像
img = x_test[dex, :].reshape(n_steps, n_features)
# 利用模型进行预测
y_predict = np.argmax(
model.predict(img.reshape(1, n_steps, n_features)))
# 显示原图像,打印预测结果
print("\n随机抽取测试集图像进行预测:")
print("测试集图像序号为:", dex)
print("原图像为:")
plt.imshow(img)
plt.show()
print("模型预测结果为:", y_predict)
定义主函数
# 定义主函数
def main():
# 参数设置
n_steps = 28 # 行
n_features = 28 # 列
# 调用自定义函数,获取MINST数据
x_train, y_train, x_test, y_test = get_minst()
# 调用自定义RNN网络进行训练
model = RNN_for_minst(x_train, y_train,
x_test, y_test,
n_steps, n_features)
# 随机测试一个测试集图像
test_RNN_model(model, x_test, n_steps, n_features)
调用主函数
# 调用主函数
if __name__ == "__main__":
main()