【问题标题】:Counterpart of hstack and vstack in TensorflowTensorflow 中 hstack 和 vstack 的对应物
【发布时间】:2019-03-11 10:03:01
【问题描述】:

Tensorflow 中的 numpy 函数 hstackvstack 的正确对应物是什么?

Tensorflow 中有tf.stacktf.concat,但我不知道如何使用它们或使用正确的axis 值,以在Tensorflow 中实现相同的行为。

【问题讨论】:

  • 查看hstackvstack的代码,看看他们做了哪些尺寸调整。

标签: python-3.x numpy tensorflow


【解决方案1】:

您应该使用tf.concat 和不同的axis 参数来获得与hstackvstack 相同的结果:

arr1 = np.random.random((2,3))
arr2 = np.random.random((2,3))
arr1
array([[0.72315241, 0.9374959 , 0.18808236],
       [0.74153715, 0.85361367, 0.13258545]])

arr2
array([[0.80159933, 0.8123236 , 0.80555496],
       [0.82570606, 0.4092662 , 0.69123989]])

np.hstack([arr1, arr2])
array([[0.72315241, 0.9374959 , 0.18808236, 0.80159933, 0.8123236 ,
        0.80555496],
       [0.74153715, 0.85361367, 0.13258545, 0.82570606, 0.4092662 ,
        0.69123989]])

np.hstack([arr1, arr2]).shape
(2, 6)

np.vstack([arr1, arr2])
array([[0.72315241, 0.9374959 , 0.18808236],
       [0.74153715, 0.85361367, 0.13258545],
       [0.80159933, 0.8123236 , 0.80555496],
       [0.82570606, 0.4092662 , 0.69123989]])

np.vstack([arr1, arr2]).shape
(4, 3)

t1 = tf.convert_to_tensor(arr1)
t2 = tf.convert_to_tensor(arr2)


tf.concat([t1, t2], axis=1)

<tf.Tensor: id=9, shape=(2, 6), dtype=float64, numpy=
array([[0.72315241, 0.9374959 , 0.18808236, 0.80159933, 0.8123236 ,
        0.80555496],
       [0.74153715, 0.85361367, 0.13258545, 0.82570606, 0.4092662 ,
        0.69123989]])>

tf.concat([t1, t2], axis=1).shape.as_list()
[2, 6]

tf.concat([t1, t2], axis=0)

<tf.Tensor: id=19, shape=(4, 3), dtype=float64, numpy=
array([[0.72315241, 0.9374959 , 0.18808236],
       [0.74153715, 0.85361367, 0.13258545],
       [0.80159933, 0.8123236 , 0.80555496],
       [0.82570606, 0.4092662 , 0.69123989]])>

tf.concat([t1, t2], axis=0).shape.as_list()
[4, 3]

只有当你想连接张量along a new axis时才应该使用tf.stack

tf.stack([t1, t2]).shape.as_list()
[2, 2, 3]

换句话说,tf.stack 创建了一个新维度并将张量堆叠在其中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2023-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多