TensorFlow – How to stack a list of rank-R tensors into one rank-(R+1) tensor in parallel
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
TensorFlow provides build in methods to stack a list of rank-R tensors into one rank-(R+1) tensor in parallel.
Methods Used:
- parallel_stack: This method accepts a list of Tensors and returns a Tensor with all values stacked in parallel. This methods copies pieces of the input into the output as they become available.
- stack: This method accepts a list of Tensors, axis along which values should be stacked and returns a Tensor with all values stacked.
Example 1: This example uses stack method to stack tensors.
Python3
import tensorflow as tf
x = tf.constant([ 1 , 2 , 3 ])
y = tf.constant([ 4 , 5 , 6 ])
z = tf.constant([ 7 , 8 , 9 ])
print ( "x: " , x)
print ( "y: " , y)
print ( "z: " , z)
res = tf.stack(values = [x, y, z], axis = 0 )
print ( "Res: " , res )
|
Output:
x: tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
y: tf.Tensor([4 5 6], shape=(3, ), dtype=int32)
z: tf.Tensor([7 8 9], shape=(3, ), dtype=int32)
Res: tf.Tensor(
[[1 2 3]
[4 5 6]
[7 8 9]], shape=(3, 3), dtype=int32)
Example 2: This example uses parallel_stack method to stack the input Tensors.
Python3
import tensorflow as tf
x = tf.constant([ 1 , 2 , 3 ])
y = tf.constant([ 4 , 5 , 6 ])
z = tf.constant([ 7 , 8 , 9 ])
print ( "x: " , x)
print ( "y: " , y)
print ( "z: " , z)
res = tf.parallel_stack(values = [x, y, z])
print ( "Res: " , res )
|
Output:
x: tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
y: tf.Tensor([4 5 6], shape=(3, ), dtype=int32)
z: tf.Tensor([7 8 9], shape=(3, ), dtype=int32)
Res: tf.Tensor(
[[1 2 3]
[4 5 6]
[7 8 9]], shape=(3, 3), dtype=int32)
Last Updated :
01 Aug, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...