Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython: how to resolve TypeError: Cannot convert memoryviewslice to numpy.ndarray?

Inside a random_stuff_printer.pyx file, I have a cdef function that looks something like this:

cdef np.ndarray[np.float64_t, ndim=4] randomizer():
    return np.random.random((4, 4, 4, 4))

Then I have a def function that looks like this, inside the same random_stuff_printer.pyx:

def random_printer():
    random_stuff = randomizer()
    print random_stuff

I compile the file, and call random_printer, but I get the following error:

TypeError: Cannot convert random_stuff_printer._memoryviewslice to numpy.ndarray

How can I fix this issue?

like image 454
bzm3r Avatar asked Oct 12 '25 01:10

bzm3r


1 Answers

I believe that this is an issue of keeping your def, cdefs, and cimport and imports straight. Here's some code that works for me:

import numpy as np
cimport numpy as cnp

cdef cnp.ndarray[cnp.float64_t, ndim=4] randomizer():    
    return np.random.random((4, 4, 4, 4))

def random_printer():
    cdef foo = randomizer()
    print(foo)

See for example this notebook: http://nbviewer.ipython.org/gist/arokem/6fa00ceb17e16c367c8a

like image 145
arokem Avatar answered Oct 14 '25 18:10

arokem