Dav*_*agh 10 python optimization numpy cython
首先我知道在SO上有许多类似的主题问题,但经过一天的搜索,阅读和测试后,我找不到解决方案.
我有一个python函数,它计算numpy ndarray(mxn)的成对相关性.我原本只是在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()])]
)
Run Code Online (Sandbox Code Playgroud)
和设置的输出:
>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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
针对某些纯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)
Run Code Online (Sandbox Code Playgroud)
并且该代码的输出是:
---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
Run Code Online (Sandbox Code Playgroud)
最后,纯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
Run Code Online (Sandbox Code Playgroud)
Fre*_*Foo 20
分析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)))
Run Code Online (Sandbox Code Playgroud)
这并不奇怪,因为您在sum
Python和Cython版本中都使用了Python内置函数.np.sum
当输入数组具有形状时,切换到将代码加速4.5倍(5000, 20)
.
如果精度损失很小,那么您可以利用线性代数进一步加速最后一行:
np.sum(rs * (3.25 + 0.75 * rs))
Run Code Online (Sandbox Code Playgroud)
实际上是一个矢量点积,即
np.dot(rs, 3.25 + 0.75 * rs)
Run Code Online (Sandbox Code Playgroud)
这仍然是次优的,因为它循环rs
三次并构造两个rs
大小的临时数组.使用初等代数,可以将此表达式重写为
3.25 * np.sum(rs) + .75 * np.dot(rs, rs)
Run Code Online (Sandbox Code Playgroud)
它不仅提供原始结果而没有前一版本中的舍入错误,而且只循环rs
两次并使用常量内存.(*)
现在是瓶颈np.dot
,所以安装一个更好的BLAS库会比在Cython中重写整个东西更多.
(*)或最新NumPy中的对数内存,其递归重新实现np.sum
比旧迭代更快.
归档时间: |
|
查看次数: |
1909 次 |
最近记录: |