Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.sum function

PyTorch torch.sum function


PyTorch torch reference manual PyTorch torch reference manual

torch.sum is a function in PyTorch used to compute the sum of tensor elements. It can compute the sum of all elements or along a specified dimension.

This is a common reduction operation in deep learning, used for loss computation, statistics, and similar scenarios.

Function definition

torch.sum(input, dim, keepdim, dtype, out)

Parameters:

Return Value:


Usage examples

Example 1: Compute the sum of all elements

Example

import

torch

Creating tensors

x

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

]

)

Compute the sum of all elements

total

=

torch.

sum

(

x

)

print

(

"Tensor:"

)

print

(

x

)

print

(

"Sum of elements:"

,

total

)

The output is:

张量:

tensor([[1, 2, 3],

        [4, 5, 6]])

元素之和: tensor(21)

Example 2: Sum along a specified dimension

Example

import

torch

x

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

]

)

Sum along dim=0 (columns)

sum_dim0

=

torch.

sum

(

x

,

dim

=

0

)

print

(

"Sum along dim=0:"

,

sum_dim0

)

Sum along dim=1 (rows)

sum_dim1

=

torch.

sum

(

x

,

dim

=

1

)

print

(

"Sum along dim=1:"

,

sum_dim1

)

The output is:

沿 dim=0 求和: tensor([5, 7, 9])

沿 dim=1 求和: tensor([ 6, 15])

Example 3: Use keepdim to keep dimensions

Example

import

torch

x

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

]

)

Do not keep dimensions

sum1

=

torch.

sum

(

x

,

dim

=

0

)

print

(

"Without keeping dimensions:"

,

sum1.

shape

)

Keep dimensions

sum2

=

torch.

sum

(

x

,

dim

=

0

,

keepdim

=

True

)

print

(

"With dimensions kept:"

,

sum2.

shape

)

print

(

sum2

)

The output is:

不保持维度: torch.Size([3])

保持维度: torch.Size([1, 3])

tensor([[5, 7, 9]])

Example 4: Compute loss in a neural network

Example

import torch

# Simulate predicted and true values
predictions = torch.tensor([0.1, 0.9, 0.8, 0.3])
targets = torch.tensor([0.0, 1.0, 1.0, 0.0])

# Compute the mean squared error loss
loss = torch.sum((predictions - targets) ** 2) / len(predictions)

print("MSE loss:", loss.item())

The output is:

MSE 损失: 0.07499999690771103


PyTorch torch reference manual PyTorch torch reference manual