tensor有三个属性:数据类型、维度(阶/rank)、shape。
1、数据类型
这个暂时我还没接触到,暂存截图
2、维度
维度要看张量的最左边有多少个左中括号,有n个,则这个张量就是n维张量。
for example:
1 #维度为0的标量
[1,2,3] #维度为1,一维向量
[[1,2],[3,4]] #维度为2, 二维矩阵
[[[1,2],[3,4]],[[1,2],[3,4]]] #维度为3,3维空间矩阵
可以认为一个二阶张量就是我们平常所说的矩阵,一阶张量可以认为是一个向量。对于一个二阶张量你可以用语句t[i, j]来访问其中的任何元素,而对于三阶张量你可以用’t[i, j, k]'来访问其中的任何元素。
3、形状(shape)
1 # 形状为[]
[1,2,3] # 形状为[3]
[[1,2],[3,4]] # 形状为[2,2]
[[[1,2],[3,4]],[[1,2],[3,4]]] # 形状为[2,2,2]
便于记忆
- 在形状的中括号中有多少个数字,就代表这个张量是多少维的张量。
- 从左面的括号开始看,形状的第一个元素要看张量最外边的中括号中有几个元素
- 形状的第二个元素要看张量中最左边的第二个中括号中有几个被逗号隔开的元素
- 之后类推
在来个例子,这个总结的常常会在shape、reshape中用到
>>> x = np.array([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
>>> np.squeeze(x, axis=0).shape
(3, 1)
>>> np.squeeze(x, axis=1).shape
Traceback (most recent call last):
...
ValueError: cannot select an axis to squeeze out which has size not equal to one
>>> np.squeeze(x, axis=2).shape
(1, 3)
4、np.squeeze(x, axis=0)(从数组的形状中删除一维条目)
这几块知识常常在一起用到。axis用来指定shape中的一维条目,从0开始
每一维度中的数据必须严格地格式对齐
否则:
x = torch.FloatTensor([[[1,2,3],[0]],[[2,0,0],[2]]])
print(x.shape)
Traceback (most recent call last):
File "C:\Users\w1573\deep-learning-for-image-processing-master\pytorch_classification\Test2_alexnet\practice.py", line 4, in <module>
x = torch.FloatTensor([[[1,2,3],[0]],[[2,0,0],[2]]])
ValueError: expected sequence of length 3 at dim 2 (got 1)
x = torch.FloatTensor([[[1,2,3],[0,0,0]],[[2,0,0],[2]]])
print(x.shape)
Traceback (most recent call last):
File "C:\Users\w1573\deep-learning-for-image-processing-master\pytorch_classification\Test2_alexnet\practice.py", line 4, in <module>
x = torch.FloatTensor([[[1,2,3],[0,0,0]],[[2,0,0],[2]]])
ValueError: expected sequence of length 3 at dim 2 (got 1)
必须严格对齐!!!
x = torch.FloatTensor([[[1,2,3],[0,0,0]],[[2,0,0],[2,0,0]]])
print(x.shape)
#结果,每一维度都对齐
torch.Size([2, 2, 3])
5、torch.stack()例子
import torch
T1 = torch.tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
T2 = torch.tensor([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
print(torch.stack((T1,T2),dim=0))
print(torch.stack((T1,T2),dim=0).shape)
print(torch.stack((T1,T2),dim=1).shape)
print(torch.stack((T1,T2),dim=2).shape)
print(torch.stack((T1,T2),dim=3).shape)
##输出
tensor([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]])##T1,T2按0维拼接,故shape为torch.Size([2, 3, 3]),输出见👆
torch.Size([2, 3, 3])
torch.Size([3, 2, 3])
torch.Size([3, 3, 2])
Traceback (most recent call last):
File "C:\Users\w1573\deep-learning-for-image-processing-master\pytorch_classification\Test2_alexnet\practice.py", line 15, in <module>
print(torch.stack((T1,T2),dim=3).shape)
IndexError: Dimension out of range (expected to be in range of [-3, 2], but got 3)