gpt4 book ai didi

python - 二维 numpy.take 快吗?

转载 作者:行者123 更新时间:2023-11-30 22:32:59 24 4
gpt4 key购买 nike

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

结果似乎很明显:

  1. 通常的 numpy 索引 arithmeitk 是最快的
  2. 采取方案 q 需要 100% 的时间(= C 排序?)
  3. 采取方案 p 需要 200% 的时间(= Fortran 排序?)

甚至不是一维 example of the scipy manual表明 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 快速的经验吗?这将是一种灵活且有吸引力的精益代码编写方式,编码速度快,并且
is told to be fast in execution以及。感谢您提供一些改进我的方法的提示!

最佳答案

索引版本可以使用切片对象进行清理,如下所示:

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]

sy1 = slice(1,ny-1)
sx1 = slice(1,nx-1)
sy2 = slice(2,ny)
sy_2 = slice(0,ny-2)
T[0:nx-2,sy1] + T[2:nx,sy1] + T[sx1,xy_2] + T[sx1,sy2] - 4.0 * T[sx1,sy1]

关于python - 二维 numpy.take 快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45290102/

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