TensorFlow1.x入门(10)——循环神经网络(RNN)

系列文章

本教程有同步的github地址

0. 统领篇

1. 计算图的创建与启动

2. 变量的定义及其操作

3. Feed与Fetch

4. 线性回归

5. 构建非线性回归模型

6. 简单分类问题

7. Dropout与优化器

8. 手动调整学习率与TensorBoard

9. 卷积神经网络(CNN)

10. 循环神经网络(RNN)

11. 模型的保存与恢复

循环神经网络(RNN)

引言

循环神经网络(Recurrent Neural Network, RNN)是深度神经网络中重要组成部分,常用于处理时序问题。但是它本身不适用于对图片信息的理解,所以在图像识别领域不常用,但是在NLP和语音识别领域较为常用。

知识点

tf.contrib.rnn.BasicLSTMCell()用于定义LSTM网络,LSTM作为RNN族中的一种可以很好的控制梯度爆炸和梯度消失的问题。参数lstm_size代表了当前LSTM的维度如何。

tf.nn.dynamic_rnn()是RNN的动态展开函数,接收输入的数据inputs和lstm_cell,训练时按照序列长度进行展开。返回的结果为outputs和final_state,前者为网络中的每个时间步的输出的综合,后者为最后一个cell的state。

示例

#%% md
# 循环神经网络(RNN)
#%% md
循环神经网络(RNN)主要用于处理序列问题,针对时序建模,通过时间步递归(循环)来更新参数。
#%% md
导包
#%%
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#%% md
载入数据
#%%
mnist = input_data.read_data_sets("MNIST", one_hot=True)
#%% md
超参数设置
#%%
n_inputs = 28  # 每个输入的维度
max_times = 28 # 序列的最大输入步数
lstm_size = 100 # LSTM的hidden_dim(可认为是RNN)
n_classes = 10 # 类别
batch_size = 32
n_batchs = mnist.train.num_examples // batch_size
#%% md
定义placeholder
#%%
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
#%% md
初始化网络的权值和偏置值
#%%
weights = tf.Variable(tf.truncated_normal([lstm_size, n_classes], stddev=0.1))
biases = tf.Variable(tf.constant(0.1,shape=[n_classes]))
#%% md
定义RNN网络
#%%
def RNN(x, w, b):
    inputs = tf.reshape(x, [-1, max_times, n_inputs])
    lstm_cell = tf.contrib.rnn.BasicLSTMCell(lstm_size)
    output, final_state = tf.nn.dynamic_rnn(lstm_cell, inputs, dtype=tf.float32)
    result = tf.nn.softmax(tf.matmul(final_state[1], w) + b)
    return result
#%%
prediction = RNN(x, weights, biases)
#%%
prediction
#%% md
定义损失函数与优化器
#%%
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)
#%% md
获取测评结果
#%%
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#%% md
初始化计算图中的变量
#%%
init = tf.global_variables_initializer()
#%% md
训练
#%%
with tf.Session() as sess:
    sess.run(init)
    for epc in range(100):
        for batch in range(n_batchs):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run([train_step],{x:batch_xs, y:batch_ys})
        acc, l = sess.run([accuracy, loss], {x:mnist.test.images, y:mnist.test.labels})
        print("Iter: " +str(epc) + " Accurcay: " + str(acc) + " Loss: " + str(l))

猜你喜欢

转载自blog.csdn.net/qq_19672707/article/details/105616284
今日推荐