【问题标题】:Convert BasicLSTMCell to bidirectional LSTM将 BasicLSTMCell 转换为双向 LSTM
【发布时间】:2021-01-13 08:30:53
【问题描述】:

最近我尝试使用 Tensorflow 的 BasicLSTMCell api 来生成视频字幕。我正在使用以下方式构建 BasicLSTMCell 的代码:

self.lstm1 = tf.compat.v1.nn.rnn_cell.BasicLSTMCell(dim_hidden, state_is_tuple=False)
self.lstm2 = tf.compat.v1.nn.rnn_cell.BasicLSTMCell(dim_hidden, state_is_tuple=False)

以后再使用如下:

with tf.compat.v1.variable_scope("Encoding") as scope:  
      for i in range(0, self.n_video_lstm_step):
          if i > 0:
              scope.reuse_variables()

          with tf.compat.v1.variable_scope("LSTM1"):
              output1, state1 = self.lstm1(image_emb[:,i,:], state1)

          with tf.compat.v1.variable_scope("LSTM2"):
              output2, state2 = self.lstm2(tf.concat([padding, output1], 1), state2)
  
          out_list.append(tf.concat([output1, output2], 1))
     

我希望这些 LSTM 单元是双向的以满足我的要求。我尝试过使用

keras.layers.Bidirectional(keras.layers.LSTM(dim_hidden, unit_forget_bias=True, unroll=True))

但它没有用。谁能告诉我如何使它与双向 lstm 一起工作。

【问题讨论】:

  • 澄清一下,您是要在 Keras 中的现有 LSTM 实现上使用双向包装器,还是要创建 LSTM 单元

标签: python tensorflow keras lstm bidirectional


【解决方案1】:

根据您提出的问题,Convert BasicLSTMCell to bidirectional LSTM - 您可以直接使用双向 RNN 包装器,如下面的代码所示。请澄清您如何修改导致您面临的错误的 LSTM 层类。我会相应地更新我的答案。

import numpy as np
from tensorflow.keras import layers, Model, utils

X = np.random.random((100,10,3))
y = np.random.random((100,))

inp = layers.Input((10,3))
x = layers.Bidirectional(layers.LSTM(8, return_sequences=True))(inp)
x = layers.Bidirectional(layers.LSTM(8))(x)
out = layers.Dense(1, activation='softmax')(x)

model = Model(inp, out)
utils.plot_model(model, show_layer_names=False, show_shapes=True)

model.compile(optimizer='adam', loss='binary_crossentropy')
model.fit(X, y, epochs=3)
Epoch 1/3
4/4 [==============================] - 5s 10ms/step - loss: 0.6963
Epoch 2/3
4/4 [==============================] - 0s 22ms/step - loss: 0.6965
Epoch 3/3
4/4 [==============================] - 0s 11ms/step - loss: 0.6976
<tensorflow.python.keras.callbacks.History at 0x7f91066bf4c0>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2018-06-29
    • 2019-05-08
    相关资源
    最近更新 更多