繁体   English   中英

如何仅使用张量流操作附加等级 1 张量?

[英]How to append rank 1 tensors using only tensorflow operations?

假设我有两个不同(重要)长度的 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 阶张量。

使用tf.concat()

import tensorflow as tf
t1 = tf.constant([1, 2, 3])
t2 = tf.constant([4, 5])
output = tf.concat([t1, t2], 0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM