python - 如何加速 numpy.all 和 numpy.nonzero()?
问题描述
我需要检查一个点是否位于边界长方体内。长方体的数量非常大(~4M)。我想出的代码是:
import numpy as np
# set the numbers of points and cuboids
n_points = 64
n_cuboid = 4000000
# generate the test data
points = np.random.rand(1, 3, n_points)*512
cuboid_min = np.random.rand(n_cuboid, 3, 1)*512
cuboid_max = cuboid_min + np.random.rand(n_cuboid, 3, 1)*8
# main body: check if the points are inside the cuboids
inside_cuboid = np.all((points > cuboid_min) & (points < cuboid_max), axis=1)
indices = np.nonzero(inside_cuboid)
在我的电脑上运行需要 8 秒,运行需要 np.all
3 秒。np.nonzero
有什么想法可以加快代码速度吗?
解决方案
我们可以沿着最小的轴长度减少内存拥塞all-reduction
以获得-slicing
3
inside_cuboid
out = (points[0,0,:] > cuboid_min[:,0]) & (points[0,0,:] < cuboid_max[:,0]) & \
(points[0,1,:] > cuboid_min[:,1]) & (points[0,1,:] < cuboid_max[:,1]) & \
(points[0,2,:] > cuboid_min[:,2]) & (points[0,2,:] < cuboid_max[:,2])
计时 -
In [43]: %timeit np.all((points > cuboid_min) & (points < cuboid_max), axis=1)
2.49 s ± 20 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [51]: %%timeit
...: out = (points[0,0,:] > cuboid_min[:,0]) & (points[0,0,:] < cuboid_max[:,0]) & \
...: (points[0,1,:] > cuboid_min[:,1]) & (points[0,1,:] < cuboid_max[:,1]) & \
...: (points[0,2,:] > cuboid_min[:,2]) & (points[0,2,:] < cuboid_max[:,2])
1.95 s ± 10.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
推荐阅读
- php - Laravel 5.4:致命错误:未捕获的 ReflectionException:类 App\Exceptions\Handler 中不存在
- c++ - 如何使用带指针的数组?
- mysql - 为什么这个查询返回“OK”?关于“删除”
- django - 在 cpanle 上上传文件时,在 django 中找不到页面(共享主机)
- spring - spring-cloud-gateway 和 oauth2(keycloak),转发用户信息
- ios - 推送通知正在发送但未收到 iOS - 云功能
- python - 有没有办法阻止跟随模型中的自我跟随?
- css - CSS Grid 项目仅在 Chrome 中增长到最大高度
- latex - 引用在使用 natbib 包的乳胶中不起作用
- java - PITest 问题:属性“mainClass”是最终的,无法进一步更改