PyTorch torch.sum function
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:
input(Tensor): the input tensor.dim(int or tuple of int, optional): The dimension(s) to compute. IfNone, the sum of all elements is computed.keepdim(bool, optional): Whether to keep the dimensions. Defaults toFalse.dtype(torch.dtype, optional): The data type of the output tensor.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: Returns the computed tensor.
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
)
(
"Tensor:"
)
(
x
)
(
"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
)
(
"Sum along dim=0:"
,
sum_dim0
)
Sum along dim=1 (rows)
sum_dim1
=
torch.
sum
(
x
,
dim
=
1
)
(
"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
)
(
"Without keeping dimensions:"
,
sum1.
shape
)
Keep dimensions
sum2
=
torch.
sum
(
x
,
dim
=
0
,
keepdim
=
True
)
(
"With dimensions kept:"
,
sum2.
shape
)
(
sum2
)
The output is:
不保持维度: torch.Size([3])
保持维度: torch.Size([1, 3])
tensor([[5, 7, 9]])
Example 4: Compute loss in a neural network
Example
# 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