numpy.take可以应用于二维
np.take(np.take(T,ix,axis=0), iy,axis=1 )
我测试了离散二维拉普拉斯算子的模板
ΔT = T[ix-1,iy] + T[ix+1, iy] + T[ix,iy-1] + T[ix,iy+1] - 4 * T[ix,iy]
有 2 个 take-schemes 和通常的 numpy.array 方案。引入函数 p 和 q 是为了编写更精简的代码,并以不同的顺序处理轴 0 和 1。这是代码:
nx = 300; ny= 300
T = np.arange(nx*ny).reshape(nx, ny)
ix = np.linspace(1,nx-2,nx-2,dtype=int)
iy = np.linspace(1,ny-2,ny-2,dtype=int)
#------------------------------------------------------------
def p(Φ,kx,ky):
return np.take(np.take(Φ,ky,axis=1), kx,axis=0 )
#------------------------------------------------------------
def q(Φ,kx,ky):
return np.take(np.take(Φ,kx,axis=0), ky,axis=1 )
#------------------------------------------------------------
%timeit ΔT_n = T[0:nx-2,1:ny-1] + T[2:nx,1:ny-1] + T[1:nx-1,0:ny-2] + T[1:nx-1,2:ny] - 4.0 * T[1:nx-1,1:ny-1]
%timeit ΔT_t = p(T,ix-1,iy) + p(T,ix+1,iy) + p(T,ix,iy-1) + p(T,ix,iy+1) - 4.0 * p(T,ix,iy)
%timeit ΔT_t = q(T,ix-1,iy) + q(T,ix+1,iy) + q(T,ix,iy-1) + q(T,ix,iy+1) - 4.0 * q(T,ix,iy)
.
1000 loops, best of 3: 944 µs per loop
100 loops, best of 3: 3.11 ms per loop
100 loops, best of 3: 2.02 ms per loop
结果似乎很明显:
- 通常的 numpy 索引 arithmeitk 是最快的
- take-scheme q 需要 100% 的时间(= C-ordering ?)
- take-scheme p 需要 200% 的时间(= Fortran 排序?)
甚至 scipy 手册的一维 示例也没有表明 numpy.take 很快:
a = np.array([4, 3, 5, 7, 6, 8])
indices = [0, 1, 4]
%timeit np.take(a, indices)
%timeit a[indices]
.
The slowest run took 6.58 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.32 µs per loop
The slowest run took 7.34 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.87 µs per loop
有没有人有经验如何使 numpy.take 快速?对于精益代码编写而言,这将是一种灵活且有吸引力的方式,它可以快速编码并且
被告知执行速度也很快。感谢您提供一些改进我的方法的提示!