Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tf.reshape is not giving ?(None) for first element

I am new to tensorflow, I have tensor like below,

a = tf.constant([[1, 2, 3], [4, 5, 6]])

Output of a.shape is

TensorShape([Dimension(2), Dimension(3)])

For my computational process I want to reshape the tensor to (?, 2, 3)

I am unable to reshape it to desire format.

I tried,

tf.reshape(a, [-1, 2, 3])

But it returns,

<tf.Tensor 'Reshape_18:0' shape=(1, 2, 3) dtype=int32> # 1 has to be replaced by ?

further I tried,

tf.reshape(a, [-1, -1, 2, 3])

it returns,

<tf.Tensor 'Reshape_19:0' shape=(?, ?, 2, 3) dtype=int32> # two ? are there

How do I get the desired result?

Sorry if it sounds simple problem.

like image 965
Mohamed Thasin ah Avatar asked Nov 06 '22 12:11

Mohamed Thasin ah


1 Answers

The "problem" is TensorFlow does as much shape inference as it can, which is generally something good, but it makes it more complicated if you explicitly want to have a None dimension. Not an ideal solution, but one possible workaround is to use a tf.placeholder_with_default, for example like this:

import tensorflow as tf

a = tf.constant([[1, 2, 3], [4, 5, 6]])
# This placeholder is never actually fed
z = tf.placeholder_with_default(tf.zeros([1, 1, 1], a.dtype), [None, 1, 1])
b = a + z
print(b)
# Tensor("add:0", shape=(?, 2, 3), dtype=int32)

Or another similar option, just with reshaping:

import tensorflow as tf

a = tf.constant([[1, 2, 3], [4, 5, 6]])
s = tf.placeholder_with_default([1, int(a.shape[0]), int(a.shape[1])], [3])
b = tf.reshape(a, s)
b.set_shape(tf.TensorShape([None]).concatenate(a.shape))
print(b)
# Tensor("Reshape:0", shape=(?, 2, 3), dtype=int32)
like image 118
jdehesa Avatar answered Nov 15 '22 12:11

jdehesa