keras:未启用急切执行时,Tensor对象不可迭代

时间:2018-09-08 12:12:27

标签: python tensorflow machine-learning keras rnn

我正在Keras中编写一个Sequence to Sequence模型。由于某些原因,当我尝试在下面的函数中定义模型时:

def define_GRU_models(encoder_input_dim,
              output_dim,
              activation,
              n_units):
# define training encoder #
###########################
# layer 1
encoder_inputs = Input(shape=encoder_input_dim)
l1_encoder = GRU(n_units,
                      name='l1_encoder',
                      return_sequences=True,
                      return_state=True)
l1_encoder_outputs, l1_encoder_state = l1_encoder(encoder_inputs)

# layer 2
l2_encoder = GRU(n_units,
                      name='l2_encoder',
                      return_state=True)
l2_encoder_outputs, l2_encoder_state = l2_encoder(l1_encoder_outputs)

# define training decoder #
###########################

# layer 1
decoder_inputs = Input(shape=(None, output_dim))
l1_decoder_gru = GRU(int(n_units/2),
                          name='l1_decoder_gru',
                          return_sequences=True,
                          return_state=False)
l1_decoder_outputs, _ = l1_decoder_gru(decoder_inputs)

# layer 2
l2_decoder_gru = GRU(n_units,
                          name='l2_decoder_gru',
                          return_sequences=True,
                          return_state=False)
l2_decoder_outputs, _ = l2_decoder_gru(l1_decoder_outputs, initial_state=l1_encoder_state)

# layer 3
l3_decoder_gru = GRU(n_units,
                          name='l3_decoder_gru',
                          return_sequences=True,
                          return_state=False)
l3_decoder_outputs, _ = l3_decoder_gru(l2_decoder_outputs, initial_state=l2_encoder_state)

# layer 4
l4_decoder_gru = GRU(int(n_units/2),
                          name='l4_decoder_gru',
                          return_state=False                              )
l4_decoder_outputs, _ = l4_decoder_gru(l3_decoder_outputs)

decoder_dense = Dense(output_dim, name='decoder_dense', activation=activation)
decoder_outputs = decoder_dense(l4_decoder_outputs)
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)

return model

我遇到此错误:

Tensor objects are not iterable when eager execution is not enabled. To iterate over this tensor use tf.map_fn.

此行(第一解码器层):

l1_decoder_outputs, _ = l1_decoder_gru(decoder_inputs)

我似乎在任何其他地方都找不到解决方案。我究竟做错了什么?因为它似乎与keras示例兼容。

顺便说一句, 我的功能输入是:

(168, 12), 24, 'softmax', 128

1 个答案:

答案 0 :(得分:1)

问题是'l1_decoder_gru'不返回其状态(即return_state=False)。它只有一个分配给l1_decoder_outputs的输出张量。因此,要解决此问题,请删除作业左侧的, _部分:

l1_decoder_outputs = l1_decoder_gru(decoder_inputs)

或者,您也可以将return_state层的True参数设置为'l1_decoder_gru'(当然,如果这样做有意义,并且您可能需要在另一部分中使用该层的状态您的模型)。这同样适用于您在模型中定义和使用的其他GRU层。