gpt4 book ai didi

python - Cython Numpy 代码并不比纯 python 快

转载 作者:太空狗 更新时间:2023-10-29 18:19:18 25 4
gpt4 key购买 nike

首先我知道SO上有很多类似主题的问题,但经过一天的搜索、阅读和测试,我找不到解决方案。

我有一个 python 函数,它计算 numpy ndarray (m x n) 的成对相关性。我最初只是在 numpy 中这样做,但该函数还计算了倒数对(即除了计算矩阵的 A 行和 B 行之间的相关性外,它还计算了 B 行和 A 行之间的相关性。)所以我采取了略有不同的方法对于大 m 的矩阵大约快两倍(我的问题的实际大小是 m ~ 8000)。

这很好,但仍然有点慢,因为会有很多这样的矩阵,并且全部完成需要很长时间。所以我开始研究用 cython 来加快速度。我从我读过的内容中了解到,cython 不会真正加快 numpy 的速度。这是真的吗,还是我遗漏了什么?

我认为下面的瓶颈是 np.sqrt , np.dot , 调用 ndarray 的 .T方法和np.absolute .我见过人们使用 sqrt来自 libc.math替换 np.sqrt,所以我想我的第一个问题是,libc.math 中的其他方法是否具有类似的功能?我可以使用?恐怕我完全不熟悉 C/C++/C# 或任何 C 系列语言,所以这种打字和 cython 业务对我来说是非常新的领域,如果原因/解决方案很明显,我们深表歉意。

如果做不到这一点,关于我可以做些什么来获得一些性能提升有什么想法吗?

下面是我的 pyx 代码、设置代码和对 pyx 函数的调用。我不知道这是否重要,但当我调用 python setup build_ext --inplace 时它有效,但有很多我不太明白的警告。这些是否也是我没有看到速度提升的原因?

非常感谢任何帮助,对于超长的帖子感到抱歉。

setup.py

from distutils.core import setup
from distutils.extension import Extension
import numpy
from Cython.Distutils import build_ext


setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("calcBrownCombinedP",
["calcBrownCombinedP.pyx"],
include_dirs=[numpy.get_include()])]
)

和设置的输出:

>python setup.py build_ext --inplace

running build_ext
cythoning calcBrownCombinedP.pyx to calcBrownCombinedP.c
building 'calcBrownCombinedP' extension
C:\Anaconda\Scripts\gcc.bat -DMS_WIN64 -mdll -O -Wall -IC:\Anaconda\lib\site-packages\numpy\core\include -IC:\Anaconda\include -IC:\Anaconda\PC -c calcBrownCombinedP.c -o build\temp.win-amd64-2.7\Release\calcbrowncombinedp.o
In file included from C:\Anaconda\lib\site-packages\numpy\core\include/numpy/ndarraytypes.h:1728:0,
from C:\Anaconda\lib\site-packages\numpy\core\include/numpy/ndarrayobject.h:17,
from C:\Anaconda\lib\site-packages\numpy\core\include/numpy/arrayobject.h:15,
from calcBrownCombinedP.c:340:
C:\Anaconda\lib\site-packages\numpy\core\include/numpy/npy_deprecated_api.h:8:9: note: #pragma message: C:\Anaconda\lib\site-packages\numpy\core\include/numpy/npy_deprecated_api.h(8) : Warning Msg: Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
calcBrownCombinedP.c: In function '__Pyx_RaiseTooManyValuesError':
calcBrownCombinedP.c:4473:18: warning: unknown conversion type character 'z' in format [-Wformat]
calcBrownCombinedP.c:4473:18: warning: too many arguments for format [-Wformat-extra-args]
calcBrownCombinedP.c: In function '__Pyx_RaiseNeedMoreValuesError':
calcBrownCombinedP.c:4479:18: warning: unknown conversion type character 'z' in format [-Wformat]
calcBrownCombinedP.c:4479:18: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]
calcBrownCombinedP.c:4479:18: warning: too many arguments for format [-Wformat-extra-args]
In file included from C:\Anaconda\lib\site-packages\numpy\core\include/numpy/ndarrayobject.h:26:0,
from C:\Anaconda\lib\site-packages\numpy\core\include/numpy/arrayobject.h:15,
from calcBrownCombinedP.c:340:
calcBrownCombinedP.c: At top level:
C:\Anaconda\lib\site-packages\numpy\core\include/numpy/__multiarray_api.h:1594:1: warning: '_import_array' defined but not used [-Wunused-function]
In file included from C:\Anaconda\lib\site-packages\numpy\core\include/numpy/ufuncobject.h:311:0,
from calcBrownCombinedP.c:341:
C:\Anaconda\lib\site-packages\numpy\core\include/numpy/__ufunc_api.h:236:1: warning: '_import_umath' defined but not used [-Wunused-function]
writing build\temp.win-amd64-2.7\Release\calcBrownCombinedP.def
C:\Anaconda\Scripts\gcc.bat -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Release\calcbrowncombinedp.o build\temp.win-amd64-2.7\Release\calcBrownCombinedP.def -LC:\Anaconda\libs -LC:\Anaconda\PCbuild\amd64 -lpython27 -lmsvcr90 -o C:\cygwin64\home\Davy\SNPsets\src\calcBrownCombinedP.pyd

pyx 代码 - 'calcBrownCombinedP.pyx'

import numpy as np
cimport numpy as np
from scipy import stats
DTYPE = np.int
ctypedef np.int_t DTYPE_t

def calcBrownCombinedP(np.ndarray genotypeArray):
cdef int nSNPs, i
cdef np.ndarray ms, datam, datass, d, rs, temp
cdef float runningSum, sigmaSq, E, df
nSNPs = genotypeArray.shape[0]
ms = genotypeArray.mean(axis=1)[(slice(None,None,None),None)]
datam = genotypeArray - ms
datass = np.sqrt(stats.ss(datam,axis=1))
runningSum = 0
for i in xrange(nSNPs):
temp = np.dot(datam[i:],datam[i].T)
d = (datass[i:]*datass[i])
rs = temp / d
rs = np.absolute(rs)[1:]
runningSum += sum(rs*(3.25+(0.75*rs)))

sigmaSq = 4*nSNPs+2*runningSum

E = 2*nSNPs

df = (2*(E*E))/sigmaSq

runningSum = sigmaSq/(2*E)
return runningSum

针对某些纯 python 测试上述内容的代码 - 'test.py'

import numpy as np
from scipy import stats
import random
import time
from calcBrownCombinedP import calcBrownCombinedP
from PycalcBrownCombinedP import PycalcBrownCombinedP

ms = [10,50,100,500,1000,5000]

for m in ms:
print '---testing implentation with m = {0}---'.format(m)
genotypeArray = np.empty((m,20),dtype=int)

for i in xrange(m):
genotypeArray[i] = [random.randint(0,2) for j in xrange(20)]

print genotypeArray.shape


start = time.time()
print calcBrownCombinedP(genotypeArray)
print 'cython implementation took {0}'.format(time.time() - start)

start = time.time()
print PycalcBrownCombinedP(genotypeArray)
print 'python implementation took {0}'.format(time.time() - start)

该代码的输出是:

---testing implentation with m = 10---
(10L, 20L)
2.13660168648
cython implementation took 0.000999927520752
2.13660167749
python implementation took 0.000999927520752
---testing implentation with m = 50---
(50L, 20L)
8.82721138
cython implementation took 0.00399994850159
8.82721130234
python implementation took 0.00500011444092
---testing implentation with m = 100---
(100L, 20L)
16.7438983917
cython implementation took 0.0139999389648
16.7438965333
python implementation took 0.0120000839233
---testing implentation with m = 500---
(500L, 20L)
80.5343856812
cython implementation took 0.183000087738
80.5343694046
python implementation took 0.161000013351
---testing implentation with m = 1000---
(1000L, 20L)
160.122573853
cython implementation took 0.615000009537
160.122491308
python implementation took 0.598000049591
---testing implentation with m = 5000---
(5000L, 20L)
799.813842773
cython implementation took 10.7159998417
799.813880445
python implementation took 11.2510001659

最后,纯python实现'PycalcBrownCombinedP.py'

import numpy as np
from scipy import stats
def PycalcBrownCombinedP(genotypeArray):
nSNPs = genotypeArray.shape[0]
ms = genotypeArray.mean(axis=1)[(slice(None,None,None),None)]
datam = genotypeArray - ms
datass = np.sqrt(stats.ss(datam,axis=1))
runningSum = 0
for i in xrange(nSNPs):
temp = np.dot(datam[i:],datam[i].T)
d = (datass[i:]*datass[i])
rs = temp / d
rs = np.absolute(rs)[1:]
runningSum += sum(rs*(3.25+(0.75*rs)))

sigmaSq = 4*nSNPs+2*runningSum

E = 2*nSNPs

df = (2*(E*E))/sigmaSq

runningSum = sigmaSq/(2*E)
return runningSum

最佳答案

使用 kernprof 进行分析显示瓶颈是循环的最后一行:

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
<snip>
16 5000 6145280 1229.1 86.6 runningSum += sum(rs*(3.25+(0.75*rs)))

这并不奇怪,因为您在 Python 和 Cython 版本中都使用了 Python 内置函数 sum。当输入数组的形状为 (5000, 20) 时,切换到 np.sum 可将代码速度提高 4.5 倍。

如果精度损失很小,那么您可以利用线性代数进一步加快最后一行的速度:

np.sum(rs * (3.25 + 0.75 * rs))

实际上是一个矢量点积,即

np.dot(rs, 3.25 + 0.75 * rs)

这仍然不是最优的,因为它遍历了 rs 三次并构造了两个 rs 大小的临时数组。使用初等代数,这个表达式可以重写为

3.25 * np.sum(rs) +  .75 * np.dot(rs, rs)

它不仅给出了原始结果,没有以前版本的舍入错误,而且只循环 rs 两次并使用常量内存。(*)

现在的瓶颈是 np.dot,所以安装一个更好的 BLAS 库比在 Cython 中重写整个东西更能给你带来好处。

(*) 或最新 NumPy 中的对数内存,它具有 np.sum 的递归重新实现,比旧的迭代实现更快。

关于python - Cython Numpy 代码并不比纯 python 快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21658356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com