What would be the correct counterpart of the numpy functions hstack and vstack in Tensorflow?
There is tf.stack and tf.concat in Tensorflow, but i don't know how to use them or use the correct axis value, to achieve the same behaviour in Tensorflow.
You should use the tf.concat with different axis argument to get the same result as with hstack or vstack:
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]
You should use tf.stack only if you want to concatenate tensors along a new axis:
tf.stack([t1, t2]).shape.as_list()
[2, 2, 3]
In other words, tf.stack creates a new dimension and stacks the tensors along in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With