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

PyTorch torch.broadcast_to function

PyTorch torch.broadcast_to function


PyTorch torch reference manual PyTorch torch reference manual

torch.broadcast_to is a function in PyTorch used to broadcast a tensor to a specified shape. It returns a view of the input tensor broadcast to the target shape. The broadcasting rules follow NumPy's broadcasting mechanism.

Function definition

torch.broadcast_to(input, shape)


Usage examples

Example

import

torch

Basic usage: Broadcast a 1D tensor to 2D

x

=

torch.

tensor

(

[

1

,

2

,

3

]

)

y

=

torch.

broadcast_to

(

x

,

(

3

,

3

)

)

print

(

"Original:"

,

x

)

print

(

"After broadcasting:"

)

print

(

y

)

tensor([[1, 2, 3],

        [1, 2, 3],

        [1, 2, 3]])

Broadcast a scalar to a larger shape

x

=

torch.

tensor

(

5

)

y

=

torch.

broadcast_to

(

x

,

(

2

,

3

,

4

)

)

print

(

"Scalar broadcast to (2,3,4):"

,

y.

shape

)

Broadcast 2D to 3D

x

=

torch.

tensor

(

[

[

1

,

2

]

,

[

3

,

4

]

]

)

 

(2, 2)

y

=

torch.

broadcast_to

(

x

,

(

3

,

2

,

2

)

)

print

(

"Broadcast to (3,2,2):"

,

y.

shape

)

print

(

y

)


PyTorch torch reference manual PyTorch torch reference manual