PyTorch torch.vstack function
PyTorch torch reference manual
torch.vstack A function in PyTorch for stacking tensors vertically (along rows).
Function definition
torch.vstack(tensors, *, out=None)
Usage examples
Example
import
torch
Vertically stack 1D tensors
x1
=
torch.
tensor
(
[
1
,
2
,
3
]
)
x2
=
torch.
tensor
(
[
4
,
5
,
6
]
)
result
=
torch.
vstack
(
[
x1
,
x2
]
)
(
"1D tensors stacked vertically:"
)
(
f
" x1: {x1}"
)
(
f
" x2: {x2}"
)
(
f
" vstack:n{result}"
)
Vertically stack 2D tensors
y1
=
torch.
tensor
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
y2
=
torch.
tensor
(
[
[
5
,
6
]
,
[
7
,
8
]
]
)
result
=
torch.
vstack
(
[
y1
,
y2
]
)
(
"n2D tensors stacked vertically:"
)
(
f
" y1:n{y1}"
)
(
f
" y2:n{y2}"
)
(
f
" vstack:n{result}"
)
Stack multiple tensors
z1
=
torch.
tensor
(
[
1
,
2
,
3
]
)
z2
=
torch.
tensor
(
[
4
,
5
,
6
]
)
z3
=
torch.
tensor
(
[
7
,
8
,
9
]
)
result
=
torch.
vstack
(
[
z1
,
z2
,
z3
]
)
(
"nMultiple 1D tensor stacking:"
)
(
f
" result:n{result}"
)
The output is:
一维张量垂直堆叠:
x1: tensor([1, 2, 3])
x2: tensor([4, 5, 6])
vstack:
tensor([[1, 2, 3],
[4, 5, 6]])
Vertical stacking of 2D tensors:
y1:
tensor([[1, 2],
[3, 4]])
y2:
tensor([[5, 6],
[7, 8]])
vstack:
tensor([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
Stacking multiple one-dimensional tensors:
result:
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])