📜  TensorFlow – 如何将 rank-R 张量列表并行堆叠成一个 rank-(R+1) 张量

📅  最后修改于: 2022-05-13 01:54:20.446000             🧑  作者: Mango

TensorFlow – 如何将 rank-R 张量列表并行堆叠成一个 rank-(R+1) 张量

TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

TensorFlow 提供了内置方法,可以将 rank-R 张量列表并行堆叠到一个 rank-(R+1) 张量中。

示例 1:此示例使用 stack 方法来堆叠张量。

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 )


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 )


输出:

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)

示例 2:此示例使用 parallel_stack 方法来堆叠输入张量。

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 )

输出:

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)