Deep learning 在TensorFlow中合并多个模型(LSTM)

Deep learning 在TensorFlow中合并多个模型(LSTM),deep-learning,tensorflow,keras,Deep Learning,Tensorflow,Keras,我知道如何在Keras中将不同的模型合并为一个 first_model = Sequential() first_model.add(LSTM(output_dim, input_shape=(m, input_dim))) second_model = Sequential() second_model.add(LSTM(output_dim, input_shape=(n-m, input_dim))) model = Sequential() model.add(Merge([firs

我知道如何在Keras中将不同的模型合并为一个

first_model = Sequential()
first_model.add(LSTM(output_dim, input_shape=(m, input_dim)))

second_model = Sequential()
second_model.add(LSTM(output_dim, input_shape=(n-m, input_dim)))

model = Sequential()
model.add(Merge([first_model, second_model], mode='concat'))
model.fit([X1,X2])
我不知道如何在TensorFlow中实现这一点

我有两个LSTM模型,希望合并它们(与上面的Keras示例中的方式相同)


任何帮助都将不胜感激

正如评论中所说,我认为最简单的方法就是将输出连接起来。我发现的唯一复杂之处是,至少我是如何制作我的LSTM层的,它们的重量张量的名称完全相同。这导致了一个错误,因为当我尝试制作第二层时,TensorFlow认为权重已经制作好了。如果存在此问题,可以使用变量范围解决,该变量范围将应用于该LSTM层中张量的名称:

with tf.variable_scope("LSTM_1"):
    lstm_cells_1 = tf.contrib.rnn.MultiRNNCell(tf.contrib.rnn.LSTMCell(256))
    output_1, state_1 = tf.nn.dynamic_rnn(lstm_cells_1, inputs_1)
    last_output_1 = output_1[:, -1, :]
# I usually work with the last one; you can keep them all, if you want

with tf.variable_scope("LSTM_2"):
    lstm_cells_2 = tf.contrib.rnn.MultiRNNCell(tf.contrib.rnn.LSTMCell(256))
    output_2, state_2 = tf.nn.dynamic_rnn(lstm_cells_2, inputs_2)
    last_output_2 = output_2[:, -1, :]

merged = tf.concat((last_output_1, last_output_2), axis=1)

正如在评论中所说的,我认为实现这一点最简单的方法就是连接输出。我发现的唯一复杂之处是,至少我是如何制作我的LSTM层的,它们的重量张量的名称完全相同。这导致了一个错误,因为当我尝试制作第二层时,TensorFlow认为权重已经制作好了。如果存在此问题,可以使用变量范围解决,该变量范围将应用于该LSTM层中张量的名称:

with tf.variable_scope("LSTM_1"):
    lstm_cells_1 = tf.contrib.rnn.MultiRNNCell(tf.contrib.rnn.LSTMCell(256))
    output_1, state_1 = tf.nn.dynamic_rnn(lstm_cells_1, inputs_1)
    last_output_1 = output_1[:, -1, :]
# I usually work with the last one; you can keep them all, if you want

with tf.variable_scope("LSTM_2"):
    lstm_cells_2 = tf.contrib.rnn.MultiRNNCell(tf.contrib.rnn.LSTMCell(256))
    output_2, state_2 = tf.nn.dynamic_rnn(lstm_cells_2, inputs_2)
    last_output_2 = output_2[:, -1, :]

merged = tf.concat((last_output_1, last_output_2), axis=1)

看起来keras只是将两个张量串联起来,所以假设它们具有相同的形状,您应该可以只调用Tensorflower.concat(outputs_1,outputs_2)等看起来keras只是将两个张量串联起来,所以假设它们具有相同的形状,您应该可以只调用Tensorflower.concat(输出_1、输出_2)等