【问题标题】:"Tried to convert 'dim' to a tensor and failed" when using expand_dims使用 expand_dims 时,“尝试将 'dim' 转换为张量但失败了”
【发布时间】:2018-12-09 01:11:14
【问题描述】:

我希望下面的代码产生相应的张量

>>> A = tf.range(3)
>>> B = tf.tile(tf.expand_dims(A), [4,1])
>>> print(tf.Session().run(B))

[[0,1,2],
 [0,1,2],
 [0,1,2],
 [0,1,2]]

但是这会导致ValueError。重现问题的简单方法如下

>>> import tensorflow as tf
>>> x = tf.constant([0,1,2])
>>> y = tf.expand_dims(x)

ValueError: Tried to convert 'dim' to a tensor and failed. Error: None values not supported.

使用expand_dims 并避免此错误的正确方法是什么?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    看起来您需要为expand_dimsaxis 参数指定一个值。默认值为None,这似乎会导致您遇到错误。这有点奇怪,因为默认参数通常会导致某种合理的默认行为......也许这是一个错误。

    您的代码应该适用于y = tf.expand_dims(x, axis=0)。这将在您的示例中生成[1, 3] 的形状,允许您在之后进行平铺。另一个选项是y = x[tf.newaxis, :],它还添加了一个轴。

    【讨论】:

    • 我怀疑这可能是一个错误。我可以在 TF repo 上将它作为一个问题打开。也许expand_dims 即将被弃用,因为newaxis 是一种更“numpy”的做事方式。谢谢你的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    相关资源
    最近更新 更多