HomeLanguagesTensorFlow – How to stack a list of rank-R tensors into...

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




# importing the library
import tensorflow as tf
  
# Initializing the Input
x = tf.constant([1, 2, 3])
y = tf.constant([4, 5, 6])
z = tf.constant([7, 8, 9])
  
# Printing the Input
print("x: ", x)
print("y: ", y)
print("z: ", z)
  
# Stacking Tensors
res = tf.stack(values =[x, y, z], axis = 0)
  
# Printing the resulting Tensor
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




# importing the library
import tensorflow as tf
  
# Initializing the Input
x = tf.constant([1, 2, 3])
y = tf.constant([4, 5, 6])
z = tf.constant([7, 8, 9])
  
# Printing the Input
print("x: ", x)
print("y: ", y)
print("z: ", z)
  
# Stacking Tensors
res = tf.parallel_stack(values =[x, y, z])
  
# Printing the resulting Tensor
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)
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

4 COMMENTS

Most Popular

Dominic
32686 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7052 POSTS0 COMMENTS
Nicole Veronica
12192 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12291 POSTS0 COMMENTS
Shaida Kate Naidoo
7178 POSTS0 COMMENTS
Ted Musemwa
7444 POSTS0 COMMENTS
Thapelo Manthata
7156 POSTS0 COMMENTS
Umr Jansen
7147 POSTS0 COMMENTS