PyTorch torch.add Function
PyTorch torch reference manual
torch.add is a function in PyTorch used to perform element-wise addition. It adds two tensors, or a tensor and a scalar.
This is one of the most basic mathematical operations and is used in various computational scenarios in deep learning.
Function definition
torch.add(input, other, alpha=1, out=None)
Parameters:
input(Tensor): the first input tensor.other(Tensor or float): the second input tensor or scalar.alpha(float, optional): a scaling factor;otherthe other input is multiplied by this value before being added toinputinput; defaults to 1.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: returns the tensor after addition.
Usage examples
Example 1: adding two tensors
Example
import
torch
Create two tensors
a
=
torch.
tensor
(
[
1
,
2
,
3
]
)
b
=
torch.
tensor
(
[
4
,
5
,
6
]
)
Sum
c
=
torch.
add
(
a
,
b
)
(
c
)
The output is:
tensor([5, 7, 9])
Example 2: adding a tensor and a scalar
Example
import
torch
Creating tensors
a
=
torch.
tensor
(
[
1
,
2
,
3
]
)
Add the scalar
b
=
torch.
add
(
a
,
10
)
(
b
)
The output is:
tensor([11, 12, 13])
Example 3: using the alpha parameter
Example
import
torch
Create two tensors
a
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
]
)
b
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
]
)
Compute a + 2 * b
c
=
torch.
add
(
a
,
b
,
alpha
=
2
)
(
c
)
The output is:
tensor([3., 6., 9.])
alpha This parameter is useful when implementing certain algorithms, such as computing input + alpha * other.
Example 4: broadcasting
Example
import
torch
Adding tensors of different shapes (broadcasting)
a
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
]
)
b
=
torch.
tensor
(
[
1
,
2
,
3
]
)
c
=
torch.
add
(
a
,
b
)
(
c
)
The output is:
tensor([[2, 4, 6],
[5, 7, 9])
PyTorch supports broadcasting, which allows operations on tensors of different shapes.
Using the plus operator
Besides using torch.add() function, you can also directly use the + operator; both have the same effect:
Example
import
torch
a
=
torch.
tensor
(
[
1
,
2
,
3
]
)
b
=
torch.
tensor
(
[
4
,
5
,
6
]
)
Both approaches are equivalent
c1
=
torch.
add
(
a
,
b
)
c2
=
a + b
(
c1
)
(
c2
)
(
torch.
equal
(
c1
,
c2
)
)