【发布时间】:2020-11-17 11:06:17
【问题描述】:
假设我有两个不同(重要)长度的 1 级张量:
import tensorflow as tf
x = tf.constant([1, 2, 3])
y = tf.constant([4, 5])
现在我想将 y 附加到 x 的末尾以给我张量:
<tf.Tensor: shape=(5,), dtype=int32, numpy=array([1, 2, 3, 4, 5], dtype=int32)>
但我似乎无法弄清楚如何。
我将在一个函数中执行此操作,我将使用 tf.function 进行装饰,我的理解是一切都需要 tensorflow 操作才能使 tf.function 装饰器工作。也就是说,将 x 和 y 转换为 numpy 数组再转换回张量会导致问题。
谢谢!
编辑:
解决方案是使用@Andrey 指出的 tf.concat() :
tf.concat([x, y], axis=0)
事实证明,问题是在尝试将单个数字附加到 1 阶张量的末尾时产生的,如下所示:
x = tf.constant([1, 2, 3])
y = tf.constant(5)
tf.concat([x, y], axis=0)
失败,因为这里 y 是形状 () 的 0 阶张量。这可以通过写来解决:
x = tf.constant([1, 2, 3])
y = tf.constant([5])
tf.concat([x, y], axis=0)
因为 y 将是形状为 (1,) 的 1 阶张量。
【问题讨论】:
标签: python tensorflow keras deep-learning tensor