numpy apply_along_axis不返回ndarray子类



我有一个ndarray子类,并正确实现了__array_wrap__np.apply_along_axis不是返回我的子类的实例,而是ndarrays。下面的代码复制了我的问题:

import numpy as np
class MySubClass(np.ndarray):
    def __new__(cls, input_array, info=None):
        obj = np.asarray(input_array).view(cls)
        obj.info = info
        return obj
    def __array_finalize__(self, obj):
        if obj is None: return
        self.info = getattr(obj, 'info', None)
    def __array_wrap__(self, out_arr, context=None):
        return np.ndarray.__array_wrap__(self, out_arr, context)
sample_ndarray = np.array([[0,5],[2.1,0]]) 
sample_subclass = MySubClass(sample_ndarray, info="Hi Stack Overflow")
# Find the smallest positive (>0) number along the first axis
min_positive = np.apply_along_axis(lambda x: np.min(np.extract(x>0,x)),
                                   0, sample_subclass)
# No more info
print hasattr(min_positive, 'info')
# Not a subclass
print isinstance(min_positive, MySubClass)
# Is an ndarray
print isinstance(min_positive, np.ndarray)

我能找到的最相关的问题是这个问题,但是似乎需要实现__array_wrap__的共识,这是我已经做过的。另外,np.extractnp.min均按预期返回子类返回子类,而当我使用apply_along_axis时,我看到了这种行为。

有什么方法可以获取我的代码返回我的子类?我正在使用numpy版本1.11.0

查看apply_along_axis代码(通过ipython ??)

Type:        function
String form: <function apply_along_axis at 0xb5a73b6c>
File:        /usr/lib/python3/dist-packages/numpy/lib/shape_base.py
Definition:  np.apply_along_axis(func1d, axis, arr, *args, **kwargs)
Source:
def apply_along_axis(func1d, axis, arr, *args, **kwargs):
...
    outarr = zeros(outshape, asarray(res).dtype)
    outarr[tuple(ind)] = res
....
    return outarr

我跳过了很多细节,但基本上它将np.zerosshapedtype一起使用,但不需要调整数组子类。

许多numpy函数将操作委托给数组的方法,或使用_wrapit_wrapit(a, 'take', indices, axis, out, mode))。

您真的需要使用apply_along_axis吗?没有什么神奇的。您可以在自己的代码中进行相同的迭代,也可以快速进行。

===================

这是2个apply_along_axis示例,也是替代实现。它们对于有意义的时间太小,我敢肯定它们的速度也一样快,甚至更多:

In [3]: def my_func(a):
    return (a[0]+a[-1]*0.5)    
In [4]: b=np.arange(1,10).reshape(3,3)
In [5]: np.apply_along_axis(my_func,0,b)
Out[5]: array([ 4.5,  6. ,  7.5])
In [6]: np.apply_along_axis(my_func,1,b)
Out[6]: array([  2.5,   7. ,  11.5])

直接阵列实现:

In [8]: b[0,:]+b[-1,:]*0.5
Out[8]: array([ 4.5,  6. ,  7.5])
In [9]: b[:,0]+b[:,-1]*0.5
Out[9]: array([  2.5,   7. ,  11.5])

第二:

In [10]: c=np.array([[8,1,7],[4,3,9],[5,2,6]])
In [11]: np.apply_along_axis(sorted, 1, c)
Out[11]: 
array([[1, 7, 8],
       [3, 4, 9],
       [2, 5, 6]])
In [12]: d=np.zeros_like(c)
In [13]: for i in range(c.shape[0]):
   ....:     d[i,:] = sorted(c[i,:]) 
In [14]: d
Out[14]: 
array([[1, 7, 8],
       [3, 4, 9],
       [2, 5, 6]])

第一个我完全跳过迭代;在第二个我使用相同的分配和迭代,开销较少。

查看np.matrixnp.ma,以获取如何实现ndarray子类的示例。


np.core.fromnumeric.py作为_wrapit函数,该功能由np.take

等函数使用
# functions that are now methods
def _wrapit(obj, method, *args, **kwds):
    try:
        wrap = obj.__array_wrap__
    except AttributeError:
        wrap = None
    result = getattr(asarray(obj), method)(*args, **kwds)
    if wrap:
        if not isinstance(result, mu.ndarray):
            result = asarray(result)
        result = wrap(result)
    return result

因此,如果obj具有__array_wrap__方法,则将其应用于数组结果。因此,您可能可以将其用作包装apply_along_axis的模型以恢复自己的课程。

最新更新