Mohamed Thasin ah
Mohamed Thasin ah

Reputation: 11192

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.

Upvotes: 5

Views: 801

Answers (2)

Dejvovo
Dejvovo

Reputation: 129

The task you are trying to achieve is fundamentally wrong. You are trying to make a Partially-known shape from Fully-known shape, see the documentation.

The partially-known shapes are used, when you don't know the fully-known shape during the graph construction. Anyway, you have to specify the actual shape when executing the graph. Therefore, it doesn't make sense to convert any tensor with fully-known shape to the partially-known one.

If you want to perform an operation on some partially-known shape, use broadcasting (e.g. add operation on tensors with shape (1, 2, 3) and (None, 2, 3) results in a tensor of shape (None, 2, 3))

Upvotes: 0

javidcf
javidcf

Reputation: 59681

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)

Upvotes: 1

Related Questions