Tensorflow中hstack和vstack的对应部分

时间:2019-03-11 10:03:02

标签: python-3.x numpy tensorflow

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

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

1 个答案:

答案 0 :(得分:0)

您应将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创建一个新尺寸并沿其堆叠张量。