相关疑难解决方法(0)

泡菜cython类

我必须保存并加载一个cython类实例.我的cython类是以及几种方法:

import numpy as np
cimport numpy as np
cimport cython    
cdef class Perceptron_avg_my:
    cdef int wlen,freePos
    cdef np.ndarray w,wtot,wac,wtotc #np.ndarray[np.int32_t]
    cdef np.ndarray wmean  #np.ndarray[np.float32_t]    
    cdef public dict fpos    

    def __cinit__(self,np.int64_t wlen=4*10**7):
        self.fpos= dict()
        self.freePos=1
        self.wlen=wlen
        self.w=np.zeros(wlen,np.int32)
        self.wtot=np.zeros(wlen,np.int32)
        self.wac=np.zeros(wlen,np.int32)
        self.wtotc=np.zeros(wlen,np.int32)
        self.wmean=np.zeros(wlen,np.float32)

    cpdef evaluate_noavg(self,list f):
        cdef np.ndarray[np.int32_t] w = self.w
        cdef dict fpos = self.fpos        
        cdef bytes ff
        cdef int i
        cdef long int score=0

        for ff in f:
            i=fpos.get(ff,0)  
            if i != 0: 
                score += w[i]
        return score
Run Code Online (Sandbox Code Playgroud)

我在考虑使用cPickle模块.我明白我必须实现一个__reduce __(自我)方法但是我有一些问题需要找到一个例子并且很好地理解文档 …

python reduce class pickle cython

9
推荐指数
2
解决办法
7396
查看次数

带有C指针的Pickle Cython类

我正在尝试为__reduce__()包含C指针的cython类编写一个方法,但迄今为止找到的关于最佳方法的信息很少.关于如何__reduce__()在将numpy数组用作成员数据时正确编写方法,有大量示例.我想远离Numpy数组,因为它们似乎总是存储为python对象,并且需要调用python API.我来自一个C的背景让我很舒服的工作内存使用手动将呼叫malloc()free(),我试图保持蟒蛇相互作用降到最低.

但是我遇到了一个问题.我需要copy.deepcopy()在Python脚本中使用与我正在创建的类相同的东西,最终将使用它.我发现执行此操作的唯一好方法是通过实现__reduce__()方法为类实现pickle协议.对于大多数原语或python对象来说,这是微不足道的.但是,对于如何为动态分配的C数组执行此操作,我绝对不知所措.显然我无法返回指针本身,因为底层内存在重建对象时会消失,那么最好的方法是什么?我确信这将需要修改__reduce__()方法以及一种或两种__init__()方法.

我已经阅读了关于这里发现的 pickle扩展类型的python文档,以及关于选择cython类(例如这个问题)的堆栈溢出的所有其他问题.

我的类的精简版看起来像这样:

cdef class Bin:
    cdef int* job_ids
    cdef int* jobs
    cdef int primitive_data

    def __cinit__(self):
        self.job_ids = <int*>malloc(40 * sizeof(int))
        self.jobs = <int*>malloc(40 * sizeof(int))

    def __init__(self, int val):
        self.primitive_data = val

    def __dealloc__(self):
        free(job_ids)
        free(jobs)

    def __reduce__(self):
        return (self.__class__, (self.primitive_data))
Run Code Online (Sandbox Code Playgroud)

python pointers pickle cython

6
推荐指数
1
解决办法
948
查看次数

标签 统计

cython ×2

pickle ×2

python ×2

class ×1

pointers ×1

reduce ×1