使用Cython

时间:2017-02-12 18:08:50

标签: python performance numpy cython

目标

我试图用Cython加速我的Python程序。编写的代码I是对Forward算法的尝试,用于递归地和有效地计算隐马尔可夫模型(HMM)中的长序列的概率。这个问题通常被称为评估问题。

Python代码

在名为hmm.py

的文件中
import numpy
import pandas

class HMM():
    '''    
    args:
        O:
            observation sequence. A list of 'H's or 'T's

        X:
            state sequence. 'S','M' or 'L's

        A:
            transition matrix, N by N

        B:
            Emission matrix, M by N

        M:
            Number of possibilities in emission matrix

        pi:
            initial transition matrix

        N:
            Number of states

        T:
            length of the observation sequence

        Q:
            possible hidden states (Xs)

        V:
            possible observations (Os)

    '''
    def __init__(self,A,B,pi,O,X):
        self.A=A
        self.N=self.A.shape[0]
        self.B=B
        self.M=self.B.shape[1]
        self.pi=pi
        self.O=O
        self.T=len(O)
        self.Q=list(self.A.index)
        self.V=list(self.B.keys())
        self.X=X


    def evaluate(self):
        '''
        Solve the evaluation problem for HMMs 
        by implementing the forward algorithm
        '''
        c0=0
        ct=numpy.zeros(self.T)
        alpha= numpy.zeros((self.T,self.N))

        ## compute alpha[0]
        for i in range(self.N):
            pi0=self.pi[self.Q[i]]
            bi0=self.B.loc[self.Q[i]][self.O[0]]
            alpha[0,i]=pi0*bi0
            c0+=alpha[0,i]
            ct[0]=alpha[0,i]
        ct[0]=1/ct[0]#[0]
        alpha=alpha*ct[0]
        for t in range(1,self.T):
            for i in range(self.N):
                for j in range(self.N):
                    aji= self.A[self.Q[j]][self.Q[i]]
                    alpha[t,j]= alpha[t-1,j]*aji
                ct[t]=ct[t]+alpha[t,i]
            ct[t]=1/ct[t]
            alpha=alpha*ct[t]
        return (alpha,ct)  

可以使用以下命令调用此代码:

if __name__=='__main__':
    A=[[0.7,0.3],[0.4,0.6]]
    A= numpy.matrix(A)
    A=pandas.DataFrame(A,columns=['H','C'],index=['H','C'])
    '''
    three types of emmission, small s, medium m and large l
    '''
    B=[[0.1,0.4,0.5],[0.7,0.2,0.1]]
    B=numpy.matrix(B)
    B=pandas.DataFrame(B,columns=['S','M','L'],index=['H','C'])
    '''
    initial probabilities for state, H and C
    '''
    pi=[0.6,0.4]
    pi=numpy.matrix(pi)
    pi=pandas.DataFrame(pi,columns=['H','C'])
    O=(0,1,0,2)
    O=('S','M','S','L')
    X=('H','H','C','C')
    H=HMM(A,B,pi,O,X)
    print H.evaluate()

使用%timeit时,我使用纯python

获得此输出

enter image description here

使用Cython进行编译

然后我将evaluate函数(而不是整个类)放在新文件hmm.pyx扩展名中:

import numpy 
cimport numpy

cpdef evaluate_compiled(A,B,pi,O,X):
    '''
    Solve the evaluation problem for HMMs 
    by implementing the forward algorithm
    '''
    T=len(O)
    N=len(list(set(X)))
    Q=list(set(X))
    V=list(set(O))

    c0=0
    ct=numpy.zeros(T)
    alpha= numpy.zeros((T,N))

    ## compute alpha[0]
    for i in range(N):
        pi0=pi[Q[i]]
        bi0=B.loc[Q[i]][O[0]]
        alpha[0,i]=pi0*bi0
        c0+=alpha[0,i]
        ct[0]=alpha[0,i]
    ct[0]=1/ct[0]#[0]
    alpha=alpha*ct[0]
    for t in range(1,T):
        for i in range(N):
            for j in range(N):
                aji= A[Q[j]][Q[i]]
                alpha[t,j]= alpha[t-1,j]*aji
            ct[t]=ct[t]+alpha[t,i]
        ct[t]=1/ct[t]
        alpha=alpha*ct[t]
    return (alpha,ct)   

setup.py

try:
    from setuptools import setup
    from setuptools import Extension
except ImportError:
    from distutils.core import setup
    from distutils.extension import Extension

from Cython.Distutils import build_ext
import numpy

setup(cmdclass={'build_ext':build_ext},
      ext_modules=[Extension('hmm',
                             sources=['HMMCluster/hmm.pyx'], #File is in a directory called HMMCluster
                                     include_dirs=[numpy.get_include()])]   )

编译后,我可以使用:

from hmm import evaluate_compiled

在上面的__main__区块下,我可以使用evaluate

print evaluate_compiled(A,B,pi,O,X)

%timeit

enter image description here

正如您所看到的,在不更改代码的情况下,我的速度提高了约3倍。但是,我读过的所有文档都表明Python中缺乏速度是由于动态推断变量类型。因此,原则上,我可以声明变量类型并进一步加快速度。

带类型声明的Cython

现在,这篇文章的最后一个函数再次使用相同的算法,但带有类型声明

cpdef evaluate_compiled_with_type_declaration(A,B,pi,O,X):
    cdef int t,i,j
    cdef int T  = len(O)
    cdef int N  = len(list(set(X)))
    cdef list Q = list(set(X))
    cdef list V = list(set(O))
    cdef float c0 = 0
#    cdef numpy.ndarray ct = numpy.zeros(T,dtype=double) ## this caused compilation to fail
    ct=numpy.zeros(T)
    alpha= numpy.zeros((T,N))
    for i in range(N):
        pi0=pi[Q[i]]
        bi0=B.loc[Q[i]][O[0]]
        alpha[0,i]=pi0*bi0
        c0+=alpha[0,i]
        ct[0]=alpha[0,i]
    ct[0]=1/ct[0]#[0]
    alpha=alpha*ct[0]
    for t in range(1,T):
        for i in range(N):
            for j in range(N):
                aji= A[Q[j]][Q[i]]
                alpha[t,j]= alpha[t-1,j]*aji
            ct[t]=ct[t]+alpha[t,i]
        ct[t]=1/ct[t]
        alpha=alpha*ct[t]
    return (alpha,ct)   

编译完成后,%timeit得到:

enter image description here

如您所见,类型声明尚未对代码性能进行任何进一步改进。我的问题是:可以对此代码的速度进行任何进一步的改进,如果是,我该怎么做?

修改 根据评论中的建议,我添加了其他类型声明:

cdef float  pi0,bi0
cdef numpy.ndarray[numpy.float64_t, ndim=1] ct
cdef numpy.ndarray[numpy.float64_t, ndim=2] aij,alpha

%timeit得到了这个:

enter image description here

所以,即使声明类型,仍然没有真正的加速。

1 个答案:

答案 0 :(得分:3)

"现代"在Cython中使用NumPy数组的方法是" Typed Memoryviews" http://docs.cython.org/en/latest/src/userguide/memoryviews.html

必须将相应的参数声明为:

cpdef evaluate_compiled_with_type_declaration(double[:,:] A, double[:,:] B, double[:] pi, int[:] O, int[:] X):

(只是猜测类型和形状)。

必须将它们直接编入索引为A[i,j]而不是A[i][j]

您可以声明结果数组并一次性填充它们。

    cdef double[:] ct=numpy.zeros(T)
    cdef double[:,:] alpha= numpy.zeros((T,N))

有关优化,请参阅编译器指令http://cython.readthedocs.io/en/latest/src/reference/compilation.html?highlight=cdivision#compiler-directives(特别是cdivisionboundscheck

您不应该通过list(set(...))转换输入数据,因为该设置会失去排序。

要检查您的代码是否已编译",请按照Warren Weckesser的建议在文件上使用cython -a