zoukankan      html  css  js  c++  java
  • 莫烦大大keras学习Mnist识别(4)-----RNN

    一、步骤:

    1. 导入包以及读取数据

    2. 设置参数

    3. 数据预处理

    4. 构建模型

    5. 编译模型

    6. 训练以及测试模型

    二、代码:

    1、导入包以及读取数据

    #导入包
    import numpy as np
    np.random.seed(1337)  #设置之后每次执行代码,产生的随机数都一样
    
    from tensorflow.examples.tutorials.mnist import input_data
    from keras.utils import np_utils
    from keras.models import Sequential
    from keras.layers import SimpleRNN , Activation , Dense
    from keras.optimizers import Adam
    
    #读取数据
    mnist = input_data.read_data_sets('E:jupyterTensorFlowMNIST_data',one_hot = True)
    X_train = mnist.train.images
    Y_train = mnist.train.labels
    X_test = mnist.test.images
    Y_test = mnist.test.labels

    2、设置参数

    #设置参数
    time_steps = 28     # same as the height of the image
    input_size = 28     # same as the width of the image
    batch_size = 50
    batch_index = 0
    output_size = 10
    cell_size = 50
    lr = 0.001

    3、数据预处理

    #数据预处理
    X_train = X_train.reshape(-1,28,28)/255
    X_test = X_test.reshape(-1,28,28)/255

    4.1、构建RNN模型

    #构建模型
    model = Sequential()
    
    #RNN层
    model.add(SimpleRNN(
        batch_input_shape =(None,time_steps,input_size), # 输入维度
        output_dim = cell_size, #输出维度
    ))
    
    #输出层
    model.add(Dense(output_size))
    model.add(Activation('softmax'))

    4.2、构建LSTM模型

    def builtLSTMModel(time_steps,input_size,cell_size,output_size):
        model = Sequential()
    
        #添加LSTM
        model.add(LSTM(
            batch_input_size = (None,time_steps,input_size),
            output_dim = cell_size,
            return_sequences = True,  #要不要每个时间点的输出都输出
            stateful = True,  #batch和batch有联系,batch和batch之间的状态需要连接起来
        ))
    
        #添加输出层
        model.add(TimeDistributed(Dense(output_size))) #每一个时间点的输出都要加入全连接层。
        return model

    5、训练模型以及测试

    #训练模型
    for step in range(4001):
        
        X_batch = X_train[batch_index:batch_size + batch_index,:,:]
        Y_batch = Y_train[batch_index:batch_size + batch_index,:]
        cost = model.train_on_batch(X_batch,Y_batch)
        
        batch_index += batch_size
        batch_index = 0 if batch_index >= X_train.shape[0] else batch_index
        
        if step % 500 ==0:
            loss , acc = model.evaluate(X_test,Y_test,batch_size =Y_test.shape[0])
            print(loss,',',acc)
  • 相关阅读:
    剑指 Offer 22. 链表中倒数第k个节点
    剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
    Leetcode1450. 在既定时间做作业的学生人数
    Leetcode1572. 矩阵对角线元素的和
    Leetcode 1480. 一维数组的动态和
    Idea连接数据库报错
    Java实现二叉树层次遍历并存入List的方法:从上往下,从左往右
    SpringCloud资源网站
    Java循环对list进行remove
    Java中字符串判空的正确打开方式
  • 原文地址:https://www.cnblogs.com/Lee-yl/p/10131543.html
Copyright © 2011-2022 走看看