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

PyTorch torch.atleast_2d function

PyTorch torch.atleast_2d function


PyTorch torch reference manual PyTorch torch reference manual

torch.atleast_2d is a function in PyTorch used to convert an input tensor to at least 2 dimensions. If the input has fewer than 2 dimensions, dimensions are automatically added to make it 2D.

Function definition

torch.atleast_2d(*tensors)


Usage examples

Example

import

torch

Convert a scalar to a 2D tensor

x

=

torch.

atleast_2d

(

5

)

print

(

"After scalar conversion:"

,

x

,

"Shape:"

,

x.

shape

)

Output: After scalar conversion: tensor([[5]]) shape: torch.Size([1, 1])

Convert a 1D tensor to 2D

x

=

torch.

tensor

(

[

1

,

2

,

3

]

)

y

=

torch.

atleast_2d

(

x

)

print

(

"1D to 2D:"

,

y

,

"Shape:"

,

y.

shape

)

Output: 1D to 2D: tensor([[1, 2, 3]]) shape: torch.Size([1, 3])

A tensor that is already 2D remains unchanged

x

=

torch.

tensor

(

[

[

1

,

2

]

,

[

3

,

4

]

]

)

y

=

torch.

atleast_2d

(

x

)

print

(

"2D tensor:"

,

y

,

"Shape:"

,

y.

shape

)


PyTorch torch reference manual PyTorch torch reference manual