且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Tensorflow Keras不适用于参差不齐的张量输入

更新时间:2023-12-03 11:22:40

在我看来像是个错误,因为对Keras的RaggedTensor支持不是***的(请参见例如

Looks like a bug to me because the RaggedTensor support for Keras isn't the best (see e.g. here). I'm not exactly sure what is causing it but the ragged conversion is failing for the placeholders.

如果可以的话,***先使用所有RaggedTensor功能 ,然后再将其作为输入并设置ragged=False.如果您只想使用它进行方便的填充,并且所有图形操作都基于无参差的张量(在您的示例中就是这种情况),则这不是问题:

If you can, it's probably best to use all RaggedTensor functionality before passing it as an input and setting ragged=False. This is not an issue if you only want to use it for convenient padding and if all graph operations are based on non-ragged tensors (which is the case for your example):

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)