【问题标题】:Tensorflow Reshape fails with TypeError: Using a `tf.Tensor` as a Python `bool` is not allowedTensorflow Reshape 因 TypeError 失败:不允许使用 `tf.Tensor` 作为 Python `bool`
【发布时间】:2020-03-18 13:12:03
【问题描述】:

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

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.

我该如何解决这个问题?

【问题讨论】:

  • 一目了然,并不清楚错误发生的时间/地点。你能添加完整的回溯吗?

标签: python tensorflow keras


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 2018-03-20
    • 2018-08-17
    • 1970-01-01
    • 2020-03-11
    • 2021-04-18
    • 2020-05-04
    相关资源
    最近更新 更多