Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reshape a tensor with multiple `None` dimensions?

I encountered a problem to reshape an intermediate 4D tensorflow tensor X to a 3D tensor Y, where

  • X is of shape ( batch_size, nb_rows, nb_cols, nb_filters )
  • Y is of shape ( batch_size, nb_rows*nb_cols, nb_filters )
  • batch_size = None

Of course, when nb_rows and nb_cols are known integers, I can reshape X without any problem. However, in my application I need to deal with the case

nb_rows = nb_cols = None

What should I do? I tried Y = tf.reshape( X, (-1, -1, nb_filters)) but it clearly fails to work.

For me, this operation is deterministic because it always squeezes the two middle axes into a single one while keeping the first axis and the last axis unchanged. Can anyone help me?

like image 495
pitfall Avatar asked Oct 31 '17 00:10

pitfall


People also ask

How do you flatten a Tensorflow tensor?

To flatten the tensor, we're going to use the TensorFlow reshape operation. So tf. reshape, we pass in our tensor currently represented by tf_initial_tensor_constant, and then the shape that we're going to give it is a -1 inside of a Python list.


1 Answers

In this case you can access to the dynamic shape of X through tf.shape(X):

shape = [tf.shape(X)[k] for k in range(4)]
Y = tf.reshape(X, [shape[0], shape[1]*shape[2], shape[3]])
like image 128
Anthony D'Amato Avatar answered Oct 16 '22 13:10

Anthony D'Amato