Python TensorFlow ``dynamic_partition()`` 方法详解与代码示例


发布日期 : 2021-05-15 08:43:44 UTC

访问量: 10 次浏览

Python – tensorflow.dynamic\_partition()

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

dynamic\_partition()用于将数据分成若干个分区。

语法:
tensorflow.dynamic_partition(data, partitions, num_partitions, name)

参数:

  • data :它是需要被分割的输入张量。
  • partitions :它是int32类型的张量,它的数据应该在 [0, num\_partitions] 范围内。
  • num\_partitions :它定义了分区的数量。
  • name(可选) :它定义了该操作的名称。

返回值:

它返回一个带有 num\_partitions 项的张量列表。列表中的每个张量都有与数据相同的 dtype

例子1:
将数据分为两个分区

# Importing the library
import tensorflow as tf

# Initializing the input
data = [1, 2, 3, 4, 5]
num_partitions = 2
partitions = [0, 0, 1, 0, 1]

# Printing the input
print('data: ', data)
print('partitions:', partitions)
print('num_partitions:', num_partitions)

# Calculating result
x = tf.dynamic_partition(data, partitions, num_partitions)


# Printing the result
print('x[0]: ', x[0])
print('x[1]: ', x[1])

输出:

data: [1, 2, 3, 4, 5]
partitions: [0, 0, 1, 0, 1]
num_partitions: 2
x[0]: tf.Tensor([1 2 4], shape=(3, ), dtype=int32)
x[1]: tf.Tensor([3 5], shape=(2, ), dtype=int32)

例子2:
划分为3个张量

# Importing the library
import tensorflow as tf

# Initializing the input
data = [1, 2, 3, 4, 5, 6, 7]
num_partitions = 3
partitions = [0, 2, 1, 0, 1, 2, 2]

# Printing the input
print('data: ', data)
print('partitions:', partitions)
print('num_partitions:', num_partitions)

# Calculating result
x = tf.dynamic_partition(data, partitions, num_partitions)


# Printing the result
print('x[0]: ', x[0])
print('x[1]: ', x[1])
print('x[2]: ', x[2])

输出:

data: [1, 2, 3, 4, 5, 6, 7]
partitions: [0, 2, 1, 0, 1, 2, 2]
num_partitions: 3
x[0]: tf.Tensor([1 4], shape=(2, ), dtype=int32)
x[1]: tf.Tensor([3 5], shape=(2, ), dtype=int32)
x[2]: tf.Tensor([2 6 7], shape=(3, ), dtype=int32)