PyTorch torch.expand function
PyTorch torch reference manual
torch.expand is a PyTorch function for expanding tensor dimensions. It expands a tensor by creating a view with repeated elements, without actually copying data.
The expanded tensor is a view that shares the original data in memory, making this a memory-efficient operation.
Function definition
torch.expand(*sizes)
torch.expand(input, *sizes)
Parameters:
input(Tensor): the input tensor.*sizes(torch.Size or int): Target size. A single dimension may be -1, meaning that dimension is kept unchanged. Dimensions of size 1 can be expanded to larger sizes.
Return Value:
torch.Tensor: Returns the expanded tensor view.
Usage examples
Example
import
torch
Create a tensor with a dimension of size 1
x
=
torch.
tensor
(
[
[
1
]
,
[
2
]
,
[
3
]
]
)
(
"Original tensor:"
)
(
x
)
(
"Shape:"
,
x.
shape
)
Expand to a larger size
y
=
x.
expand
(
3
,
4
)
(
"nAfter expansion:"
)
(
y
)
(
"Shape:"
,
y.
shape
)
The output is:
原始张量:
tensor([[1],
[2],
[3]])
形状: torch.Size([3, 1])
Extended:
tensor([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
形状: torch.Size([3, 4])
Example
import
torch
Use -1 to keep a dimension unchanged
x
=
torch.
tensor
(
[
1
,
2
,
3
,
4
]
)
Expand to a 2x4 tensor
y
=
x.
expand
(
2
,
1
)
(
"Original:"
,
x.
shape
)
(
"After expansion:"
,
y.
shape
)
(
y
)
The output is:
原始: torch.Size([4])
扩展后: torch.Size([2, 4])
tensor([[1, 2, 3, 4],
[1, 2, 3, 4]])
Example
import
torch
Application scenarios of broadcasting
Expand a column vector into a matrix
column
=
torch.
randn
(
5
,
1
)
Expand to add with a matrix
matrix
=
torch.
randn
(
5
,
10
)
Broadcasting: column vectors are extended automatically
result
=
matrix + column
(
"Column vector shape:"
,
column.
shape
)
(
"Matrix shape:"
,
matrix.
shape
)
(
"Result shape:"
,
result.
shape
)
The output is:
列向量形状: torch.Size([5, 1])
矩阵形状: torch.Size([5, 10])
结果形状: torch.Size([5, 10])
Example
import
torch
Expand from a 2D tensor to 3D
x
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
]
)
Expand the third dimension
y
=
x.
expand
(
2
,
2
,
3
)
(
"Original shape:"
,
x.
shape
)
(
"Expanded shape:"
,
y.
shape
)
(
"nExpanded tensor:"
)
(
y
)
Verify that data is shared
(
"nModify the original tensor:"
)
x
[
0
,
0
]
=
100
(
"x[0,0]:"
,
x
[
0
,
0
]
)
(
"y[0,0,0]:"
,
y
[
0
,
0
,
0
]
)
The output is:
原始形状: torch.Size([2, 3])
扩展后形状: torch.Size([2, 2, 3])
Extended tensor:
tensor([[[1, 2, 3],
[4, 5, 6]],
[[1, 2, 3],
[4, 5, 6]]])
Modify original tensor:
x[0,0]: tensor(100)
y[0,0,0]: tensor(100)
注意:torch.expand 只可以扩展维度大小为1的维度到更大的尺寸。不能将大于1的维度缩小或扩展到不同的尺寸。返回的是视图,不是副本。
Pytorch torch 参考手册