【问题标题】:How to concatenate two tensors horizontally in TensorFlow?如何在 TensorFlow 中水平连接两个张量?
【发布时间】:2017-04-13 01:43:55
【问题描述】:

我有 2 个形状张量 (100, 4)(100, 2)。 我想在 TensorFlow 中执行连接操作,类似于在 NumPy 中的np.hstack,以便输出的形状为(100, 6)。有没有 TensorFlow 函数可以做到这一点?

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    您可以按如下方式使用tf.concat

    sess=tf.Session()
    t1 = [[1, 2], [4, 5]]
    t2 = [[7, 8, 9], [10, 11, 12]]
    res=tf.concat(concat_dim=1,values=[t1, t2])
    print(res.eval(session=sess))
    

    打印出来

    [[ 1  2  7  8  9]
     [ 4  5 10 11 12]]
    

    【讨论】:

    • 有没有办法在不使用 tf.concat() 的情况下连接张量?
    • @Pototo 在某些情况下可以使用tf.stack()
    • 批量大小是否被视为第一维度?看起来 API 也发生了变化tensorflow.org/api_docs/python/tf/concat
    • 现在是(我使用的是 TF 版本 1.6.0):axis=1not concat_dim=1
    【解决方案2】:

    我尝试了上面的代码,我得到了一些错误。以下代码在 tf 1.15 版本下运行良好:

    x = tf.constant( [[1, 2,4],[7,8,12]])
    

    y = tf.constant([[88],[99]])

    res=tf.concat([x, y],1)
    

    【讨论】:

      【解决方案3】:

      我也有类似的问题。我尝试将两个图像张量与 Keras 连接起来。 Tensor type and shape 两者是相同的,但它表示 Layer concatenate_X(数字 X 的变化)是使用不是符号张量的输入调用的。接收类型: 我尝试像这样连接它们:

      X=concatenate([X1,X2],axis=-1)
      

      【讨论】:

        【解决方案4】:

        在 PyTorch 中有一种更简单的方法。假设 t1 是您的 100x4 张量,而 t2 是 100x2 张量。您可以执行以下操作:

        result= torch.concat((t1,t2), axis=1)
        

        结果是一个 100x6 的张量。

        【讨论】:

        • 此解决方案适用于 PyTorch。 OP 正在寻求 TensorFlow 中的解决方案。
        • 哦,好的,感谢您指出。我已经编辑了我的答案。
        猜你喜欢
        • 2017-08-20
        • 1970-01-01
        • 2021-11-20
        • 2012-03-29
        • 2020-09-26
        • 2019-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多