Ste*_*and 16 python numpy scipy
我在某些代码中遇到过numpy.apply_along_axis函数.我不明白有关它的文档.
这是文档的一个示例:
>>> def new_func(a):
... """Divide elements of a by 2."""
... return a * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(new_func, 0, b)
array([[ 0.5, 1. , 1.5],
[ 2. , 2.5, 3. ],
[ 3.5, 4. , 4.5]])
Run Code Online (Sandbox Code Playgroud)
至于我认为我理解文档,我原以为:
array([[ 0.5, 1. , 1.5],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]])
Run Code Online (Sandbox Code Playgroud)
即在[[1,2,3],[4,5,6],[7,8,9]中沿轴[1,2,3]应用函数,即轴0
显然我错了.你能纠正我吗?
tal*_*ies 15
apply_along_axis
沿着输入数组的1D切片应用提供的函数,沿您指定的轴截取切片.因此,在您的示例中,new_func
沿着第一个轴应用于数组的每个切片.如果使用向量值函数而不是标量,它会变得更清晰:
In [20]: b = np.array([[1,2,3], [4,5,6], [7,8,9]])
In [21]: np.apply_along_axis(np.diff,0,b)
Out[21]:
array([[3, 3, 3],
[3, 3, 3]])
In [22]: np.apply_along_axis(np.diff,1,b)
Out[22]:
array([[1, 1],
[1, 1],
[1, 1]])
Run Code Online (Sandbox Code Playgroud)
这里,numpy.diff
沿着输入阵列的第一轴或第二轴(尺寸)的每个切片施加.
该函数在沿轴 = 0 的一维数组上执行。您可以使用“axis”参数指定另一个轴。这种范式的用法是:
np.apply_along_axis(np.cumsum, 0, b)
Run Code Online (Sandbox Code Playgroud)
该函数沿维度 0 在每个子数组上执行。因此,它适用于一维函数,并为每个一维输入返回一个一维数组。
另一个例子是:
np.apply_along_axis(np.sum, 0, b)
Run Code Online (Sandbox Code Playgroud)
为一维数组提供标量输出。当然,您可以只在 cumsum 或 sum 中设置轴参数来执行上述操作,但这里的重点是它可以用于您编写的任何一维函数。