学习,笔记,有时间会加注释以及函数之间的逻辑关系。
# https://www.cnblogs.com/felixwang2/p/9190664.html
1 # https://www.cnblogs.com/felixwang2/p/9190664.html 2 # TensorFlow(十二):使用RNN实现手写数字识别 3 4 import tensorflow as tf 5 from tensorflow.examples.tutorials.mnist import input_data 6 7 # 载入数据集 8 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 9 10 # 输入图片是28*28 11 n_inputs = 28 # 输入一行,一行有28个数据 12 max_time = 28 # 一共28行 13 lstm_size = 100 # 隐层单元 14 n_classes = 10 # 10个分类 15 batch_size = 50 # 每批次50个样本 16 n_batch = mnist.train.num_examples // batch_size # 计算一共有多少个批次 17 18 # 这里的none表示第一个维度可以是任意的长度 19 x = tf.placeholder(tf.float32, [None, 784]) 20 # 正确的标签 21 y = tf.placeholder(tf.float32, [None, 10]) 22 23 # 初始化权值 24 weights = tf.Variable(tf.truncated_normal([lstm_size, n_classes], stddev=0.1)) 25 # 初始化偏置值 26 biases = tf.Variable(tf.constant(0.1, shape=[n_classes])) 27 28 29 # 定义RNN网络 30 def RNN(X, weights, biases): 31 # inputs=[batch_size, max_time, n_inputs] 32 inputs = tf.reshape(X, [-1, max_time, n_inputs]) 33 # 定义LSTM基本CELL 34 lstm_cell = tf.contrib.rnn.BasicLSTMCell(lstm_size) 35 # final_state[state,batch_size,cell.state_size] 36 # final_state[0]是cell state 37 # final_state[1]是hidden_state 38 # outputs: The RNN output 'Tensor'. 39 # If time_major == False (default), this will be a `Tensor` shaped: 40 # `[batch_size, max_time, cell.output_size]`. 41 # If time_major == True, this will be a `Tensor` shaped: 42 # `[max_time, batch_size, cell.output_size]`. 43 # final_state 记录的是最后一次的输出结果 44 # outputs 记录的是每一次的输出结果 45 46 outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, inputs, dtype=tf.float32) 47 results = tf.nn.softmax(tf.matmul(final_state[1], weights) + biases) 48 return results 49 50 51 # 计算RNN的返回结果 52 prediction = RNN(x, weights, biases) 53 # 损失函数 54 cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=y)) 55 # 使用AdamOptimizer进行优化 56 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 57 # 结果存放在一个布尔型列表中 58 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) # argmax返回一维张量中最大的值所在的位置 59 # 求准确率 60 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 把correct_prediction变为float32类型 61 # 初始化 62 init = tf.global_variables_initializer() 63 64 gpu_options = tf.GPUOptions(allow_growth=True) 65 with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess: 66 sess.run(init) 67 for epoch in range(6): 68 for batch in range(n_batch): 69 batch_xs, batch_ys = mnist.train.next_batch(batch_size) 70 sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys}) 71 72 acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}) 73 print("Iter " + str(epoch) + ", Testing Accuracy= " + str(acc))
输出
Iter 0, Testing Accuracy= 0.6694 Iter 1, Testing Accuracy= 0.714 Iter 2, Testing Accuracy= 0.7984 Iter 3, Testing Accuracy= 0.8568 Iter 4, Testing Accuracy= 0.8863 Iter 5, Testing Accuracy= 0.9088 Process finished with exit code 0