首页 文章

如何使用TensorFlow堆叠LSTM图层

提问于
浏览
3

我所拥有的是以下内容,我认为这是一个具有一个隐藏LSTM层的网络:

# Parameters
learning rate = 0.001
training_iters = 100000
batch_size = 128
display_step = 10

# Network Parameters
n_input = 13
n_steps = 10
n_hidden = 512
n_classes = 13

# tf Graph input
x = tf.placeholder("float", [None, n_steps, n_input])
y = tf.placeholder("float", [None, n_classes])

# Define weights
weights = {
    'out' : tf.Variable(tf.random_normal([n_hidden, n_classes]))
}
biases = {
    'out' : tf.Variable(tf.random_normal([n_classes]))
}

但是,我正在尝试使用TensorFlow构建LSTM网络来预测功耗 . 我一直在寻找一个很好的例子,但我找不到任何带有2个隐藏LSTM层的模型 . 这是我想要构建的模型:

1个输入层,1个输出层,2个隐藏的LSTM层(每个中有512个神经元),时间步长(序列长度):10

任何人都可以指导我使用TensorFlow构建它吗? (从定义权重,构建输入形状,培训,预测,使用优化器或成本函数等),任何帮助将非常感激 .

非常感谢你提前!

2 回答

  • 2

    以下是我在使用GRU单元格的翻译模型中的操作方法 . 您只需用LSTM替换GRU即可 . 只需使用tf.nn.rnn_cell.MultiRNNCell,它应该包含多个单元格的列表 . 在下面的代码中,我手动展开它,但您也可以将它传递给 tf.nn.dynamic_rnntf.nn.rnn .

    y = input_tensor
    with tf.variable_scope('encoder') as scope:
        rnn_cell = rnn.MultiRNNCell([rnn.GRUCell(1024) for _ in range(3)])
        state = tf.zeros((BATCH_SIZE, rnn_cell.state_size))
        output = [None] * TIME_STEPS
        for t in reversed(range(TIME_STEPS)):
            y_t = tf.reshape(y[:, t, :], (BATCH_SIZE, -1))
            output[t], state = rnn_cell(y_t, state)
            scope.reuse_variables()
        y = tf.pack(output, 1)
    
  • 5

    首先,您需要一些占位符来放置您的培训数据(一批)

    x_input = tf.placeholder(tf.float32, [batch_size, truncated_series_length, 1])
    y_output = tf.placeholder(tf.float32, [batch_size, truncated_series_length, 1])
    

    LSTM需要一个状态,它由两个组成部分组成,隐藏状态和单元状态,非常好的指南:https://arxiv.org/pdf/1506.00019.pdf . 对于LSTM中的每个层,您都有一个单元状态和一个隐藏状态 .

    问题是Tensorflow将其存储在LSTMStateTuple中,您无法将其发送到占位符 . 所以你需要将它存储在Tensor中,然后将其解压缩为一个元组:

    state_placeholder = tf.placeholder(tf.float32, [num_layers, 2, batch_size, state_size])
    
    l = tf.unpack(state_placeholder, axis=0)
    rnn_tuple_state = tuple(
        [tf.nn.rnn_cell.LSTMStateTuple(l[idx][0], l[idx][1])
         for idx in range(num_layers)]
    )
    

    然后,您可以使用内置的Tensorflow API创建堆叠的LSTM图层 .

    cell = tf.nn.rnn_cell.LSTMCell(state_size, state_is_tuple=True)
    cell = tf.nn.rnn_cell.MultiRNNCell([cell]*num_layers, state_is_tuple=True)
    outputs, state = tf.nn.dynamic_rnn(cell, x_input, initial_state=rnn_tuple_state)
    

    从这里继续输出以计算logits,然后相对于 y_inputs 的损失 .

    然后使用 sess.run -command运行每个批处理,并使用截断的反向传播(这里有很好的解释http://r2rt.com/styles-of-truncated-backpropagation.html

    init_state = np.zeros((num_layers, 2, batch_size, state_size))
    
    ...current_state... = sess.run([...state...], feed_dict={x_input:batch_in, state_placeholder:current_state ...})
    current_state = np.array(current_state)
    

    在再次进给之前,您必须将状态转换为 numpy 数组 .

    也许最好使用像Tflearn或Keras这样的图书馆?

相关问题