首页 > 解决方案 > tensor.size(-1) 中的 -1 是什么意思?

问题描述

我在 Pytorch 文档中看到过类似的内容,

import torch

a = torch.tensor([1, 2])
a.size() # torch.Size([2])
a.size(-1) # 2

这是如何运作的?我没找到说明。谢谢,

标签: pythonpytorch

解决方案


a.size(-1)指最后一个维度。例如,如果 x 的形状为 (10,20),则 x.size(-1) 指的是第二维,即 20。请看以下示例:

import torch
a= torch.zeros((2,5)) # a is matrix of 2 rows and 5 columns all elements are 0
#size gives a 1d tensor containing the shapes
a.size(-1)# refers to the last element in the tensor

这相当于:

a_size= a.size()
a_size(-1)

希望这对您有所帮助。


推荐阅读