rnn tensorflow 学习笔记

    1、将一个batch送入模型计算,设输入数据的形状为(batch_size, input_size),那么计算时得到的隐层状态就是(batch_size, state_size),输出就是(batch_size, output_size)。代码:(代码中没有输出,只有隐层状态)

#BasicRNNCell
import tensorflow as tf
import numpy as np

cell = tf.nn.rnn_cell.BasicRNNCell(num_units=128) # state_size = 128
print(cell.state_size) # 128

inputs = tf.placeholder(np.float32, shape=(32, 100)) # 32 是 batch_size,100 is input_size
h0 = cell.zero_state(32, np.float32) # 通过zero_state得到一个全0的初始状态,形状为(batch_size, state_size)
output, h1 = cell.__call__(inputs, h0) #调用call函数

print(h1.shape) # (32, 128)
   2、对于BasicLSTMCell,LSTM可以看做有两个隐状态h和c
#BasicLSTMCell
import tensorflow as tf
import numpy as np
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(num_units=128)
inputs = tf.placeholder(np.float32, shape=(32, 100)) # 32 是 batch_size,100 is input_size
h0 = lstm_cell.zero_state(32, np.float32) # 通过zero_state得到一个全0的初始状态
output, h1 = lstm_cell.__call__(inputs, h0)

print(h1.h)  # shape=(32, 128)
print(h1.c)  # shape=(32, 128)

    注意理解input_size 与time_step的区别:input_size是输入数据单个序列单个时间维度上固有的长度,即输入神经元的个数,输入维数。而time_step代表的是序列长度,序列长度为10,则time_step=10。

    3、一次执行多步:tf.nn.dynamic_rnn函数,使用该函数就相当于调用了n次call函数。即通过{h0,x1, x2, …., xn}直接得{h1,h2…,hn}。

time_steps = 10
inputs = tf.placeholder(np.float32, shape=(32, time_steps, 100))
outputs, state = tf.nn.dynamic_rnn(lstm_cell, inputs, initial_state=h0)
print(outputs) #shape=(32, 10, 128)
print(state) #c.shape=(32, 128) h.shape=(32, 128)

    outputs就是time_steps步里所有的输出。它的形状为(batch_size, time_steps, cell.output_size)。state是最后一步的隐状态,它的形状为(batch_size, cell.state_size)。

    4、堆叠多层RNNCell:MultiRNNCell。将x输入第一层RNN的后得到隐层状态h,这个隐层状态就相当于第二层RNN的输入,第二层RNN的隐层状态又相当于第三层RNN的输入,以此类推。

import tensorflow as tf
import numpy as np

# 每调用一次这个函数就返回一个BasicRNNCell
def get_a_cell():
    return tf.nn.rnn_cell.BasicRNNCell(num_units=128)
# 用tf.nn.rnn_cell MultiRNNCell创建3层RNN
cell = tf.nn.rnn_cell.MultiRNNCell([get_a_cell() for _ in range(3)]) # 3层RNN
# 得到的cell实际也是RNNCell的子类
# 它的state_size是(128, 128, 128)
# (128, 128, 128)并不是128x128x128的意思
# 而是表示共有3层RNN,每层RNN单元的个数为128
print(cell.state_size) # (128, 128, 128)
# 使用对应的call函数
inputs = tf.placeholder(np.float32, shape=(32, 100)) # 32 是 batch_size
h0 = cell.zero_state(32, np.float32) # 通过zero_state得到一个全0的初始状态
output, h1 = cell.__call__(inputs, h0)
print(h1) # tuple中含有3个32x128的向量,表示每层输出的隐层状态的shape是(32,128)

问题:为什么3层RNN每层都是128个单元,而每层的隐层输出都能是(batch_size, 128),层与层之间应该不是 全连接的。

参考博客:

TensorFlow中RNN实现的正确打开方式


    

    

    

猜你喜欢

转载自blog.csdn.net/qq_28808697/article/details/80646977