我希望以下代码生成相应的张量
>>> 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
并避免此错误的正确方法是什么?
1 回答
看起来你需要为
expand_dims
的axis
参数指定一个值 . 默认值为None
,这似乎会导致您获得的错误 . 这有点奇怪,因为默认参数通常应该导致某种合理的默认行为...也许这是一个错误 .您的代码应该与
y = tf.expand_dims(x, axis=0)
一起使用 . 在您的示例中,这将导致[1, 3]
的形状,允许您在之后平铺 . 另一种选择是y = x[tf.newaxis, :]
,它也增加了一个轴 .