Tensorflow: Reshape a 1-D tensor with given numbers of elements in each row

106 views Asked by At

I want to convert a 1-D tensor to 2-D shape in Tensorflow 2, with the number of elements in each row is given. I found a solution using the RaggedTensor like this

numbers = tf.constant([1,3,2,5,4])
c0 = tf.ones(shape=(15,)) # the tensor need to be reshape
rc0 = tf.RaggedTensor.from_row_lengths(values=c0, row_lengths=numbers)
c1 = rc0.to_tensor()

The final value of c1 should be

<tf.Tensor: shape=(5, 5), dtype=float32, numpy=
array([[1., 0., 0., 0., 0.],
       [1., 1., 1., 0., 0.],
       [1., 1., 0., 0., 0.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 0.]], dtype=float32)>

I found it refused to work when the size of the input tensor is large, and the performance is not good enough.

Is there any other high performance solution?

0

There are 0 answers