Given training data, test data, and k, compute pairwise Euclidean distances and return the k nearest neighbor indices for each test point.
This is the core computational step in k-Nearest Neighbors (KNN) algorithm. Understanding efficient distance computation and neighbor lookup is crucial for implementing KNN classifiers and regressors.
Euclidean Distance Formula:
d(x,y)=i=1∑d(xi−yi)2Where x,y∈Rd are feature vectors and d is the number of dimensions.
X_train: array-like, shape (n_train, d) or (n_train,) - Training featuresX_test: array-like, shape (n_test, d) or (n_test,) - Test featuresk: int - Number of nearest neighbors to findInput: X_train=[1,3,5], X_test=[2], k=2
Output: [[0,1]]
Input: X_train=[[0,0],[1,1],[2,2]], X_test=[[0.5,0.5]], k=2
Output: [[0,1]]
Use broadcasting to compute all pairwise distances: X_test[:, np.newaxis, :] - X_train[np.newaxis, :, :].
Use np.argsort() to get indices of sorted distances, then take the first k.
Handle 1D arrays by reshaping to 2D: X.reshape(-1, 1).
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
Given training data, test data, and k, compute pairwise Euclidean distances and return the k nearest neighbor indices for each test point.
This is the core computational step in k-Nearest Neighbors (KNN) algorithm. Understanding efficient distance computation and neighbor lookup is crucial for implementing KNN classifiers and regressors.
Euclidean Distance Formula:
d(x,y)=i=1∑d(xi−yi)2Where x,y∈Rd are feature vectors and d is the number of dimensions.
X_train: array-like, shape (n_train, d) or (n_train,) - Training featuresX_test: array-like, shape (n_test, d) or (n_test,) - Test featuresk: int - Number of nearest neighbors to findInput: X_train=[1,3,5], X_test=[2], k=2
Output: [[0,1]]
Input: X_train=[[0,0],[1,1],[2,2]], X_test=[[0.5,0.5]], k=2
Output: [[0,1]]
Use broadcasting to compute all pairwise distances: X_test[:, np.newaxis, :] - X_train[np.newaxis, :, :].
Use np.argsort() to get indices of sorted distances, then take the first k.
Handle 1D arrays by reshaping to 2D: X.reshape(-1, 1).
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number