numpy 中sum(axis=0), 对axis的理解

sum函数中的axis

相当于去除axis指定的那个维度。
例如:a维度是(2,3,4),则a.sum(axis=0) 结果为(3,4)
a.sum(axis=1)结果为(2,4)。
即除了axis指定的那个维度外,其它维度索引值相同就累加。

def dfs_index(a, dim, index, outlist):
    '''
    get all indexs for a
    '''
    if dim >= a.ndim:
        #print(index)
        outlist.append(index.copy())
        return
    for val in range(a.shape[dim]):
        index[dim] = val
        dfs_index(a, dim+1, index, outlist)

def sum_axis(a, axis=0):
    '''
    imitate numpy sum
    '''
    shape_list = list(a.shape)
    # delete the item at axis
    shape_list.pop(axis)
    acc_sum = np.zeros(tuple(shape_list), dtype=a.dtype)
    out = []
    dfs_index(a, 0, [0]*a.ndim, out)
    for ind in out:
        #print("ind", ind)
        sum_ind = ind.copy()
        sum_ind.pop(axis)
        #print("sum_ind", sum_ind)
        acc_sum[tuple(sum_ind)] += a[tuple(ind)]
    return acc_sum

>>> a = np.arange(6).reshape(2,3)
array([[0, 1, 2],
       [3, 4, 5]])
>>> a.sum(0)
array([3, 5, 7])
>>> sum_axis(a, 0)
array([3, 5, 7])
>>> a.sum(1)
array([ 3, 12])
>>> sum_axis(a, 1)
array([ 3, 12])

# test case 2
>>> b = np.arange(24).reshape(3,2,4)
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]],

       [[16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> b.sum(0)
array([[24, 27, 30, 33],
       [36, 39, 42, 45]])
>>> sum_axis(b, 0)
array([[24, 27, 30, 33],
       [36, 39, 42, 45]])
>>> b.sum(1)
array([[ 4,  6,  8, 10],
       [20, 22, 24, 26],
       [36, 38, 40, 42]])
>>> sum_axis(b, 1)
array([[ 4,  6,  8, 10],
       [20, 22, 24, 26],
       [36, 38, 40, 42]])
>>> b.sum(2)
array([[ 6, 22],
       [38, 54],
       [70, 86]])
>>> sum_axis(b, 2)
array([[ 6, 22],
       [38, 54],
       [70, 86]])
... other test case
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值