【深度学习】NestedTensors

NestedTensors

DETR 中常见的数据格式为 NestedTensors,那么什么是 NestedTensors 呢?
NestedTensor,包括 tensormask 两个成员,tensor 就是输入的图像。mask 跟 tensor 同高宽但是单通道。比如 masks 大小为 (1, 800, 1440),tensor 大小为 (1, 3, 800, 1440)。

Why NestedTensor

当数据是连续的时,通常情况下每个样本都有不同的长度。
例如,在一批句子中,每个句子都有不同数量的单词。处理变化序列的一种常见技术是手动将每个数据张量填充到相同的形状,以形成一个批。
例如,我们有两个不同长度的句子和一个词汇表。为了将其表示为单个张量,我们将 0 填充到批中的最大长度。
简单说就是把图片都 padding 成最大的尺寸,padding 的方式就是补零,那么 batch 中的每一张图都有一个 mask 矩阵,在 img 有值的地方是 1,补零的地方是 0。

举个例子,下面两种构造方式其实是等价的,

padded_sentences = torch.tensor([[1.0, 2.0, 0.0],
                                 [3.0, 4.0, 5.0]])
nested_sentences = torch.nested.nested_tensor([torch.tensor([1.0, 2.0]),
                                               torch.tensor([3.0, 4.0, 5.0])])

初始化 NestedTensor

我们可以从张量列表中创建 nestedtensor。我们将 nt[i] 表示为nestedtensor的第 i 个张量分量。

nt = torch.nested.nested_tensor([torch.arange(12).reshape(
    2, 6), torch.arange(18).reshape(3, 6)], dtype=torch.float, device=device)

NestedTensor 操作

reshape

nt_reshaped = nt.reshape(2, -1, 2, 3)

转置

nt_transposed = nt_reshaped.transpose(1, 2)

查看维度

假设 features 为 NestedTensor 格式,直接运行 features[-1]. shape 则会报错 AttributeError: ‘NestedTensor’ object has no attribute ‘Nested_Tensor’,应该使用 features[-1]. tensors. shape

其他

其他操作具有与常规张量相同的语法。

nt_mm = torch.nested.nested_tensor([torch.randn((2, 3, 4)), torch.randn((2, 3, 5))], device=device)
nt3 = torch.matmul(nt_transposed, nt_mm)
print(f"Result of Matmul:\n {nt3}")

nt4 = F.dropout(nt3, 0.1)
print(f"Result of Dropout:\n {nt4}")

nt5 = F.softmax(nt4, -1)
print(f"Result of Softmax:\n {nt5}")

相关推荐

  1. 深度学习NestedTensors

    2024-03-24 20:00:07       36 阅读
  2. 深度学习

    2024-03-24 20:00:07       51 阅读
  3. 深度学习????????

    2024-03-24 20:00:07       53 阅读
  4. 动手学深度学习深度学习计算

    2024-03-24 20:00:07       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-24 20:00:07       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-24 20:00:07       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-24 20:00:07       82 阅读
  4. Python语言-面向对象

    2024-03-24 20:00:07       91 阅读

热门阅读

  1. ubuntu安装k8s

    2024-03-24 20:00:07       34 阅读
  2. 用 Delphi 做 FTP 服务器以及如何配置防火墙

    2024-03-24 20:00:07       41 阅读
  3. spring boot整合elasticsearch实现查询功能

    2024-03-24 20:00:07       41 阅读
  4. vim | vim的快捷命令行

    2024-03-24 20:00:07       38 阅读
  5. 阅读 MySQL知识1

    2024-03-24 20:00:07       37 阅读
  6. Vue常用指令介绍

    2024-03-24 20:00:07       40 阅读
  7. 2024网络安全&数据安全加固类资料合集

    2024-03-24 20:00:07       37 阅读
  8. Pytorch:torch.utils.checkpoint()

    2024-03-24 20:00:07       43 阅读
  9. ModuleNotFoundError: No module named ‘sklearn.cross_validation

    2024-03-24 20:00:07       35 阅读
  10. rollup打包起手式

    2024-03-24 20:00:07       47 阅读