Tensorflow重塑失败并出现TypeError:不允许将tf.Tensor作为Python bool使用

时间:2019-11-22 12:50:03

标签: python tensorflow keras

我有一个表示嵌入的张量,我想对其重塑形状,但是它失败并出现以下错误:

  

TypeError:不允许将tf.Tensor用作Python bool。采用   if t is not None:代替if t:来测试是否定义了张量,   并使用tf.cond等TensorFlow操作来执行子图   以张量的值为条件。

我用于重塑的代码:

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

和embedding_feature:

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

我正在使用tf.shape()来捕获张量的动态形状,如此处其他问题所述:

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

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

完整追溯:

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.

我该如何解决?

1 个答案:

答案 0 :(得分:0)

Reshape层需要一个整数元组作为输入(同样,赋予该层的尺寸不应包含批处理尺寸)。如果要重塑为事先未知的形状,请使用Lambda层:

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)