亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何加速 numpy.all 和 numpy.nonzero()?

如何加速 numpy.all 和 numpy.nonzero()?

肥皂起泡泡 2023-08-22 16:29:47
我需要檢查一個點是否位于邊界長方體內部。長方體的數量非常多(~4M)。我想出的代碼是:import numpy as np# set the numbers of points and cuboidsn_points = 64n_cuboid = 4000000# generate the test datapoints = np.random.rand(1, 3, n_points)*512cuboid_min = np.random.rand(n_cuboid, 3, 1)*512cuboid_max = cuboid_min + np.random.rand(n_cuboid, 3, 1)*8# main body: check if the points are inside the cuboidsinside_cuboid = np.all((points > cuboid_min) & (points < cuboid_max), axis=1)indices = np.nonzero(inside_cuboid)運行需要8秒, 在我的電腦上np.all運行需要3秒np.nonzero。有什么想法可以加快代碼速度嗎?
查看完整描述

1 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

我們可以減少內存擁塞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)


查看完整回答
反對 回復 2023-08-22
  • 1 回答
  • 0 關注
  • 1441 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號