PyTorch torch.broadcast_tensors function
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
)
(
"Shape of x after broadcasting:"
,
a.
shape
)
(
"Shape of y after broadcasting:"
,
b.
shape
)
(
"x after broadcasting:"
)
(
a
)
(
"y after broadcasting:"
)
(
b
)
(
"Element-wise addition:"
)
(
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
)
(
"Shape after broadcasting:"
,
r1.
shape
)