对使用numpy的函数进行cythonizing

时间:2019-02-08 10:48:37

标签: python numpy cython

我正在尝试对以下代码进行cythonize:

def my_func(vector_b):
    vector_b = np.unpackbits(np.frombuffer(vector_b, dtype=np.uint8))
    vector_b = (vector_b * _n_vector_ranks_only)
    min_ab = np.sum(np.minimum(vector_a, vector_b))
    max_ab = np.sum(np.maximum(vector_a, vector_b))
    return min_ab / max_ab 


_n_vector_ranks_only = np.arange(1023, -1, -1, dtype=np.uint16)

# vector_a data type is same of vector_b, is not contained in db, it is passed manually
vector_a = np.frombuffer(vector_a, dtype=np.uint8)
vector_a = (vector_a * _n_vector_ranks_only)

#fetch all vectors from DB
df = dd.read_sql_table('mydb', 'postgresql://user:passwordg@localhost/table1',  npartitions=16, index_col='id', columns=['data'])
res = df.map_partitions(lambda df: df.apply( lambda x: my_func(x['data']), axis=1), meta=('result', 'double')).compute(scheduler='processes')

#data is a binary array saved with numpy packbits

目前我在这里:

from ruzi_cython import ruzicka
def my_func(vector_b):
    vector_b = np.unpackbits(np.frombuffer(vector_b, dtype=np.uint8))
    vector_b = (vector_b * _n_vector_ranks_only)
    #min_ab = np.sum(np.minimum(vector_a, vector_b))
    #max_ab = np.sum(np.maximum(vector_a, vector_b))
    #return min_ab / max_ab 
    return ruzicka.run_old(vector_a, vector_b)

这是ruzicka.pyx:

# cython: profile=True
import numpy as np
cimport numpy as np
cimport cython

ctypedef np.uint16_t data_type_t

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.overflowcheck(False)
@cython.initializedcheck(False)
cdef double ruzicka_old(data_type_t[:] a, data_type_t[:] b):
    cdef int i
    cdef float max_ab = 0
    cdef float min_ab = 0
    for i in range(1024):
        if a[i] > b[i]:
            max_ab += a[i]
            min_ab += b[i]
        else:
            max_ab += b[i]
            min_ab += a[i]
    return min_ab / max_ab 

def run_old(a, b):
    return ruzicka_old(a, b)

在那里我获得了很多表演。 在对两个数组进行乘法运算的第一部分中,我仍然无法获得良好的结果。

这是我做乘法的方法:

cdef double ruzicka(data_type_16[:] a, data_type_8[:] b):
    cdef int i
    cdef float max_ab = 0
    cdef float min_ab = 0
    cdef data_type_16 tmp = 0
    for i in range(1024):
        tmp = b[i] * (1023-i)
        if a[i] > tmp:
            max_ab += a[i]
            min_ab += tmp
        else:
            max_ab += tmp
            min_ab += a[i]
    return min_ab / max_ab 

1 个答案:

答案 0 :(得分:2)

您似乎正在努力获取数组的第n位(本质上是np.unpackbits做的事情)。

第n位包含在n//8字节内(我使用的是//除法和舍入运算符)。您可以使用&(通过1<<m移一位)来按“按位与”(m)的方式访问字节中的单个位。这将为您提供数字2**(m-1),而您实际上只是在乎它是否为0。

因此,假设vector_bnp.int8_t的内存视图,您可以执行以下操作:

byte_idx = n//8
bit_idx = n%8 # remainder operator
bitmask = 1<<bit_idx
bit_is_true = 1 if (vector_b[byte_idx]&bitmask) else 0

您需要将其放在循环中,并cdef放置变量的类型。