numpy中axis选项背后的算法是什么?

问题描述 投票:0回答:1

我不明白numpy中的轴如何用于任何常规n维数组

例如,np.mean(array, axis=1)将给出预期的数组,而不考虑array的形状。

[如果我想不使用numpy编写代码,则可以对k-D数组进行求平均,例如,带有轴选项的mean_1dmean_2d,...。但是,我无法想象如何使单个函数适用于具有任何k值的任何输入数组。到目前为止,我找不到有关numpy轴如何工作的解释。有人可以帮助我了解幕后发生的事情吗?

添加:我的最初目标是使用numba编写代码,以进行具有异常排除的快速数组组合(即,nD数组列表的sigma-clipped中位数组合并获得(n-1)-D数组)。

arrays numpy
1个回答
0
投票

如果数组的大小允许,您可以递归查看。我刚刚测试了下面的代码,它似乎对于沿轴3的求和函数工作正常。这很简单,但应该可以传达出这样的想法:

import numpy as np

a = np.ones((3,4,5,6,7))

# first get the shape of the result
def shape_res(sh1, axis) :
    sh2 = [sh1[0]]

    if len(sh1)>0 :
        for i in range(len(sh1)) :
            if i > 0 and i != axis :
                sh2.append(sh1[i])
            elif i == axis :
                # shrink the summing axis
                sh2.append(1)
    return sh2


def sum_axis(a, axis=0) : 
    cur_sum = 0
    sh1 = np.shape(a)
    sh2 = shape_res(sh1, axis)

    res = np.zeros(sh2)
    print(sh1, sh2)

    def rec_fun (a, res, cur_axis) :
        for i in range(len(a)) :
            if axis > cur_axis :
                # dig in the array to reach the right axis
                next_axis = cur_axis + 1
                rec_fun(a[i], res[i], next_axis)
            elif axis == cur_axis :
                # sum along the given axis
                res[0] += a[i]

    rec_fun(a, res, cur_axis)
    return res

result = sum_axis(a, axis=3)
print(result)
© www.soinside.com 2019 - 2024. All rights reserved.