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

PyTorch torch.add Function

PyTorch torch.add Function


PyTorch torch reference manual 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:

Return Value:


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

)

print

(

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

)

print

(

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

)

print

(

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

)

print

(

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

print

(

c1

)

print

(

c2

)

print

(

torch.

equal

(

c1

,

c2

)

)


PyTorch torch reference manual PyTorch torch reference manual