python - float64 to float32 Cython Error -
i've created cython code make matrix operations between dense matrix , sparse vector,as follows (as i'm learning cython i'm not sure code, it's best come far):
import numpy np cimport numpy 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] = none): """ computes = y * (v_i) """ if y none: raise valueerror("input cannot null") = np.zeros(y.shape[1]) cdef py_ssize_t i, indice cdef dtype_t s in range(a.shape[0]): s = 0 indice in range(len(i)): s += y[i[indice], i] * v[indice] a[i] = s return
it works fine. when change third line from:
ctypedef np.float64_t dtype_t
to:
ctypedef np.float32_t dtype_t
and compile .pyx file , run again matrix operations error:
"buffer dtype mismatch, expected 'dtype_t' got 'long'"
as example, when compiling using np.float32_t , running code:
in [3]: numpy import random 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]: = array([0, 1, 2], dtype = int32) in [7]: 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' got 'double'
is there different way use float32 in cython? using float64 , float32 shouldn't work same way?
for i've researched far should work same, didn't in code.
thanks in advance!
the default behaviour of np.zeros create float64 data, if want force datatype float32 should specify it. should put cdefs in beginning of function.
Comments
Post a Comment