np.expand_dims()用于扩展数组的形状
参数:
values:数组
axis:表示在该位置添加数据
示例:
import numpy as np
a = np.array([1,2,3])
print(a)
print(a.shape)
"""
输出:
[1 2 3]
(3,)
"""
b = np.array([[1,2,3],[4,5,6]])
print(a)
print(a.shape)
"""
输出:
[[1 2 3]
[4 5 6]]
(2, 3)
"""
c = np.expand_dims(b, axis=0)
print(c)
print(c.shape)
print(c[0][0][0])
print(c[0][0][1])
print(c[0][0][2])
print(c[0][1][0])
print(c[0][1][1])
print(c[0][1][2])
"""
输出:
[[[1 2 3]
[4 5 6]]]
(1, 2, 3)
1
2
3
4
5
6
"""
d = np.expand_dims(b, axis=1)
print(d)
print(d.shape)
print(d[0][0][0])
print(d[0][0][1])
print(d[0][0][2])
print(d[1][0][0])
print(d[1][0][1])
print(d[1][0][2])
"""
输出:
[[[1 2 3]]
[[4 5 6]]]
(2, 1, 3)
1
2
3
4
5
6
"""
e = np.expand_dims(b, axis=2)
print(e)
print(e.shape)
print(e[0][0][0])
print(e[0][1][0])
print(e[0][2][0])
print(e[1][0][0])
print(e[1][1][0])
print(e[1][2][0])
"""
输出:
[[[1]
[2]
[3]]
[[4]
[5]
[6]]]
(2, 3, 1)
1
2
3
4
5
6
"""
f = np.array([[[1,2,3],[4,5,6]]])
print(f)
print(f.shape)
"""
输出:
[[[1 2 3]
[4 5 6]]]
(1, 2, 3)
"""
g = np.expand_dims(f, 0)
print(g)
print(g.shape)
print('g[0][0][0]: ',g[0][0][0])
print('g[0][0][1]: ',g[0][0][1])
"""
输出:
[[[[1 2 3]
[4 5 6]]]]
(1, 1, 2, 3)
g[0][0][0]: [1 2 3]
g[0][0][1]: [4 5 6]
"""
g = np.expand_dims(f, 1)
print(g)
print(g.shape)
print('g[0][0][0]: ',g[0][0][0])
print('g[0][0][1]: ',g[0][0][1])
"""
输出:
[[[[1 2 3]
[4 5 6]]]]
(1, 1, 2, 3)
g[0][0][0]: [1 2 3]
g[0][0][1]: [4 5 6]
"""
g = np.expand_dims(f, 2)
print(g)
print(g.shape)
print('g[0][0][0]: ',g[0][0][0])
print('g[0][1][0]: ',g[0][1][0])
"""
输出:
[[[[1 2 3]]
[[4 5 6]]]]
(1, 2, 1, 3)
g[0][0][0]: [1 2 3]
g[0][1][0]: [4 5 6]
"""
g = np.expand_dims(f, 3)
print(g)
print(g.shape)
"""
输出:
[[[[1]
[2]
[3]]
[[4]
[5]
[6]]]]
(1, 2, 3, 1)
"""