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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With