首页 > 解决方案 > Tensorflow 中 hstack 和 vstack 的对应物

问题描述

numpy函数hstackTensorflow的正确对应物是vstack什么?

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

标签: python-3.xnumpytensorflow

解决方案


您应该使用tf.concatwith 不同的参数来获得与 with oraxis相同的结果: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]

tf.stack仅当您想沿新轴连接张量时才应使用:

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

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


推荐阅读