本文介绍了加快python中的numpy循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 使用非常慢的numpy数组考虑以下代码: #八叉树的交点和轨迹 def intersection(八叉树,轨迹):#初始化numpy数组 ox = octree.get(x) oy = octree.get(y) oz = octree.get(z) oe = octree.get(extent)/ 2 tx = trajectory.get(x) ty = trajectory.get( y) tz = trajectory.get(z) result = np.zeros(np.size(ox))#循环元素 for i in range (0,np.size(tx)):表示范围内的j(0,np.size(ox)): if(tx [i]> ox [j] -oe [j ]和 tx [i]< ox [j] + oe [j]和 ty [i]> oy [j] -oe [j]和 ty [i] < oy [j] + oe [j]和 tz [i]> oz [j] -oe [j]和 tz [i]< oz [j] + oe [j ]):结果[j] + = 1 #Finalize 返回结果 如何重写函数以加快计算速度? ( np.size(tx)== 10000 和 np.size(ox)== 100000 )解决方案您正在分配10000个大小为100000的列表。首先要做的是停止使用范围用于嵌套的 j 循环,而是使用生成器版本 xrange 。这将节省您分配所有这些列表的时间和空间。 下一个将使用向量化操作: for x in xrange(0,np.size(tx)): index =(ox-oe< tx [i])& (ox + oe> tx [i])& (oy-oe< ty [i])& (oy + oe> ty [i])& (oz-oe< tz [i])& (oz + oe> tz [i])结果[指数] + = 1 Consider the following code using numpy arrays which is very slow :# Intersection of an octree and a trajectorydef intersection(octree, trajectory): # Initialize numpy arrays ox = octree.get("x") oy = octree.get("y") oz = octree.get("z") oe = octree.get("extent")/2 tx = trajectory.get("x") ty = trajectory.get("y") tz = trajectory.get("z") result = np.zeros(np.size(ox)) # Loop over elements for i in range(0, np.size(tx)): for j in range(0, np.size(ox)): if (tx[i] > ox[j]-oe[j] and tx[i] < ox[j]+oe[j] and ty[i] > oy[j]-oe[j] and ty[i] < oy[j]+oe[j] and tz[i] > oz[j]-oe[j] and tz[i] < oz[j]+oe[j]): result[j] += 1 # Finalize return resultHow to rewrite the function to speed up the calculation ? (np.size(tx) == 10000 and np.size(ox) == 100000) 解决方案 You are allocating 10000 lists of size 100000. The first thing to do would be to stop using range for the nested j loop and use the generator version xrange instead. This will save you time and space allocating all those lists.The next one would be to use vectorized operations:for i in xrange(0, np.size(tx)): index = (ox-oe < tx[i]) & (ox+oe > tx[i]) & (oy-oe < ty[i]) & (oy+oe > ty[i]) & (oz-oe < tz[i]) & (oz+oe > tz[i]) result[index] += 1 这篇关于加快python中的numpy循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-12 17:02