Skip to content

Commit

Permalink
add knn example
Browse files Browse the repository at this point in the history
  • Loading branch information
briangu committed Dec 19, 2023
1 parent 83a80d5 commit 4bcf424
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
20 changes: 20 additions & 0 deletions examples/ml/knn.kg
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)
24 changes: 24 additions & 0 deletions examples/ml/knn.py
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)

0 comments on commit 4bcf424

Please sign in to comment.