循环神经网络lstm代码实现(07-3)

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#载入数据集
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)

#输入的图片是28*28
n_inputs=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,weight,biases):
    inputs=tf.reshape(X,[-1,max_time,n_inputs])
    #定义LSTM基本CELL
    lstm_cell=tf.contrib.rnn.BasicLSTMCell(lstm_size)
    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进行优化
trian_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#结果存放在一个布尔型列表中
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #argmax返回一维张量中最大的值所在的位置
#求准确率
accuarcy=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(6):
        for batch in range(n_batch):
            batch_xs,batch_ys=mnist.train.next_batch(batch_size)
            sess.run(trian_step, feed_dict={x:batch_xs,y:batch_ys})

        acc=sess.run(accuarcy, feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print ("Iter "+str(epoch)+", Testing Accuarcy= " + str(acc))

运行结果:

目录:

  1. tensorflow简介、目录
  2. tensorflow中的图(02-1)
  3. tensorflow变量的使用(02-2)
  4. tensorflow中的Fetch、Feed(02-3)
  5. tensorflow版helloworld---拟合线性函数的k和b(02-4)
  6. tensorflow非线性回归(03-1)
  7. MNIST手写数字分类simple版(03-2)
  8. 二次代价函数、交叉熵(cross-entropy)、对数似然代价函数(log-likelihood cost)(04-1)
  9. 多层网络通过防止过拟合,增加模型的准确率(04-2)
  10. 修改优化器进一步提升准确率(04-3)
  11. 手写数字识别-卷积神经网络cnn(06-2)
  12. 循环神经网络rnn与长短时记忆神经网络简述(07-2)
  13. 循环神经网络lstm代码实现(07-3)
  14. tensorflow模型保存和使用08
  15. 下载inception v3  google训练好的模型并解压08-3
  16. 使用inception v3做各种图像分类识别08-4
  17. word2vec模型训练简单案例
  18. word2vec+textcnn文本分类简述及代码
原文地址:https://www.cnblogs.com/go-ahead-wsg/p/12543627.html