在 PyTorch 中使用 None 索引张量 [英] Indexing a tensor with None in PyTorch
问题描述
我见过这种在 PyTorch 中索引张量的语法,不知道是什么意思:
v = torch.div(t, n[:, None])
其中 v
、t
和 n
是张量.
None
"的作用是什么?这里?我似乎无法在文档中找到它.
与 NumPy 类似,您可以通过使用 None 索引此维度来插入单个维度(unsqueeze" 维度)代码>.反过来,
n[:, None]
将具有在 dim=1
上插入新维度的效果.这相当于 n.unsqueeze(dim=1)
:
这里有一些其他类型的无
索引.
在上面的例子中,:
被用作占位符来指定第一个维度 dim=0
.如果您想在 dim=2
上插入一个维度,您可以添加第二个 :
作为 n[:, :, None]
.
您也可以放置 None
而不是相对于最后一个维度.为此,您可以使用 省略号 语法<代码>...代码>:
n[..., None]
最后插入一个维度,ien.unsqueeze(dim=-1)
.n[..., None, :]
在前一个维度上,ien.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屋!