• TensorFlow——LSTM长短期记忆神经网络处理Mnist数据集


    1、RNN(Recurrent Neural Network)循环神经网络模型

    详见RNN循环神经网络:https://www.cnblogs.com/pinard/p/6509630.html

    2、LSTM(Long Short Term Memory)长短期记忆神经网络模型

    详见LSTM长短期记忆神经网络:http://www.cnblogs.com/pinard/p/6519110.html
     
    3、LSTM长短期记忆神经网络处理Mnist数据集
    import tensorflow as tf
    from tensorflow.examples.tutorials.mnist import input_data
    from tensorflow.contrib import rnn
    
    # 载入数据集
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    
    # 输入图片是28*28
    n_inputs = 28  # 输入一行,一行有28个数据(28个像素点),即输入序列长度为28
    max_time = 28  # 一共28行
    lstm_size = 100  # 隐层单元
    n_classes = 10  # 10个分类
    batch_size = 50  # 每批次50个样本
    n_batch = mnist.train.num_examples // batch_size  # 计算一共有多少个批次
    
    # 这里的none表示第一个维度可以是任意的长度
    x = tf.placeholder(tf.float32, [None, 784])
    # 正确的标签
    y = tf.placeholder(tf.float32, [None, 10])
    
    # 初始化权值
    weights = tf.Variable(tf.truncated_normal([lstm_size, n_classes], stddev=0.1))
    # 初始化偏置值
    biases = tf.Variable(tf.constant(0.1, shape=[n_classes]))
    
    
    # 定义RNN网络
    def RNN(X, weights, biases):
        inputs = tf.reshape(X, [-1, max_time, n_inputs])
        # 定义LSTM基本CELL
        lstm_cell = rnn.BasicLSTMCell(lstm_size)
        # final_state[0]是cell state
        # final_state[1]是hidden_state
        outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, inputs, dtype=tf.float32)
        results = tf.nn.softmax(tf.matmul(final_state[1], weights) + biases)
        return results
    
    # 计算RNN的返回结果
    prediction = RNN(x, weights, biases)
    # 损失函数
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    # 使用AdamOptimizer进行优化
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    # 结果存放在一个布尔型列表中
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))  # argmax返回一维张量中最大的值所在的位置
    # 求准确率
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  # 把correct_prediction变为float32类型
    # 初始化
    init = tf.global_variables_initializer()
    
    with tf.Session() as sess:
        sess.run(init)
        for epoch in range(21):
            for batch in range(n_batch):
                batch_xs, batch_ys = mnist.train.next_batch(batch_size)
                sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})
    
            acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
            print("Iter " + str(epoch) + ", Testing Accuracy= " + str(acc))
    

     结果为:

     

  • 相关阅读:
    教你一招Linux下文本比对方法
    Linux下find与exec的联手干大事
    Linux下Shell日期的格式,你知道几种?
    Linux下Python3.6的安装及避坑指南
    多线程中使用CompletableFuture
    ElasticSearch7.6.2中语法使用(更新中)
    ElasticSearch7.6.2使用_update_by_query语法
    ElasticSearch7.6.2使用_delete_by_query产生版本冲突问题
    filebeat7.6.2进程运行一段时间后自动退出问题解决
    把本地项目提交到gitLab
  • 原文地址:https://www.cnblogs.com/asialee/p/9277161.html
Copyright © 2020-2023  润新知