【问题标题】:Cython: memory views on `numpy` arrays lose `numpy` array features?Cython:“numpy”数组的内存视图失去了“numpy”数组功能?
【发布时间】:2015-03-09 02:41:10
【问题描述】:

考虑以下示例:

cdef test_function():
    cdef:
        double[:] p1 = np.array([3.2, 2.1])
        double[:] p2 = np.array([0.9, 6.])

    return p1-p2

如果使用,则返回以下错误:

Error compiling Cython file:
------------------------------------------------------------
...
cdef test_function():
    cdef:
        double[:] p1 = np.array([3.2, 2.1])
        double[:] p2 = np.array([0.9, 6.])

    return p1-p2
            ^
------------------------------------------------------------

cython_cell_v3.pyx:354:13: Invalid operand types for '-' (double[:]; double[:])

如果我使用 numpy 数组来初始化内存视图,我该如何使用它的功能?我是否必须以某种方式对内存视图进行取消引用?

【问题讨论】:

    标签: python numpy cython


    【解决方案1】:

    这行得通:

    cpdef test_function():
        cdef:
            double[:] p1 = np.array([3.2, 2.1])
            double[:] p2 = np.array([0.9, 6.])
    
        # return p1-p2
        cdef int I
        I = p1.shape[0]
        for i in range(I):
            p1[i] -= p2[i]
        return np.asarray(p1)
    print "Test _function", test_function()
    

    我对数组进行迭代,就好像它们是“c”数组一样。如果没有最后的np.asarray,它只会显示

    >>> memview.test_function()
    <MemoryView of 'ndarray' at 0xb60e772c>
    

    另见示例 http://docs.cython.org/src/userguide/memoryviews.html#comparison-to-the-old-buffer-support


    我尝试了不同的功能:

    cpdef test_function1(x):
        cdef:
            int i, N = x.shape[0]
            double[:] p1 = x
        for i in range(N):
            p1[i] *= p1[i]
        return np.asarray(p1)*2
    
    x = np.arange(10.)
    print "test_function1 return", test_function1(x)
    print "x after test_function1", x
    

    正如所料,函数x 之后是x**2。但是函数返回的是2*x**2

    我直接修改p1,但最终也修改了x。我认为p1x 的一种视图,但功能有所减少。 np.asarray(p1) 为其提供了numpy 功能,因此我可以对其执行数组* 并返回结果(无需进一步修改x)。

    如果我用以下方式完成了函数:

    out = np.asarray(p1)
    out *= 2
    return out 
    

    我最终也修改了原来的xoutx 的一个 numpy 视图。 out 表现得像一个数组,因为它是一个数组,而不是因为与 x 的某个远距离链接。

    【讨论】:

    • 是的;我正在纠正它。我更关注是否需要创建返回数组或内存视图,而不是算术运算符。
    • 我不知道我是否可以仅仅因为我没有寻找任何解决方案而接受这个作为答案,但特别是我想知道 numpy 数组的类型化内存视图如何仍然记得它们是numpy 数组?
    • 我添加了一个函数,显示 memoryview 是 view,但功能有所减少。
    猜你喜欢
    • 2014-01-25
    • 2014-01-27
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多