Keras 成长之路(五)构建RNN-LSTM模型并处理MNIST手写数字集(RNN循环神经网络)

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()
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值