要开始做实验,写代码了,想自己写一下工具,偏机器学习的,要用到矩阵运算比较多,于是想对numpy 的效率进行一下探索。
版本一
首先简单看一下矩阵乘法的结果,只用numpy:
import numpy as np
n = 4000
for i in range(10):
a = np.random.uniform(low=0., high=1., size=(n, n)).astype(np.float32) b = np.random.uniform(low=0., high=1., size=(n, n)).astype(np.float32)
a = a.dot(b)
版本二
用cython加速一下,看看效果,
首先,改一下后缀,用pyx
然后运行:
cython bench_numpy_c.pyx
写一个setup.py文件:
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'bench_numpy_c',
ext_modules = cythonize("bench_numpy_c.pyx"),
)
然后编译:
python setup.py build_ext --inplace
版本三
然后用GPU加速一下,先装cudamat,然后使用gnumpy:
import gnumpy as gpu
import numpy as np
n = 4000
for i in range(10):
a = np.random.uniform(low=0., high=1., size=(n, n)).astype(np.float32) b = np.random.uniform(low=0., high=1., size=(n, n)).astype(np.float32)
ga = gpu.garray(a)
gb = gpu.garray(b)
ga = ga.dot(gb)
最后,总体来测试一下效果,用timeit模块,代码如下:
from timeit import Timer
t1 =Timer('bench_numpy.test()','import bench_numpy')
t2 =Timer('bench_numpy_c.test()','import bench_numpy_c')
t3 =Timer('bench_gnumpy.test()','import bench_gnumpy')
print "pure numpy cost: %f s"%t1.timeit(1)
print "cython numpy cost: %f s"%t2.timeit(1)
print "using gnumpy cost: %f s"%t3.timeit(1)
print "test 10 times"
print "pure numpy cost: %f s"%t1.timeit(10)
print "cython numpy cost: %f s"%t2.timeit(10)
print "using gnumpy cost: %f s"%t3.timeit(10)
结果:cython加速了一点点而已,但是gnumpy加速了不少,2-3倍
[test@localhost benchmarkNumpy]$ python benchmark.py
pure numpy cost: 2.523334 s
cython numpy cost: 2.515121 s
gnumpy: failed to use gpu_lock. Using board #0 without knowing whether it is in use or not.
using gnumpy cost: 1.700691 s
test 10 times
pure numpy cost: 25.952191 s
cython numpy cost: 25.452048 s
using gnumpy cost: 7.745144 s
pure numpy cost: 250.188029 s
cython numpy cost: 251.585954 s
gnumpy: failed to use gpu_lock. Using board #0 without knowing whether it is in use or not.
using gnumpy cost: 78.827483 s
还是gpu提升速度比较多,简单的提升了三倍左右的速度。
以后有时间再探索一下numpy的c api 接口什么的
评论发不了链接。。。
cudamat 安装文档:https://github.com/cudamat/cudamat/blob/master/INSTALL.md
gnumpy 网址: http://www.cs.toronto.edu/~tijmen/gnumpy.html