PyTorch torch.expand_as function
PyTorch torch reference manual
torch.expand_as is a PyTorch function for expanding a tensor to the same size as another tensor. It is a torch.expand convenience version of that, automatically using the reference tensor's size for expansion.
Function definition
torch.expand_as(other)
Parameters:
other(Tensor): Reference tensor; the current tensor will be expanded to the same size as this tensor.
Return Value:
torch.Tensor: Returns the expanded tensor view.
Usage examples
Example
import
torch
Create a vector
x
=
torch.
tensor
(
[
1
,
2
,
3
,
4
]
)
Create a target matrix
other
=
torch.
randn
(
3
,
4
)
Expand x to the same shape as other
y
=
x.
expand_as
(
other
)
(
"Original vector shape:"
,
x.
shape
)
(
"Reference tensor shape:"
,
other.
shape
)
(
"Expanded shape:"
,
y.
shape
)
(
"nExpanded tensor:"
)
(
y
)
The output is:
原始向量形状: torch.Size([4])
参考张量形状: torch.Size([3, 4])
扩展后形状: torch.Size([3, 4])
Extended tensor:
tensor([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
Example
import
torch
Create a column vector
x
=
torch.
tensor
(
[
[
1
]
,
[
2
]
,
[
3
]
]
)
Create a target 3D tensor
other
=
torch.
randn
(
3
,
4
,
5
)
Expand x to the same shape as other
y
=
x.
expand_as
(
other
)
(
"Original column vector shape:"
,
x.
shape
)
(
"Reference tensor shape:"
,
other.
shape
)
(
"Expanded shape:"
,
y.
shape
)
The output is:
原始列向量形状: torch.Size([3, 1])
参考张量形状: torch.Size([3, 4, 5])
扩展后形状: torch.Size([3, 4, 5])
Example
import
torch
Application example in neural networks
Suppose a bias vector needs to be broadcast to a feature map
bias
=
torch.
tensor
(
[
0.1
,
0.2
,
0.3
]
)
Bias for 3 channels
Simulate a feature map from a convolution output (batch, channel, height, width)
feature_map
=
torch.
randn
(
8
,
3
,
32
,
32
)
Expand the bias to the same shape as the feature map
bias_expanded
=
bias.
expand_as
(
feature_map
)
(
"Bias shape:"
,
bias.
shape
)
(
"Feature map shape:"
,
feature_map.
shape
)
(
"Expanded bias shape:"
,
bias_expanded.
shape
)
Add bias
output
=
feature_map + bias_expanded
(
"nOutput shape after adding bias:"
,
output.
shape
)
The output is:
偏置形状: torch.Size([3])
特征图形状: torch.Size([8, 3, 32, 32])
扩展后偏置形状: torch.Size([8, 3, 32, 32])
加上偏置后的输出形状: torch.Size([8, 3, 32, 32])
Note:torch.expand_as Only dimensions of size 1 can be expanded to larger sizes.other The tensor's size must be compatible with the expanded size (i.e. the current tensor's dimensions can be broadcast to the target size). A view is returned, not a copy.