张量

0维向量

一维张量

向量就是一维张量。一维张量没有行和列的概念,只有长度的概念。如:

1
2
3
4
5
6
import numpy as np
a = np.array([1,2,3,4])
print(a)
>>>[1 2 3 4]
print(a.shape)
>>>(4,)

二维张量

矩阵就是二维张量,如:

1
2
3
4
5
6
7
8
import numpy as np
b = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
print(b)
>>>[[1 2 3 4]
[5 6 7 8]
[9 10 11 12]]
print(b.shape)
>>>(3,4)

打印出来的就是一个三行四列的矩阵。

三维张量

三维张量在行和列的基础上增加了深度的方向。

代码:

1
2
3
4
5
6
7
import numpy as np
c = np.array([[[1,2,3],[4,5,6]]])
print(c)
>>>[[[1 2 3]
[4 5 6]]]
print(c.shape)
>>>(1,2,3)

打印的是深度为1的二行三列的三维张量

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import numpy as np
d = np.array([[[1,2],[3,4],[5,6],[7,8]],[[11,12],[13,14],[15,16],[17,18]],[[21,22],[23,24],[25,26],[27,28]]])
print(d)
>>>[[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]]

[[11 12]
[13 14]
[15 16]
[17 18]]

[[21 22]
[23 24]
[25 26]
[27 28]]]
print(d.shape)
>>>(3, 4, 2)

打印的是一个深度为2的二行三列三维张量。

四维张量

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import numpy as np
e = np.array([[[[1,2],[3,4],[5,6],[7,8]],[[11,12],[13,14],[15,16],[17,18]],[[21,22],[23,24],[25,26],[27,28]]],[[[1,2],[3,4],[5,6],[7,8]],[[11,12],[13,14],[15,16],[17,18]],[[21,22],[23,24],[25,26],[27,28]]]])
print(e)
>>>[[[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]]

[[11 12]
[13 14]
[15 16]
[17 18]]

[[21 22]
[23 24]
[25 26]
[27 28]]]


[[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]]

[[11 12]
[13 14]
[15 16]
[17 18]]

[[21 22]
[23 24]
[25 26]
[27 28]]]]

print(e.shape)
>>>(2, 3, 4, 2)