1
votes

I have a tensor representing an embedding and I want to reshape it but it fails with the following error:

TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

The code that I use for reshaping:

embedding_feature = \
    Reshape((tf.shape(embedding_feature)[0],
             10, 20, tf.shape(embedding_feature)[2])) \
        (embedding_feature)

and the embedding_feature:

Tensor("tags_embedding/GatherV2:0", shape=(?, 200, 60), dtype=float32)

I am using tf.shape() to capture the dynamic shape of the tensor as explained in other questions here:

https://github.com/tensorflow/tensorflow/issues/7253

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

Full traceback:

Traceback (most recent call last):
  File "/usr/lib/python3.6/contextlib.py", line 99, in __exit__
    self.gen.throw(type, value, traceback)
  File "/home/eleni/Desktop/recommender/recommender/venv/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 5285, in get_controller
    yield g
  File "/home/eleni/Desktop/recommender/recommender/venv/lib/python3.6/site-packages/keras/engine/topology.py", line 622, in __call__
    output_shape = self.compute_output_shape(input_shape)
  File "/home/eleni/Desktop/recommender/recommender/venv/lib/python3.6/site-packages/keras/layers/core.py", line 390, in compute_output_shape
    input_shape[1:], self.target_shape)
  File "/home/eleni/Desktop/recommender/recommender/venv/lib/python3.6/site-packages/keras/layers/core.py", line 364, in _fix_unknown_dimension
    if dim < 0:
  File "/home/eleni/Desktop/recommender/recommender/venv/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 665, in __bool__
    raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

How can I fix this ?

1
It's not clear when/where the error is happening at a glance. Could you add full traceback? - Paritosh Singh

1 Answers

1
votes

The Reshape layer requires a tuple of integers as input (also, the dimensions given to the layer should not include the batch dimension). If you want to reshape to a shape not known in advance, use a Lambda layer:

from keras.layers import Lambda
import keras.backend as K

# ...
embedding_feature = Lambda(
     lambda x: K.reshape(x, [K.shape(x)[0], 10, 20, K.shape(x)[2]]))(embedding_feature)