PyTorch torch.sum() Method

PyTorch torch.sum() method “returns the sum of all elements in the input tensor.”

Syntax

torch.sum(input, dim, keepdim=False, *, dtype=None)

Parameters

  1. input (Tensor): It is an input tensor.
  2. dim (int or tuple of ints, optional): It is the dimension or dimensions to reduce. If None, all dimensions are reduced.
  3. keepdim (bool):  Whether the output tensor has dim retained or not.
  4. dtype: The desired data type of the returned tensor. If specified, the input tensor is cast to dtype before operating.

Example 1: Sum all elements of a tensor

import torch

a = torch.Tensor([1, 2, 3, 4, 5])

result = torch.sum(a)

print(result)

Output

tensor(15.)

Example 2: Sum along a specific dimension

import torch

a = torch.Tensor([[1, 2], [3, 4], [5, 6]])

result = torch.sum(a, dim=0)

print(result)

Output

tensor([ 9., 12.])

Example 3: Sum along multiple dimensions

import torch

a = torch.Tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

result = torch.sum(a, dim=(0, 1))

print(result)

Output

tensor([16., 20.])

Example 4: Keep dimensions

import torch

a = torch.Tensor([[1, 2], [3, 4], [5, 6]])

result = torch.sum(a, dim=0, keepdim=True) 

print(result)

Output

tensor([[ 9., 12.]])

Example 6: Torch sum a tensor along an axis

To sum a tensor along an axis in PyTorch, use the “torch.sum() function”. The torch.sum() function accepts two arguments: the tensor you want to sum and the axis you want to sum over. The axis can be a single integer or a list of integers. If you specify a list of integers, the tensor will be summed over all the axes specified in the list.

import torch

tensor = torch.rand(3, 4)

sum = torch.sum(tensor, dim=0)

print(sum)

Output

tensor([1.1096, 1.9846, 0.5725, 1.8936])

The torch.sum() function is used to sum along the last axis of a tensor. To do this, you can use the -1 argument for the dim parameter.

import torch

tensor = torch.rand(3, 4)

sum = torch.sum(tensor, dim=-1)

print(sum)

Output

tensor([3.1583, 2.5213, 2.4922])

Related posts

PyTorch full()

Leave a Comment