我希望下面的代码产生相应的张量
>>> 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
并避免此错误的正确方法是什么?
最佳答案
看起来您需要为 expand_dims
的 axis
参数指定一个值。默认值为 None
,这似乎会导致您收到错误。这有点奇怪,因为默认参数通常会导致某种合理的默认行为……也许这是一个错误。
您的代码应该适用于 y = tf.expand_dims(x, axis=0)
。这将在您的示例中生成 [1, 3]
的形状,允许您之后平铺。另一种选择是 y = x[tf.newaxis, :]
,它也添加了一个轴。
关于python - "Tried to convert ' 使用 expand_dims 时变暗 ' to a tensor and failed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53688537/