[英]Nearest Neighbors in Python given the distance matrix
我必須在 Python 中應用最近的鄰居,我正在尋找scikit-learn
和scipy
庫,它們都需要數據作為輸入,然后將計算距離並應用算法。
在我的情況下,我必須計算一個非常規距離,因此我想知道是否有辦法直接輸入距離矩陣。
正如福特所說並根據文檔http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier,您應該將自定義距離轉換為DistanceMetric對象並傳遞它作為度量參數。
您需要創建一個DistanceMetric
對象,提供您自己的函數作為參數:
metric = sklearn.neighbors.DistanceMetric.get_metric('pyfunc', func=func)
來自文檔:
這里
func
是一個函數,它接受兩個一維numpy數組,並返回一個距離。 請注意,為了在BallTree中使用,距離必須是真正的度量:即它必須滿足以下屬性
- 非負性:d(x,y)> = 0
- 身份:當且僅當x == y時,d(x,y)= 0
- 對稱性:d(x,y)= d(y,x)
- 三角不等式:d(x,y)+ d(y,z)> = d(x,z)
然后,您可以使用metric=metric
作為關鍵字參數創建分類器,並在計算距離時使用此分類器。
想要添加福特的答案,你必須這樣做
metric = DistanceMetric.get_metric('pyfunc',func = /你的函數名稱/)
你不能只把你自己的函數作為第二個參數,你必須將參數命名為“func”
如果您設置metric="precomputed"
您可以將您自己的距離矩陣傳遞給sklearn.neighbors.NearestNeighbors
。 如下例所示,當使用歐幾里得距離度量時,結果確實相當於直接傳遞特征。
import numpy as np
from numpy.testing import assert_array_equal
from scipy.spatial.distance import cdist
from sklearn.neighbors import NearestNeighbors
# Generate random vectors to use as data for k-nearest neighbors.
rng = np.random.default_rng(0)
X = rng.random((10, 2))
# Fit NearestNeighbors on vectors and retrieve neighbors.
knn_vector_based = NearestNeighbors(n_neighbors=2).fit(X)
nn_1 = knn_vector_based.kneighbors(return_distance=False)
# Calculate distance matrix.
# This computation can be replaced with any custom distance metric you have.
distance_matrix = cdist(X, X)
# Fit NearestNeighbors on distance matrix and retrieve neighbors.
knn_distance_based = (
NearestNeighbors(n_neighbors=2, metric="precomputed")
.fit(distance_matrix)
)
nn_2 = knn_distance_based.kneighbors(return_distance=False)
# Verify that that the result is the same.
assert_array_equal(nn_1, nn_2)
# Neighbors for single points can be retrieved by passing
# a subset of the original distance matrix.
nn_of_first_point_1 = knn_vector_based.kneighbors(
X[0, None], return_distance=False
)
nn_of_first_point_2 = knn_distance_based.kneighbors(
distance_matrix[0, None], return_distance=False
)
assert_array_equal(nn_of_first_point_1, nn_of_first_point_2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.