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

PyTorch torch.hstack function

PyTorch torch.hstack function


PyTorch torch reference manual PyTorch torch reference manual

torch.hstack A function in PyTorch for stacking tensors horizontally (along columns).

Function definition

torch.hstack(tensors, *, out=None)


Usage examples

Example

import

torch

Horizontally stack 1D tensors

x1

=

torch.

tensor

(

[

1

,

2

,

3

]

)

x2

=

torch.

tensor

(

[

4

,

5

,

6

]

)

result

=

torch.

hstack

(

[

x1

,

x2

]

)

print

(

"1D tensor stacking:"

)

print

(

f

"  x1: {x1}"

)

print

(

f

"  x2: {x2}"

)

print

(

f

"  hstack: {result}"

)

Horizontally stack 2D tensors

y1

=

torch.

tensor

(

[

[

1

,

2

]

,

[

3

,

4

]

]

)

y2

=

torch.

tensor

(

[

[

5

,

6

]

,

[

7

,

8

]

]

)

result

=

torch.

hstack

(

[

y1

,

y2

]

)

print

(

"n2D tensor horizontal stacking:"

)

print

(

f

"  y1:n{y1}"

)

print

(

f

"  y2:n{y2}"

)

print

(

f

"  hstack:n{result}"

)

Stack multiple tensors

z1

=

torch.

tensor

(

[

1

,

2

]

)

z2

=

torch.

tensor

(

[

3

,

4

]

)

z3

=

torch.

tensor

(

[

5

,

6

]

)

result

=

torch.

hstack

(

[

z1

,

z2

,

z3

]

)

print

(

"nMultiple 1D tensor stacking:"

)

print

(

f

"  result: {result}"

)

The output is:

一维张量堆叠:

  x1: tensor([1, 2, 3])

  x2: tensor([4, 5, 6])

  hstack: tensor([1, 2, 3, 4, 5, 6])



Horizontal stacking of 2D tensors:

  y1:

tensor([[1, 2],

        [3, 4]])

  y2:

tensor([[5, 6],

        [7, 8]])

  hstack:

tensor([[1, 2, 5, 6],

        [3, 4, 7, 8]])



Stacking multiple one-dimensional tensors:

  result: tensor([1, 2, 3, 4, 5, 6])


PyTorch torch reference manual PyTorch torch reference manual