【问题标题】:How to append rank 1 tensors using only tensorflow operations?如何仅使用 tensorflow 操作附加 1 级张量?
【发布时间】: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


    【解决方案1】:

    使用tf.concat():

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

    【讨论】:

    • 谢谢@Andrey!起初我尝试了 tf.concat,但我现在意识到真正的问题出在哪里。将在原始帖子中进行编辑和澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多