背景:tensor的维度一直令我疑惑,在此记录一下。
注意: 首先,能添加的维度是有限制的,假设为tensor
添加维度,其中添加的维度是有个范围限制(左闭右开)的:
[
−
tensor
.
d
i
m
(
)
−
1
,
tensor
.
d
i
m
(
)
+
1
)
[-\text{tensor}.dim() - 1, \text{tensor}.dim() + 1)
[−tensor.dim()−1,tensor.dim()+1)当添加的维度为负数时,可以根据以下公式转换到正数的维度
dim
=
dim
+
tensor
.
d
i
m
(
)
+
1.
\text{dim} = \text{dim} + \text{tensor}.dim() + 1.
dim=dim+tensor.dim()+1.
0维度
指的是最外面的维度, 也就是最外层的框
a = torch.rand(3, 3)
print(a)
b = a.unsqueeze(0) # 添加一个0维度
print(b)
tensor([[0.7927, 0.5813, 0.9975],
[0.0247, 0.5305, 0.5472],
[0.5818, 0.2442, 0.4680]])
tensor([[[0.7927, 0.5813, 0.9975],
[0.0247, 0.5305, 0.5472],
[0.5818, 0.2442, 0.4680]]])
可以看到,在看到在0维度
添加一个维度以后,在最外面多了一个框。 以此类推,一个tensor的维度的最大值指的是最里面的那个框