我在飛機上有 1000 個點的資料集。我代表了 P 中所有可能的點對并計算了所有可能對的距離。我要做的是:對于給定的 n,計算 P 中所有點 p 的所有第 n 個最近點。
我之前做的:
P_pairs = [((33, 9), (34, 13)), ((33, 9), (62, 119)), ((33, 9), (33, 7)), ((33, 9), (48, 123)), ...]
listofdistances = [{'((33, 9), (34, 13))': 4.123105625617661}, {'((33, 9), (62, 119))': 113.75851616472501}, {'((33, 9), (33, 7))': 2.0}, ...]
在這種情況下,我堅持排序listofdistances,以便對于每個點,都有最小的 n 個距離作為剩余值。
也許我必須直接計算第n個最近的點,而不是計算所有點的距離。但我不知道如何。
uj5u.com熱心網友回復:
創建一個所有可能對的串列,然后創建一個以距離為值的單鍵字典串列,確實會造成排序問題。我會改為矢量化這項作業并使用 numpy。
import numpy as np
P = np.array([(33, 9), (34, 13), (62, 119), ...])
# Finds the n closest points to p in P
def n_closest_points(p, P, n)
p_vector = np.tile(p, (len(P), 1))
dists = np.linalg.norm(P-p_vector, axis=1)
sorted_dists = np.sort(dists)
# Exclude the 0th element as the distance from p to itself is 0
return sorted_dists[1:n 1]
uj5u.com熱心網友回復:
P = [(33, 9), (34, 13), (62, 119), (33, 7), (48, 123)]
P = np.array(P)
x, y = P[:,0], P[:,1]
# Create a distance table of point (row) vs point (column)
dist = np.sqrt((x - x[:,None])**2 (y - y[:,None])**2)
# The diagonals are 0, as the distance of a point to itself is 0,
# but we want that to have a large value so it comes last in sorting
np.fill_diagonal(dist, np.inf)
# Get the sorted index for each row
idx = dist.argsort(axis=1)
現在如果你想要第 n 個最近的鄰居,n = 3,你可以用idx = idx[:,:3]. 對于第一點,你現在可以做
P[0] # the point itself
P[idx[0]] # its nearest neighbours
dist[0,idx[0]] # their distances
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359775.html
