python – Cython Numpy变量ndim?

我需要初始化变量形状的数组(dim,)(nbins,)* dim,其中dim通常很小,但nbins可能很大,所以数组有ndims = dim 1.例如,如果dim = 1我需要一个形状数组(1,nbins),如果dim = 2,形状为(2,nbins,nbins)等.

是否可以相应地键入numpy数组?我试过类似的东西

 ctypedef uint32_t  uint_t
 ctypedef float     real_t
 ...
     cdef:
         uint_t dim = input_data.shape[1]
         np.ndarray[real_t, ndim=dim+1] my_array = np.zeros((dim,)\
     + (nbins,)*dim, dtype = np.float32)

是的,我有预感它不会工作,但不得不尝试;)

是可以做这样的事情还是我必须使用指针/内存分配等?或者我必须(gulp!)只使用一维数组并在最后重塑它?

最佳答案

Or do I have to (gulp!) just use a one dimensional array and just reshape it at the end?

我怕你这样做.如果在编译时已知维数,Cython只能执行其数组访问优化魔术.不要与malloc混淆,这是不值得的.

cdef:
    np.npy_intp size = dim * n_bins ** dim
    np.ndarray[float, ndim=1, mode='c'] arr = np.zeros(size, dtype=np.float32)

    # do work, using "manual" index calculations

    return arr.reshape(dim, (n_bins,) * dim)

(旁注:形状的正确类型是np.npy_intp,而不是uint32_t.)

点赞