我必须保存并加载一个 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
我正在考虑使用 cPickle 模块。我知道我必须实现一个 __reduce__(self) 方法,但我有一些问题要找到一个例子并很好地理解文档
我试图将这样的东西添加到 Perceptron_avg_my 但不起作用:
def rebuild(self,l):
self.fpos=l[0]
self.freePos=l[1]
def __reduce__(self):
#print 'reduce call'
return (Perceptron_avg_my.rebuild,(self.fpos,self.freePos))
有什么建议么?非常感谢!!!