Python ``tensorflow.gather()`` 张量索引切片函数与实例


发布日期 : 2021-02-02 10:26:47 UTC

访问量: 10 次浏览

Python – tensorflow.gather()

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

gather()用于根据提供的指数对输入张量进行切片。

语法:
tensorflow.gather( params, indices, validate_indices, axis, batch_dims, name)

参数:

  • params: 它是一个等级大于或等于 axis+1 的张量。
  • indices: 它是一个dtype int32或int64的张量。它的值应该在 [0, params.shape[axis]] 的范围内。
  • axis: 它是一个dtype int32或int64的张量。它定义了应该收集指数的轴。默认值是0,它必须大于或等于 batch\_dims
  • batch\_dims : 它是一个整数,代表批次维度的数量。它必须小于或等于rank(indices)。
  • name: 它定义了操作的名称。

返回值:

它返回一个张量,其 dtype 与参数相同。

示例 1:

# Importing the library
import tensorflow as tf

# Initializing the input
data = tf.constant([1, 2, 3, 4, 5, 6])
indices = tf.constant([0, 1, 2, 1])

# Printing the input
print('data: ',data)
print('indices: ',indices)

# Calculating result
res = tf.gather(data, indices)

# Printing the result
print('res: ',res)

输出:

data: tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32)
indices: tf.Tensor([0 1 2 1], shape=(4,), dtype=int32)
res: tf.Tensor([1 2 3 2], shape=(4,), dtype=int32)

示例 2:

# Importing the library
import tensorflow as tf

# Initializing the input
data = tf.constant([[1, 2], [3, 4], [5, 6]])
indices = tf.constant([2, 0, 1])

# Printing the input
print('data: ',data)
print('indices: ',indices)

# Calculating result
res = tf.gather(data, indices)

# Printing the result
print('res: ',res)

输出:

data: tf.Tensor(
[[1 2]
[3 4]
[5 6]], shape=(3, 2), dtype=int32)
indices: tf.Tensor([2 0 1], shape=(3,), dtype=int32)
res: tf.Tensor(
[[5 6]
[1 2]
[3 4]], shape=(3, 2), dtype=int32)