gpt4 book ai didi

python - Cython + Numpy 变量 ndim?

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:57 25 4
gpt4 key购买 nike

我需要初始化可变形状的数组(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)

是的,我有预感它行不通,但无论如何都必须尝试 ;)

是否可以做这样的事情,还是我必须使用指针/内存分配等?还是我必须(吞咽!)只使用一维数组并在最后 reshape 它??

最佳答案

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。)

关于python - Cython + Numpy 变量 ndim?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27514467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com