我正在尝试在sklearn
模块中扩展某些sklearn.neighbors.dist_metrics
类。但是,整个模块都是用Cython编写的,显然,我想对自定义类执行的操作必须实现cdef dist
(而不是def dist
)。
因此,在我自己的模块中(实际上,我现在正在使用jupyter %%cython
)我想在Cython中实现我的自定义类,并根据需要实现cdef dist
方法。但是,在同一模块中,cdef
模块中,还有可能需要导入的其他模块中,还有许多其他sklearn.neighbors.typedefs
事物。当我尝试导入这些东西时,会出现各种错误。
当我尝试天真import
时:
%%cython
import numpy as np
from sklearn.neighbors.dist_metrics import DistanceMetric
from sklearn.neighbors.typedefs import DTYPE_t, ITYPE_t
cdef class NewDistance(sklearn.neighbors.DistanceMetric):
cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2,
ITYPE_t size) nogil except -1:
return 5
我收到错误消息,提示一旦将事物“ python化”,就无法在“ cython”定义中使用它们:
Error compiling Cython file:
...
First base of 'KernelDistance' is not an extension type
...
'DTYPE_t' is not a type identifier
有一个cimport
关键字,因此:
%%cython
import numpy as np
from sklearn.neighbors.dist_metrics cimport DistanceMetric
from sklearn.neighbors.typedefs cimport DTYPE_t, ITYPE_t
cdef class NewDistance(sklearn.neighbors.DistanceMetric):
cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2,
ITYPE_t size) nogil except -1:
return 5
Annnnndddd ...
Error compiling Cython file:
....
'sklearn/neighbors/dist_metrics.pxd' not found
....
'sklearn/neighbors/typedefs.pxd' not found
如何从其他库中导入cython文件?