Tensorflow Keras não funciona com entrada de tensor irregular

Sep 11 2020

Estou usando o Tensorflow 2.3.

Se eu usar uma entrada de tensor tf normal, o exemplo abaixo funciona bem:

import tensorflow as tf
text_input = tf.keras.Input([None], dtype=tf.string, name="text_input", ragged=False)
predictions = tf.gather(text_input, 0, axis=-1)
model = tf.keras.Model(inputs=[text_input], outputs=[predictions])
model(tf.constant([['A1', 'A2', 'A3'], ['B1', 'B2', 'B3']]))

<tf.Tensor: shape=(2,), dtype=string, numpy=array([b'A1', b'B1'], dtype=object)>

No entanto, se eu alterar a entrada para um tensor irregular, recebo um erro ao tentar criar o modelo.

import tensorflow as tf
ragged_input = tf.keras.Input([None], dtype=tf.string, name="ragged_input", ragged=True)
padded_input = ragged_input.to_tensor('')
predictions = tf.gather(padded_input, 0, axis=-1)
model = tf.keras.Model(inputs=[ragged_input], outputs=[predictions])

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-201-9adaf4aae2b5> in <module>()
      3 padded_input = ragged_input.to_tensor('')
      4 predictions = tf.gather(padded_input, 0, axis=-1)
----> 5 model = tf.keras.Model(inputs=[ragged_input], outputs=[predictions])

13 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     58     ctx.ensure_initialized()
     59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 60                                         inputs, attrs, num_outputs)
     61   except core._NotOkStatusException as e:
     62     if name is not None:

InvalidArgumentError:  You must feed a value for placeholder tensor 'Placeholder_38' with dtype int64 and shape [?]
     [[node Placeholder_38 (defined at <ipython-input-201-9adaf4aae2b5>:5) ]] [Op:__inference_keras_scratch_graph_136790]

Function call stack:
keras_scratch_graph

Respostas

2 runDOSrun Sep 11 2020 at 12:14

Parece um bug para mim porque o RaggedTensorsuporte para Keras não é o melhor (veja por exemplo aqui ). Não tenho certeza do que está causando isso, mas a conversão irregular está falhando para os espaços reservados.

Se você puder, provavelmente é melhor usar todas as RaggedTensorfuncionalidades antes de passá-las como uma entrada e configuração ragged=False. Isso não é um problema se você deseja usá-lo apenas para preenchimento conveniente e se todas as operações de gráfico são baseadas em tensores não irregulares (que é o caso do seu exemplo):

import tensorflow as tf
ragged_input = tf.keras.Input([None], dtype=tf.string, name="ragged_input", ragged=False)
# padded_input = ragged_input.to_tensor('')
predictions = tf.gather(ragged_input, 0, axis=-1)

model = tf.keras.Model(inputs=[ragged_input], outputs=[predictions])
padded_input = tf.ragged.constant([['A1', 'A2'], ['B1', 'B2', 'B3']]).to_tensor('')
result = model(padded_input)
print(result)
# >>> tf.Tensor([b'A1' b'B1'], shape=(2,), dtype=string)