第12章 TensorFlow 张量切片指南
TensorFlow
学习
TensorFlow Core
指南
张量切片简介
使用集合保持内容井井有条
根据您的偏好保存和分类内容。
在 TensorFlow.org 上查看
在 Google Colab 中运行
在 GitHub 上查看源码
下载 notebook
在开发目标检测、NLP 这类机器学习应用时,有时需要操作张量的部分内容(即切片)。例如,模型架构中可能包含路由逻辑——由某一层控制哪些训练样本被送往下一层。这时就可以用张量切片操作把张量拆开,再按正确的顺序拼回去。
在 NLP 应用中,可以在训练时用张量切片来做词遮蔽(word masking)。例如,可以从一组句子生成训练数据:为每个句子选一个要遮蔽的词索引,把该词取出作为标签,再用 mask token 替换原词。
在本指南中,你将学习如何使用 TensorFlow API 来:
从张量中提取切片 在张量的指定索引处插入数据
本指南假定你已了解张量索引。开始之前,请先阅读 Tensor 和 TensorFlow NumPy 两篇指南中关于索引的章节。
环境设置 import tensorflow as tf import numpy as np
2024-08-15 02:59:22.387959: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:485] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2024-08-15 02:59:22.409014: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:8454] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2024-08-15 02:59:22.415391: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1452] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
提取张量切片
使用 tf.slice 可以进行类似 NumPy 的张量切片操作。 t1 = tf.constant([0, 1, 2, 3, 4, 5, 6, 7])
print(tf.slice(t1, begin=[1], size=[3]))
tf.Tensor([1 2 3], shape=(3,), dtype=int32) WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1723690765.029742 169903 cuda_executor.cc:1015] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 I0000 00:00:1723690766.383365 169903 cuda_executor.cc:1015] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355
也可以使用更 Pythonic 的语法。注意,张量切片是在 start-stop 范围内均匀间隔的。 print(t1[1:4])
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
print(t1[-3:])
tf.Tensor([5 6 7], shape=(3,), dtype=int32)
对于二维张量,可以这样写: t2 = tf.constant([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]])
print(t2[:-1, 1:3])
tf.Tensor( [[ 1 2] [ 6 7] [11 12]], shape=(3, 2), dtype=int32)
tf.slice 同样适用于更高维的张量。 t3 = tf.constant([[[1, 3, 5, 7], [9, 11, 13, 15]], [[17, 19, 21, 23], [25, 27, 29, 31]] ])
print(tf.slice(t3, begin=[1, 1, 0], size=[1, 1, 2]))
tf.Tensor([[[25 27]]], shape=(1, 1, 2), dtype=int32)
你还可以用 tf.strided_slice,通过沿张量维度“跨步”的方式提取切片。
使用 tf.gather 可以从张量的单个轴上提取指定索引的元素。 print(tf.gather(t1, indices=[0, 3, 6]))
This is similar to doing
t1[::3]
tf.Tensor([0 3 6], shape=(3,), dtype=int32)
tf.gather 不要求索引均匀间隔。 alphabet = tf.constant(list('abcdefghijklmnopqrstuvwxyz'))
print(tf.gather(alphabet, indices=[2, 0, 19, 18]))
tf.Tensor([b'c' b'a' b't' b's'], shape=(4,), dtype=string)
要从张量的多个轴上提取切片,请使用 tf.gather_nd。当你想按元素收集矩阵内容而不只是按行或列收集时,它非常有用。 t4 = tf.constant([[0, 5], [1, 6], [2, 7], [3, 8], [4, 9]])
print(tf.gather_nd(t4, indices=[[2], [3], [0]]))
tf.Tensor( [[2 7] [3 8] [0 5]], shape=(3, 2), dtype=int32)
t5 = np.reshape(np.arange(18), [2, 3, 3])
print(tf.gather_nd(t5, indices=[[0, 0, 0], [1, 2, 1]]))
tf.Tensor([ 0 16], shape=(2,), dtype=int64)
Return a list of two matrices
print(tf.gather_nd(t5, indices=[[[0, 0], [0, 2]], [[1, 0], [1, 2]]]))
tf.Tensor( [[[ 0 1 2] [ 6 7 8]]
[[ 9 10 11] [15 16 17]]], shape=(2, 2, 3), dtype=int64)
Return one matrix
print(tf.gather_nd(t5, indices=[[0, 0], [0, 2], [1, 0], [1, 2]]))
tf.Tensor( [[ 0 1 2] [ 6 7 8] [ 9 10 11] [15 16 17]], shape=(4, 3), dtype=int64)
向张量中插入数据
使用 tf.scatter_nd 可以在张量的指定切片/索引处插入数据。注意,被插入数据的目标张量是零初始化的。 t6 = tf.constant([10]) indices = tf.constant([[1], [3], [5], [7], [9]]) data = tf.constant([2, 4, 6, 8, 10])
print(tf.scatter_nd(indices=indices, updates=data, shape=t6))
tf.Tensor([ 0 2 0 4 0 6 0 8 0 10], shape=(10,), dtype=int32)
像 tf.scatter_nd 这类需要零初始化张量的方法,与稀疏张量初始化器类似。你可以结合 tf.gather_nd 和 tf.scatter_nd 来模拟稀疏张量操作的行为。
来看一个结合这两种方法构造稀疏张量的例子。 # Gather values from one tensor by specifying indices
new_indices = tf.constant([[0, 2], [2, 1], [3, 3]]) t7 = tf.gather_nd(t2, indices=new_indices)
Add these values into a new tensor
t8 = tf.scatter_nd(indices=new_indices, updates=t7, shape=tf.constant([4, 5]))
print(t8)
tf.Tensor( [[ 0 0 2 0 0] [ 0 0 0 0 0] [ 0 11 0 0 0] [ 0 0 0 18 0]], shape=(4, 5), dtype=int32)
这等价于: t9 = tf.SparseTensor(indices=[[0, 2], [2, 1], [3, 3]], values=[2, 11, 18], dense_shape=[4, 5])
print(t9)
SparseTensor(indices=tf.Tensor( [[0 2] [2 1] [3 3]], shape=(3, 2), dtype=int64), values=tf.Tensor([ 2 11 18], shape=(3,), dtype=int32), dense_shape=tf.Tensor([4 5], shape=(2,), dtype=int64))
Convert the sparse tensor into a dense tensor
t10 = tf.sparse.to_dense(t9)
print(t10)
tf.Tensor( [[ 0 0 2 0 0] [ 0 0 0 0 0] [ 0 11 0 0 0] [ 0 0 0 18 0]], shape=(4, 5), dtype=int32)
若要向已有值的张量中插入数据,请使用 tf.tensor_scatter_nd_add。 t11 = tf.constant([[2, 7, 0], [9, 0, 1], [0, 3, 8]])
Convert the tensor into a magic square by inserting numbers at appropriate indices
t12 = tf.tensor_scatter_nd_add(t11, indices=[[0, 2], [1, 1], [2, 0]], updates=[6, 5, 4])
print(t12)
tf.Tensor( [[2 7 6] [9 5 1] [4 3 8]], shape=(3, 3), dtype=int32)
类似地,可以使用 tf.tensor_scatter_nd_sub 从已有值的张量中减去数值。 # Convert the tensor into an identity matrix
t13 = tf.tensor_scatter_nd_sub(t11, indices=[[0, 0], [0, 1], [1, 0], [1, 1], [1, 2], [2, 1], [2, 2]], updates=[1, 7, 9, -1, 1, 3, 7])
print(t13)
tf.Tensor( [[1 0 0] [0 1 0] [0 0 1]], shape=(3, 3), dtype=int32)
使用 tf.tensor_scatter_nd_min 可以把一个张量的逐元素最小值复制到另一个张量。 t14 = tf.constant([[-2, -7, 0], [-9, 0, 1], [0, -3, -8]])
t15 = tf.tensor_scatter_nd_min(t14, indices=[[0, 2], [1, 1], [2, 0]], updates=[-6, -5, -4])
print(t15)
tf.Tensor( [[-2 -7 -6] [-9 -5 1] [-4 -3 -8]], shape=(3, 3), dtype=int32)
类似地,使用 tf.tensor_scatter_nd_max 可以把一个张量的逐元素最大值复制到另一个张量。 t16 = tf.tensor_scatter_nd_max(t14, indices=[[0, 2], [1, 1], [2, 0]], updates=[6, 5, 4])
print(t16)
tf.Tensor( [[-2 -7 6] [-9 5 1] [ 4 -3 -8]], shape=(3, 3), dtype=int32)
延伸阅读与资源
在本指南中,你学习了如何使用 TensorFlow 提供的张量切片操作,对张量中的元素进行更精细的控制。
了解 TensorFlow NumPy 提供的切片操作,例如 tf.experimental.numpy.take_along_axis 和 tf.experimental.numpy.take。 另请参阅 Tensor 指南和 Variable 指南。