axis=0 axis=1 axis=2 在numpy中的区别

背景:

在图像数据处理的过程中,处理的数据大多是矩阵或者多维数组。同时,对多维数组或者矩阵的操作有多种可能,为了帮助实现对数组或矩阵各种各样的功能,就有了axis这一参数。


样例:

1 随机创建一个三维数据:

import numpy as np
# 创建从0到15的矩阵:深度为2,4行2列(reshape的第一个参数为深度,其次是行,最后是列)
arr = np.arange(16).reshape(2,4,2) 

打印所创建的矩阵:

[[[ 0,  1],
  [ 2,  3],
  [ 4,  5],
  [ 6,  7]],
 [[ 8,  9],
  [10, 11],
  [12, 13],
  [14, 15]]] 

2 执行各种操作及其对应结果

(1)求和操作:

# 对数组执行sum操作
result_0 = arr.sum(axis=0)
result_1 = arr.sum(axis=1)
result_2 = arr.sum(axis=2)
print('result_0:',result_0,'result_1:',result_1,'result_2:',result_2)

输出结果:

result_0:
[[ 8, 10]
 [12, 14]
 [16, 18]
 [20, 22]]
result_1:
[[12, 16]
 [44, 48]]
result_2:
[[ 1,  5,  9, 13]
 [17, 21, 25, 29]]

可见当axis=0时,表示通道方向,是对各个通道上相同位置的元素进行求和;
当axis=1时,是对矩阵每一列求和;
当axis=2时,是对矩阵每一行求和。

(2)求最小值

result_0 = arr.min(axis=0)
result_1 = arr.min(axis=1)
result_2 = arr.min(axis=2)
print('result_0:',result_0,'result_1:',result_1,'result_2:',result_2)

输出结果:

result_0:
[[ 0, 1]
 [ 2, 3]
 [ 4, 5]
 [ 6, 7]]
 result_1:
 [[0, 1]
  [8, 9]]
 result_2:
 [[0,  2,  4,  6]
  [8, 10, 12, 14]]

其他运算法则同理可推,只需牢记axis的数值和reshape()中的参数是一致的即可。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值