numpy数组操作

...符号用来省略:

代码如下

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(a, a.shape)
b = a[..., 1]
c = a[1, ...]
print("切片b:\n", b, b.shape)
print("切片c:\n", c, c.shape)

输出:

D:\Anaconda3\envs\tensorflow_gpu\python.exe E:/programSpace/PythonPrograme/test/test.py
[[1 2 3]
 [4 5 6]
 [7 8 9]] (3, 3)
切片b:
 [2 5 8] (3,)
切片c:
 [4 5 6] (3,)

可见,选取矩阵中的一行或者一列数据切片出来都是一维数组

对多行或者多列进行切片操作

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(a, a.shape)
b = a[..., 1:3]
c = a[1:3, ...]
print("切片b:\n", b, b.shape)
print("切片c:\n", c, c.shape)

输出结果:

D:\Anaconda3\envs\tensorflow_gpu\python.exe E:/programSpace/PythonPrograme/test/test.py
[[1 2 3]
 [4 5 6]
 [7 8 9]] (3, 3)
切片b:
 [[2 3]
 [5 6]
 [8 9]] (3, 2)
切片c:
 [[4 5 6]
 [7 8 9]] (2, 3)

可见对二维数组进行多行或者多列切片会保留原来的排列

对于三维数组(张量)进行切片操作

a = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[11, 12, 13], [14, 15, 16], [17, 18, 19]]])
print(a, a.shape)
b = a[..., 1]
c = a[1, ...]
print("切片b\n", b, b.shape)
print("切片c\n", c, c.shape)

输出结果:

D:\Anaconda3\envs\tensorflow_gpu\python.exe E:/programSpace/PythonPrograme/test/test.py
[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[11 12 13]
  [14 15 16]
  [17 18 19]]] (2, 3, 3)
切片b
 [[ 2  5  8]
 [12 15 18]] (2, 3)
切片c
 [[11 12 13]
 [14 15 16]
 [17 18 19]] (3, 3)

可见经过切片操作,三维张量变成了二维张量

更改b的切片操作

a = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[11, 12, 13], [14, 15, 16], [17, 18, 19]]])
print(a, a.shape)
b = a[..., 1:2]
print("切片b\n", b, b.shape)

结果:

D:\Anaconda3\envs\tensorflow_gpu\python.exe E:/programSpace/PythonPrograme/test/test.py
[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[11 12 13]
  [14 15 16]
  [17 18 19]]] (2, 3, 3)
切片b
 [[[ 2]
  [ 5]
  [ 8]]

 [[12]
  [15]
  [18]]] (2, 3, 1)

区别使用'b = a[..., 1:2]和b = a[..., 1]'可以达到不变或者降维的效果

在深度学习里,描述特征图张量喜欢用h*w*n来分别表示特征图的高*宽*通道数,但是在numpy数组里面,要达到同样的描述,需要修改为n*w*h

你可能感兴趣的:(numpy数组操作)