Torch sum a tensor along an axis

The simplest and best solution is to use torch.sum().

To sum all elements of a tensor:

torch.sum(x) # gives back a scalar

To sum over all rows (i.e. for each column):

torch.sum(x, dim=0) # size = [ncol]

To sum over all columns (i.e. for each row):

torch.sum(x, dim=1) # size = [nrow]

It should be noted that the dimension summed over is eliminated from the resulting tensor.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)