假設您在 3D 空間中有一個坐標為 (2,2,2) 的點。如何使用 numpy(我正在考慮使用 meshgrid,我只是無法讓它作業)或 scipy 對操作進行矢量化以在 3D 空間中找到 26 個最近的鄰居?有 26 個鄰居,因為我將該點視為立方體,因此鄰居將是沿著立方體面的 6 個鄰居 沿著立方體角的 8 個鄰居 12 個連接到立方體邊緣的鄰居。
那么對于點(2,2,2),我怎樣才能得到以下坐標:
(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1 , 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2 , 1), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2 ), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)
我已經用三重 for 回圈實作了這個,它有效。但是,速度對我的系統至關重要,因此我需要將此操作矢量化以使我的系統不會出現故障。三重for回圈如下:
neighbors = [] # initialize the empty neighbor list
# Find the 26 neighboring voxels' coordinates
for i in [-1, 0, 1]: # i coordinate
for j in [-1, 0, 1]: # j coordinate
for k in [-1, 0, 1]: # k coordinate
if (i ==0 and j ==0 and k ==0): # if at the same point
pass # skip the current point
else:
neighbors.append((self.current_point[0] i,self.current_point[1] j,self.current_point[2] k)) # add the neighbor to the neighbors list
這是我在 StackOverflow 上的第一篇文章,如有遺漏,敬請見諒。這是用于我希望放在無人機上的路徑規劃演算法,因此時間很關鍵,這樣我就不會撞到墻或其他東西。
uj5u.com熱心網友回復:
您可以使用以下方法輕松創建運動方向itertools.product:
from itertools import product
motion = np.array(list(product(m, repeat=3)))
motion
>>> array([[-1, -1, -1],
[-1, -1, 0],
[-1, -1, 1],
[-1, 0, -1],
[-1, 0, 0],
[-1, 0, 1],
[-1, 1, -1],
[-1, 1, 0],
[-1, 1, 1],
[ 0, -1, -1],
[ 0, -1, 0],
[ 0, -1, 1],
[ 0, 0, -1],
[ 0, 0, 0],
[ 0, 0, 1],
[ 0, 1, -1],
[ 0, 1, 0],
[ 0, 1, 1],
[ 1, -1, -1],
[ 1, -1, 0],
[ 1, -1, 1],
[ 1, 0, -1],
[ 1, 0, 0],
[ 1, 0, 1],
[ 1, 1, -1],
[ 1, 1, 0],
[ 1, 1, 1]])
這很容易,但比純 numpy 慢:
m = [-1, 0, 1]
motion = np.stack(np.meshgrid(m, m, m), axis=-1).reshape(-1, 3)
或者:
motion = np.transpose(np.indices((3,3,3)) - 1).reshape(-1, 3)
然后洗掉原點(0, 0, 0)(它在中間):
motion = np.delete(motion, 13, axis=0)
然后您就可以捕獲所有周圍的點:
motion [[2, 2, 2]]
>>> array([[1, 1, 1],
[1, 1, 2],
[1, 1, 3],
[1, 2, 1],
[1, 2, 2],
[1, 2, 3],
[1, 3, 1],
[1, 3, 2],
[1, 3, 3],
[2, 1, 1],
[2, 1, 2],
[2, 1, 3],
[2, 2, 1],
[2, 2, 3],
[2, 3, 1],
[2, 3, 2],
[2, 3, 3],
[3, 1, 1],
[3, 1, 2],
[3, 1, 3],
[3, 2, 1],
[3, 2, 2],
[3, 2, 3],
[3, 3, 1],
[3, 3, 2],
[3, 3, 3]])
uj5u.com熱心網友回復:
如果您已經將要比較的坐標作為 numpy 陣列進行比較,比如是,那么您可以計算和之間的x歐幾里得距離(2, 2, 2)x
distances = np.power(x - (2, 2, 2), 2).sum(axis=1)
現在你只想要 26 個最小的索引,你可以用np.argpartition
indices = np.argpartition(distances, 26)[:26]
現在,要獲取實際元素:
elements = x[indices, :]
例如,如果x只是您提供的一組點,那么
distances = np.power(x - (2, 2, 2), 2).sum(axis=1)
indices = np.argpartition(distances, 2)[:2]
elements = x[indices, :]
這回傳
array([[1, 2, 2],
[2, 1, 2]])
正如預期的那樣。
請注意,這個高度評價的答案聲稱該函式argpartition以線性時間運行,而不是nlog(n)常規排序運行所需的時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424146.html
上一篇:pandasgroupby將字串值與前一行值進行比較并發現新列中的變化
下一篇:決議特定元素的字串-python
