Dan*_*ani 5 python loops nested-lists cython numba
我想要一个函数,它接收列表列表作为参数,每个子列表具有不同的大小,并且可以迭代每个子列表(包含整数),将它们作为广播传递到 numpy 数组并执行不同的操作操作(如平均值)。
让我提供一个不使用 cython 的预期行为的简单示例:
import numpy as np
mask = [[0, 1, 2, 4, 6, 7, 8, 9],
[0, 1, 2, 4, 6, 7, 8, 9],
[0, 1, 2, 4, 6, 9],
[3, 5, 8],
[0, 1, 2, 4, 6, 7, 8, 9],
[3, 5, 7],
[0, 1, 2, 4, 6, 9],
[0, 1, 4, 5, 7, 8, 9],
[0, 1, 3, 4, 7, 8, 9],
[0, 1, 2, 4, 6, 7, 8, 9]] # This is the list of lists
x = np.array([2.0660689 , 2.08599832, 0.45032649, 1.05435649, 2.06010132,
1.07633407, 0.43014785, 1.54286467, 1.644388 , 2.15417444])
def nocython(mask, x):
out = np.empty(len(x), dtype=np.float64)
for i, v in enumerate(mask):
out[i] = x[v].mean()
return out
>>> nocython(mask, x)
array([1.55425875, 1.55425875, 1.54113622, 1.25835952, 1.55425875,
1.22451841, 1.54113622, 1.80427567, 1.80113602, 1.55425875])
Run Code Online (Sandbox Code Playgroud)
主要问题是我必须处理更大的 numpy 数组和掩码列表,并且循环在 Python 中变得非常低效。所以我想知道如何对这个函数进行 cythonize(或 numbaize)。像这样的东西:
%%cython
import numpy as np
cimport numpy as np
cdef np.ndarray[np.float64_t] cythonloop(int[:,:] mask, np.ndarray[np.float64_t] x):
cdef Py_ssize_t i
cdef Py_ssize_t N = len(x)
cdef np.ndarray[np.float64_t] out = np.empty(N, dtype=np.float64)
for i in range(N):
out[i] = x[mask[i]]
cythonloop(mask, x)
Run Code Online (Sandbox Code Playgroud)
但这不起作用(无法强制列表输入“int[:, :]”)。
如果我在 numba 尝试的话也不行
import numba as nb
@nb.njit
def nocython(mask, x):
out = np.empty(len(x), dtype=np.float64)
for i, v in enumerate(mask):
out[i] = x[v].mean()
return out
Run Code Online (Sandbox Code Playgroud)
这给出了以下错误:
TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Invalid use of Function(<built-in function getitem>) with argument(s) of type(s): (array(float64, 1d, A), reflected list(int64))
* parameterized
Run Code Online (Sandbox Code Playgroud)
小智 3
在 Numba 中,您可以使用类型列表来迭代列表列表。Numba 不支持使用列表对 NumPy 数组进行索引,因此该函数还需要进行一些修改,以通过迭代内部列表的元素并索引到 来实现平均值x
。
在调用 jitted 函数之前,您还需要将列表列表转换为类型列表的类型列表。
将其放在一起给出(除了您问题中的代码之外):
from numba import njit
from numba.typed import List
@njit
def jitted(mask, x):
out = np.empty(len(x), dtype=np.float64)
for i in range(len(mask)):
m_i = mask[i]
s = 0
for j in range(len(m_i)):
s += x[m_i[j]]
out[i] = s / len(m_i)
return out
typed_mask = List()
for m in mask:
typed_mask.append(List(m))
# Sanity check - Numba and nocython implementations produce the same result
np.testing.assert_allclose(nocython(mask, x), jitted(typed_mask, x))
Run Code Online (Sandbox Code Playgroud)
请注意,也可以避免使列表成为类型列表,因为当传递内置列表类型时,Numba 将使用反射列表- 但是此功能已弃用,并将从 Numba 的未来版本中删除,因此建议请改用类型化列表。
归档时间: |
|
查看次数: |
1900 次 |
最近记录: |