Слой внимания Keras от последовательности к модели последовательности TypeError: невозможно выполнить итерацию по тензору с неизвестным первым измерением - PullRequest
1 голос
/ 06 августа 2020

Я использую Tensorflow 2.1.1 и пытаюсь построить последовательность для модели последовательности с Attention.

latent_dim = 300
embedding_dim=100
batch_size  = 128

# Encoder
encoder_inputs = tf.keras.Input(shape=(None,), dtype='int32')

#embedding layer
enc_emb =  tf.keras.layers.Embedding(x_voc, embedding_dim,trainable=True)(encoder_inputs)

#encoder lstm 1
encoder_lstm = tf.keras.layers.LSTM(latent_dim,return_sequences=True,return_state=True,dropout=0.4,recurrent_dropout=0.4)
encoder_output, state_h, state_c = encoder_lstm(enc_emb)
print(encoder_output.shape)

# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = tf.keras.Input(shape=(None,), dtype='int32')

#embedding layer
dec_emb_layer = tf.keras.layers.Embedding(y_voc, embedding_dim,trainable=True)
dec_emb = dec_emb_layer(decoder_inputs)

decoder_lstm = tf.keras.layers.LSTM(latent_dim, return_sequences=True, return_state=True,dropout=0.4,recurrent_dropout=0.2)
decoder_output,decoder_fwd_state, decoder_back_state = decoder_lstm(dec_emb,initial_state=[state_h, state_c])

# Attention layer
attn_out, attn_states = tf.keras.layers.Attention()([encoder_output, decoder_output])

# Concat attention input and decoder LSTM output
decoder_concat_input = tf.keras.layers.Concatenate(axis=-1, name='concat_layer')([decoder_output, attn_out])

#dense layer
decoder_dense =  tf.keras.layers.TimeDistributed(Dense(y_voc, activation='softmax'))
decoder_outputs = decoder_dense(decoder_concat_input)

# Define the model 
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)

model.summary()

Когда я запускаю это, я получаю ошибку при создании уровня Attention TypeError: Cannot iterate over a tensor with unknown first dimension..

Я проверил размеры encoder_output и decoder_output, и они оба (None, None, 300), так что подумал, что это может быть проблемой. Но я проверил пример «Внимание» из примера тензорного потока , и у них также есть размер None для своих входных параметров слоя внимания.

Интересно, что мне тогда не хватает? Пожалуйста, предложите.

EDIT

Добавление трассировки стека

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-d37cd48e626b> in <module>()
     28 
     29 # Attention layer
---> 30 attn_out, attn_states = tf.keras.layers.Attention()([encoder_output, decoder_output])
     31 
     32 # Concat attention input and decoder LSTM output

~/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py in __iter__(self)
    546     if shape[0] is None:
    547       raise TypeError(
--> 548           "Cannot iterate over a tensor with unknown first dimension.")
    549     for i in xrange(shape[0]):
    550       yield self[i]

TypeError: Cannot iterate over a tensor with unknown first dimension.

1 Ответ

1 голос
/ 07 августа 2020

ошибка из-за того, что keras Attention выводит 1 тензор, пока вы ожидаете 2. вам нужно изменить

attn_out, attn_states = tf.keras.layers.Attention()([encoder_output, decoder_output])

на

attn_out = tf.keras.layers.Attention()([encoder_output, decoder_output])

здесь полная модель

# Encoder
encoder_inputs = tf.keras.Input(shape=(None,), dtype='int32')

#embedding layer
enc_emb =  tf.keras.layers.Embedding(x_voc, embedding_dim)(encoder_inputs)

#encoder lstm 1
encoder_lstm = tf.keras.layers.LSTM(latent_dim, return_sequences=True,return_state=True)
encoder_output, state_h, state_c = encoder_lstm(enc_emb)

# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = tf.keras.Input(shape=(None,), dtype='int32')

#embedding layer
dec_emb = tf.keras.layers.Embedding(y_voc, embedding_dim)(decoder_inputs)

decoder_lstm = tf.keras.layers.LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_output,decoder_fwd_state,decoder_back_state = decoder_lstm(dec_emb,initial_state=[state_h, state_c])

# Attention layer
attn_out = tf.keras.layers.Attention()([encoder_output, decoder_output])

# Concat attention input and decoder LSTM output
decoder_concat_input = tf.keras.layers.Concatenate(axis=-1, name='concat_layer')([decoder_output, attn_out])

#dense layer
decoder_dense =  tf.keras.layers.TimeDistributed(Dense(y_voc, activation='softmax'))
decoder_outputs = decoder_dense(decoder_concat_input)

# Define the model 
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)

model.summary()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...