TensorFlow stack 与 ``parallel_stack`` 张量堆叠用法


发布日期 : 2023-01-29 14:51:25 UTC

访问量: 10 次浏览

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

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

TensorFlow提供了内置的方法来将一个R级张量列表并行地堆叠成一个R级(R+1)张量。

使用的方法:

  • parallel\_stack :这个方法接受一个张量列表,并返回一个所有数值都被平行堆叠的张量。这个方法将输入的部分复制到输出中,因为它们是可用的。
  • stack :这个方法接受一个张量列表,轴沿着哪些值应该被堆叠,并返回一个具有所有值堆叠的张量。

实例1:
本实例使用堆栈方法来堆栈张量。

# 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 )

输出:

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方法来堆叠输入的 Tensors

# 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)