简体   繁体   English

float64到float32 Cython错误

[英]float64 to float32 Cython Error

I've created a Cython code to make matrix operations between a dense matrix and a sparse vector,as follows (as I'm learning Cython I'm not sure this is a good code, but it's the best I could come up with so far): 我已经创建了一个Cython代码来在密集矩阵和稀疏向量之间进行矩阵运算,如下所示(因为我正在学习Cython我不确定这是一个很好的代码,但它是我能想到的最好的代码远):

import numpy as np
cimport numpy as np
ctypedef np.float64_t dtype_t
ctypedef np.int32_t dtypei_t
cimport cython

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
def cdenseXsparse(np.ndarray[dtype_t, ndim = 2] Y,
                  np.ndarray[dtype_t, ndim = 1] V,
                  np.ndarray[dtypei_t, ndim = 1] I,
                  np.ndarray[dtype_t, ndim = 1] A = None):
    """
    Computes A = Y * (V_I)
    """
    if Y is None:
        raise ValueError("Input cannot be Null")
    A = np.zeros(Y.shape[1])
    cdef Py_ssize_t i, indice
    cdef dtype_t s  
    for i in range(A.shape[0]):             
        s = 0
        for indice in range(len(I)):
            s += Y[I[indice], i] * V[indice]
        A[i] = s
    return A    

It works fine. 它工作正常。 But when I change the third line from: 但是当我改变第三行时:

ctypedef np.float64_t dtype_t

to: 至:

ctypedef np.float32_t dtype_t

and compile the .pyx file and run again the matrix operations I get the error: 并编译.pyx文件并再次运行矩阵操作我得到错误:

"Buffer dtype mismatch, expected 'dtype_t' but got 'long'"

As an example, when compiling using np.float32_t and running the code: 例如,在使用np.float32_t进行编译并运行代码时:

In [3]: from numpy import random as rd, array, int32, float32

In [4]: y = array(rd.rand(10, 200), dtype = float32)

In [5]: v = array([1, 2, 3], dtype = float32)

In [6]: i = array([0, 1, 2], dtype = int32) 

In [7]: from cdenseXsparse import cdenseXsparse

In [8]: r = cdenseXsparse(y, v, i)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-319f9c8c8d49> in <module>()
----> 1 r = cdenseXsparse(y, v, i)

/home/will/workspace/s3_RecSys/SVD/cdenseXsparse.so in cdenseXsparse.cdenseXsparse     (cdenseXsparse.c:1484)()

ValueError: Buffer dtype mismatch, expected 'dtype_t' but got 'double'

Is there a different way to use float32 in Cython? 在Cython中使用float32有不同的方法吗? Using float64 and float32 shouldn't work the same way? 使用float64和float32不应该以相同的方式工作?

For what I've researched so far it should work the same, but it didn't in that code. 对于我到目前为止所研究的内容它应该工作相同,但它没有在那段代码中。

Thanks in advance! 提前致谢!

The default behaviour of np.zeros is to create a float64 data, if you want to force the datatype to be float32 you should specify it. np.zeros的默认行为是创建一个float64数据,如果要强制数据类型为float32,则应指定它。 You should also put all cdefs in the beginning of the function. 您还应该将所有cdef放在函数的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM