在 PyTorch 中使用 None 索引张量 [英] Indexing a tensor with None in PyTorch

查看:26
本文介绍了在 PyTorch 中使用 None 索引张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过这种在 PyTorch 中索引张量的语法,不知道是什么意思:

v = torch.div(t, n[:, None])

其中 vtn 是张量.

None"的作用是什么?这里?我似乎无法在文档中找到它.

解决方案

与 NumPy 类似,您可以通过使用 None 索引此维度来插入单个维度(unsqueeze" 维度).反过来,n[:, None] 将具有在 dim=1 上插入新维度的效果.这相当于 n.unsqueeze(dim=1):

<预><代码>>>>n = 火炬.rand(3, 100, 100)>>>n[:, 无].shape(3, 1, 100, 100)>>>n.unsqueeze(1).shape(3, 1, 100, 100)


这里有一些其他类型的索引.

在上面的例子中,: 被用作占位符来指定第一个维度 dim=0.如果您想在 dim=2 上插入一个维度,您可以添加第二个 : 作为 n[:, :, None].

您也可以放置 None 而不是相对于最后一个维度.为此,您可以使用 省略号 语法<代码>...:

  • n[..., None] 最后插入一个维度,ie n.unsqueeze(dim=-1).

  • n[..., None, :] 在前一个维度上,ie n.unsqueeze(dim=-2).

I've seen this syntax to index a tensor in PyTorch, not sure what it means:

v = torch.div(t, n[:, None])

where v, t, and n are tensors.

What is the role of "None" here? I can't seem to find it in the documentation.

解决方案

Similar to NumPy you can insert a singleton dimension ("unsqueeze" a dimension) by indexing this dimension with None. In turn n[:, None] will have the effect of inserting a new dimension on dim=1. This is equivalent to n.unsqueeze(dim=1):

>>> n = torch.rand(3, 100, 100)

>>> n[:, None].shape
(3, 1, 100, 100)

>>> n.unsqueeze(1).shape
(3, 1, 100, 100)


Here are some other types of None indexings.

In the example above : is was used as a placeholder to designate the first dimension dim=0. If you want to insert a dimension on dim=2, you can add a second : as n[:, :, None].

You can also place None with respect to the last dimension instead. To do so you can use the ellipsis syntax ...:

  • n[..., None] will insert a dimension last, i.e. n.unsqueeze(dim=-1).

  • n[..., None, :] on the before last dimension, i.e. n.unsqueeze(dim=-2).

这篇关于在 PyTorch 中使用 None 索引张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆