numpy数组维度
1 | import numpy as np |
1 | arr_1 = np.array([1, 2, 3, 4]) |
output:
arr_1 = [1 2 3 4]
shape of arr_1: (4,) , dimension of arr_1: 1
1 | arr_2 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) |
output:
arr_2 =
[[1 2 3 4]
[5 6 7 8]]
shape of arr_2: (2, 4) , dimension of arr_2: 2
1 | arr_3 = np.array([[[1, 2, 3, 4], [5, 6, 7, 8]], [[1, 2, 3, 4], [5, 6, 7, 8]], [[1, 2, 3, 4], [5, 6, 7, 8]]]) |
output:
arr_3 =
[[[1 2 3 4]
[5 6 7 8]]
[[1 2 3 4]
[5 6 7 8]]
[[1 2 3 4]
[5 6 7 8]]]
shape of arr_3: (3, 2, 4) , dimension of arr_3: 3
numpy数组切片中[…]的理解
假设 x 是一个数组,np.ndim(x) == 5
x[1,2,...]
==x[1,2,:,:,:]
x[...,3]
==x[:,:,:,:,3]
x[4,...,5,:]
==x[4,:,:,5,:]
numpy数组切片中None的理解
None 的作用就是在相应的位置上增加了一个维度,在这个维度上只有一个元素
假设 x.shape == (a, b),则
(a, b)
==>[None, :, :]
==>(1, a, b)
(a, b)
==>[:, None, :]
==>(a, 1, b)
(a, b)
==>[:, :, None]
==>(a, b, 1)
1 | import numpy as np |
output:
arr =
[[1 2 3]
[4 5 6]]
shape of arr: (2, 3) , dimension of arr: 2
1 | None_1 = arr[None, :, :] |
output:
None_1 =
[[[1 2 3]
[4 5 6]]]
shape of None_1: (1, 2, 3) , dimension of None_1: 3
1 | None_2 = arr[:, None, :] |
output:
None_2 =
[[[1 2 3]]
[[4 5 6]]]
shape of None_2: (2, 1, 3) , dimension of None_2: 3
1 | None_3 = arr[:, :, None] |
output:
None_3 =
[[[1]
[2]
[3]]
[[4]
[5]
[6]]]
shape of None_3: (2, 3, 1) , dimension of None_3: 3
numpy[…, None]的理解
1 | None_3 = arr[..., None] # 等价于 None_3 = arr[:, :, None] |
output:
None_3 =
[[[1]
[2]
[3]]
[[4]
[5]
[6]]]
shape of None_3: (2, 3, 1) , dimension of None_3: 3
1 | y = np.arange(12).reshape((2,2,3)) |
output:
y =
[[[ 0 1 2]
[ 3 4 5]]
[[ 6 7 8]
[ 9 10 11]]]
shape of y: (2, 2, 3) , dimension of y: 3
1 | y = y[..., None] |
output:
y =
[[[[ 0]
[ 1]
[ 2]]
[[ 3]
[ 4]
[ 5]]]
[[[ 6]
[ 7]
[ 8]]
[[ 9]
[10]
[11]]]]
shape of y: (2, 2, 3, 1) , dimension of y: 4