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

PyTorch torch.broadcast_tensors function

PyTorch torch.broadcast_tensors function


PyTorch torch reference manual PyTorch torch reference manual

torch.broadcast_tensors is a function in PyTorch used to broadcast multiple tensors. It broadcasts the input tensors to the same shape and returns a set of tensors that can be operated on element-wise. The broadcasting rules follow NumPy's broadcasting mechanism.

Function definition

torch.broadcast_tensors(*tensors)


Usage examples

Example

import

torch

Broadcast tensors of different shapes

x

=

torch.

tensor

(

[

[

1

,

2

,

3

]

]

)

 

Shape (1, 3)

y

=

torch.

tensor

(

[

[

1

]

,

[

2

]

,

[

3

]

]

)

 

Shape (3, 1)

a

,

b

=

torch.

broadcast_tensors

(

x

,

y

)

print

(

"Shape of x after broadcasting:"

,

a.

shape

)

print

(

"Shape of y after broadcasting:"

,

b.

shape

)

print

(

"x after broadcasting:"

)

print

(

a

)

print

(

"y after broadcasting:"

)

print

(

b

)

print

(

"Element-wise addition:"

)

print

(

a + b

)

Multiple tensors

x1

=

torch.

randn

(

3

,

1

,

5

)

x2

=

torch.

randn

(

1

,

4

,

5

)

x3

=

torch.

randn

(

3

,

4

,

1

)

r1

,

r2

,

r3

=

torch.

broadcast_tensors

(

x1

,

x2

,

x3

)

print

(

"Shape after broadcasting:"

,

r1.

shape

)


PyTorch torch reference manual PyTorch torch reference manual