southdoor
southdoor

Reputation: 441

How to extract the shape value of a placeholder Tensor in Tensorflow?

I defined a x = tf.placeholder("float", shape=[None, 784]) for input data. Later on, I need to know the first value of the shape of x as batch size. And I extract the value by x.get_shape().as_list()[0] but I got None. Could you please tell me how should I extract it properly? Thanks a lot!

Edit:

I have used tf.get_shape() now but it cause another bug. In my code, I have defined a deconv funciton:

def deconv(X, W, b, output_shape):
    X += b 
    return tf.nn.conv2d_transpose(X, W, output_shape, strides=[1, 1, 1, 1])

If I set the batch_size to a int in such way: batch_size = 50, the calling of the deconv functions works well as following:

W_conv2_T = tf.ones([5, 5, 32, 64])
pool1_tr = deconv(conv2_tr, W_conv2_T, tf.zeros([64]), [batch_size, 14, 14, 32])

The shape of conv2_tr is [50, 14, 14, 64]. And the resulting shape of pool1_tr is [50, 14, 14, 32]. But if I set batch_size = tf.get_shape(x)[0], shape of conv2_tr is [None, 14, 14, 64] and the resulting shape of pool1_tr becomes [None, None, None, None]. This bug is so strange. Could you please help me with this issue? Thanks in advance!

Upvotes: 1

Views: 5620

Answers (1)

mrry
mrry

Reputation: 126154

A value of None for the number of rows in your placeholder means that it can vary at runtime, so you must use tf.shape(x) to get the shape as a tf.Tensor. The following code should work:

batch_size = tf.shape(x)[0]

Upvotes: 7

Related Questions