-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
:" euclidean distance " | ||
ed::{[d];d::x-y;({+/x}'d*d)^0.5} | ||
|
||
:" compute knn between point x and data y " | ||
knn::{[distances];distances::ed(y;z);x#<distances} | ||
|
||
:" test data " | ||
data::[[1 2] [2 3] [3 4] [5 5] [1 4] [2 5]] | ||
|
||
:" test point " | ||
tp::[3 3] | ||
|
||
:" number of neighbors " | ||
k::3 | ||
|
||
:" Find the k-nearest neighbors " | ||
neighbors::knn(k;tp;data) | ||
|
||
:" Output the indices of the nearest neighbors " | ||
.d("Indices of the k-nearest neighbors: ");.p(neighbors) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import numpy as np | ||
|
||
def euclidean_distance(a, b): | ||
return np.sqrt(np.sum((a - b) ** 2)) | ||
|
||
def knn(k, point, data): | ||
distances = np.array([euclidean_distance(point, d) for d in data]) | ||
sorted_indices = np.argsort(distances) | ||
return sorted_indices[:k] | ||
|
||
# Sample Data | ||
data = np.array([[1, 2], [2, 3], [3, 4], [5, 5], [1, 4], [2, 5]]) | ||
|
||
# Test Point | ||
test_point = np.array([3, 3]) | ||
|
||
# Number of Neighbors | ||
k = 3 | ||
|
||
# Find the k-nearest neighbors | ||
neighbors = knn(k, test_point, data) | ||
|
||
# Output the indices of the nearest neighbors | ||
print("Indices of the k-nearest neighbors:", neighbors) |