what does dim=-1 or -2 mean in torch.sum()?

A tensor has multiple dimensions, ordered as in the following figure. There is a forward and backward indexing. Forward indexing uses positive integers, backward indexing uses negative integers.

Example:

-1 will be the last one, in our case it will be dim=2

-2 will be dim=1

-3 will be dim=0

enter image description here


The minus essentially means you go backwards through the dimensions. Let A be a n-dimensional matrix. Then dim=n-1=-1, dim=n-2=-2, ..., dim=1=-(n-1), dim=0=-n. See the numpy doc for more information, as pytorch is heavily based on numpy.

Tags:

Python

Pytorch