PyTorch torch.tile function
PyTorch torch reference manual
torch.tile is a function in PyTorch used to repeat a tensor multiple times.
Function definition
torch.tile(input, dims)
Usage examples
Example
import
torch
Repeat a one-dimensional tensor
x
=
torch.
tensor
(
[
1
,
2
,
3
]
)
(
"Original 1D tensor:"
)
(
x
)
result
=
torch.
tile
(
x
,
3
)
(
"Repeated 3 times:"
)
(
result
)
Repeat a 2D tensor
y
=
torch.
tensor
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
(
"nOriginal 2D tensor:"
)
(
y
)
result
=
torch.
tile
(
y
,
(
2
,
3
)
)
(
"Repeated 2 times along rows and 3 times along columns:"
)
(
result
)
Repeat a 3D tensor
z
=
torch.
tensor
(
[
[
[
1
,
2
]
,
[
3
,
4
]
]
]
)
(
"nOriginal 3D tensor:"
)
(
z
)
result
=
torch.
tile
(
z
,
(
2
,
1
,
2
)
)
(
"Repeated with shape [2, 1, 2]:"
)
(
result
)
(
f
"Shape: {result.shape}"
)
The output is:
原始一维张量:
tensor([1, 2, 3])
Repeat 3 times:
tensor([1, 2, 3, 1, 2, 3, 1, 2, 3])
Original two-dimensional tensor:
tensor([[1, 2],
[3, 4]])
Repeat 2 times along the row, repeat 3 times along the column:
tensor([[1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4],
[1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4]])
Original three-dimensional tensor:
tensor([[[1, 2],
[3, 4]]])
Shape [2, 1, 2] repeated:
tensor([[[1, 2, 1, 2],
[3, 4, 3, 4]],
[[1, 2, 1, 2],
[3, 4, 3, 4]]])
形状: torch.Size([2, 2, 4])