我正在自己實作加權 knn 演算法。
為了簡化邏輯,讓我們將其表示為一個 predict 方法,它采用三個引數:
索引 - 來自物件 i 的訓練樣本的最近 j 個鄰居的矩陣(i=1...n,總共 n 個物件)。[i, j] - 來自訓練樣本的物件索引。例如,對于 4 個物件和 3 個鄰居:
indices = np.asarray([[0, 3, 1],
[0, 3, 1],
[1, 2, 0],
[5, 4, 3]])
distances - 從訓練樣本到物件 i 的 j 個最近鄰居的距離矩陣。(i=1...n,總共 n 個物件)。例如,對于 4 個物件和 3 個鄰居:
distances = np.asarray([[ 4.12310563, 7.07106781, 7.54983444],
[ 4.89897949, 6.70820393, 8.24621125],
[ 0., 1.73205081, 3.46410162],
[1094.09368886, 1102.55022561, 1109.62245832]])
標簽 - 訓練樣本的每個物件 j 具有真實類別標簽的向量。例如:
labels = np.asarray([0, 0, 0, 1, 1, 2])
因此,函式簽名是:
def predict(indices, distances, labels):
....
# return [np.bincount(x).argmax() for x in labels[indices]]
return predict
在評論中,您可以看到回傳“非加權”knn 方法預測的代碼,該方法不使用距離。你能說明一下,如何使用距離矩陣來計算預測嗎?我找到了演算法,但現在我完全被難住了,因為我不知道如何用 numpy.
謝謝!
uj5u.com熱心網友回復:
這應該有效:
# compute inverses of distances
# suppress division by 0 warning,
# replace np.inf with a very large number
with np.errstate(divide='ignore'):
dinv = np.nan_to_num(1 / distances)
# an array with distinct class labels
distinct_labels = np.array(list(set(labels)))
# an array with labels of neighbors
neigh_labels = labels[indices]
# compute the weighted score for each potential label
weighted_scores = ((neigh_labels[:, :, np.newaxis] == distinct_labels) * dinv[:, :, np.newaxis]).sum(axis=1)
# choose the label with the highest score
predictions = distinct_labels[weighted_scores.argmax(axis=1)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/345536.html
上一篇:從參考表生成動態矩陣
