python - "Tried to convert ' 使用 expand_dims 时变暗 ' to a tensor and failed"

标签 python tensorflow

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

>>> 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_dimsaxis 参数指定一个值。默认值为 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/

相关文章:

python - 为什么这个操作在 CPU 上比在 GPU 上执行得更快?

python - Keras RNN 回归输入维度和架构

python - f 字符串十进制格式舍入

python - 没有重复的依赖装饰器

python - 手动停止由 mod_wsgi 启动的进程,并监控有多少进程正在运行

tensorflow - Transformer 培训如何实现教师强制?

python - 使用tensorflow对句子相似度建模

python - 矢量化数组 : construct matrix with 1 in specified places and 0 elsewhere

python - 复制的变量改变了原来的?

python - 如何为 Keras 实现 Beholder(Tensorboard 插件)?