Skip to content Skip to sidebar Skip to footer

Cython: Transpose A Memoryview

Some background for the question: I'm trying to optimise a custom neural network code. It relies heavily on loops and I decided to use cython to speed up the calculation. I followe

Solution 1:

I think the best answer is "you store the numpy as an untyped python object"

cdefclass C:
    cdefobject array

    defexample_function(self):
        # if you want to use the fast Cython array indexing in a function# you can do:
        cdefnp.ndarray[np.float64_t,ndim=4] self_array = self.array
        # or
        cdefnp.float64_t[:,:,:,:] self_array2 = self.array

        # note that neither of these are copies - they're references# to exactly the same array and so if you modify one it'll modify# self.array toodeffunction2(self):
        return self.array.transpose(1,0,2,3) # works fine!

The small cost to doing it this way is that there's a bit of type-checking at the start of example_function to check that it is actually a 4D numpy array with the correct dtype. Provided you do a decent amount of work in the function that shouldn't matter.


As an alternative (if you decide you really want to store them as memoryviews) you could use np.asarray to convert it back to a numpy array without making a copy (i.e. they share data).

e.g.

cdefnp.ndarray[DTYPE_t, ndim=4] d_out_image = np.asarray(self.d_y).transpose(1, 0, 2,3)

Post a Comment for "Cython: Transpose A Memoryview"