张量切片简介

在 TensorFlow.org 上查看 在 Google Colab 中运行 在 GitHub 上查看源代码 下载笔记本

在处理目标检测和 NLP 等机器学习应用时,有时需要使用张量的子部分(切片)。例如,如果您的模型架构包含路由,则其中一层可能控制将哪个训练样本路由到下一层。在这种情况下,可以使用张量切片运算将张量拆分并以正确的顺序将它们重新组合在一起。

在 NLP 应用中,可以在训练时使用张量切片来执行单词遮盖。例如,可以通过在每个句子中选择要遮盖的单词索引,将单词作为标签,然后使用遮盖词例替换选中的单词,以从句子列表中生成训练数据。

在本指南中,您将学习如何使用 TensorFlow API 执行以下操作:

  • 从张量中提取切片
  • 在张量中的特定索引处插入数据

本指南假定您熟悉张量索引。在开始学习本指南之前,请阅读张量TensorFlow NumPy 指南的索引部分。

安装

import tensorflow as tf
import numpy as np
2022-12-14 22:47:45.408531: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 22:47:45.408626: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 22:47:45.408636: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.

提取张量切片

使用 tf.slice 执行类似 NumPy 的张量切片。

t1 = tf.constant([0, 1, 2, 3, 4, 5, 6, 7