Tensorflow - pad tensor with unknown shape

I'm trying to pad a tensor with unknown shape (but fixed rank) to a fixed shape in my Keras model. The tensor is of type string, so I cannot use tf.keras.preprocessing.sequence.pad_sequences or tf.image.pad_to_bounding_box.

I want to use tf.pad, but the problem is that I don't know the shape of the tensor, so I have to dynamically compute the padding length. How can I do that?

My current approach is like this, which doesn't work:

def pad_to_length(t: tf.Tensor, target_length: int):
    return tf.pad(t, [0, target_length-t.shape[0]], 'REFLECT')

Because t can have dynamic shape, t.shape will be (None,), so I got the error: TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'

1 answer

  • answered 2022-01-18 16:21 Alexey Tochin

    Use dynamic shape tf.shape instead of static shape .shape like

    def pad_to_length(t: tf.Tensor, target_length: int):
        return tf.pad(t, [[0, target_length - tf.shape(t)[0]]], 'REFLECT')
    

    for tensors t of rank 1.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum