v2026.6.1
All Bundles
Bundle Core machine learning types: the seedable Random generator, Matrix2D linear algebra and activations, matrix reference holders, the NeuralNetwork and CSV-backed MatrixReader. Compile with -lib ml.

KDTree

K-d tree for fast exact nearest-neighbor queries over numeric rows. Built by median splits cycling through the dimensions; queries prune subtrees whose splitting plane lies farther than the current k-th best distance. Equivalent results to a brute-force scan (Euclidean).

Example

tree := KDTree->New(matrix);
nearest := tree->Nearest(3, [57.0, 170.0]);   # row indexes, closest first

Operations

Classify #

Classifies a query point by majority vote of its k nearest neighbors. Ties are broken in favor of the label that first reaches the top count.

method : public : Classify(k:Int, query:Float[]) ~ String

Parameters

NameTypeDescription
kIntnumber of neighbors to poll
queryFloatinput feature vector

Return

TypeDescription
Stringpredicted category label (empty string if there are no neighbors)

Example

knn := KNearestNeighbors->New(matrix, labels);
knn->Classify(3, [57.0, 170.0])->PrintLine();

Nearest #

Finds the k nearest rows to the query point.

method : public : Nearest(k:Int, query:Float[]) ~ Int[]

Parameters

NameTypeDescription
kIntnumber of neighbors
queryFloatquery point (length = features)

Return

TypeDescription
Introw indexes sorted closest-first (fewer than k when the tree is smaller), or Nil on invalid input

New # constructor

Builds the tree from a data matrix.

New(data:Float[,])

Parameters

NameTypeDescription
dataFloatmatrix (rows=samples, cols=features)

New # constructor

Constructor.

New(matrix:Float[,], labels:String[])

Parameters

NameTypeDescription
matrixFloatmatrix input matrix
labelsStringcategories labels

Query #

Query the matrix for classification

method : public : Query(k:Int, query:Float[]) ~ KNeighbor[]

Parameters

NameTypeDescription
kIntnumber of nearest neighbors
queryFloatinput query

Return

TypeDescription
KNeighbork nearest neighbors

Size #

Gets the number of rows indexed.

method : public : Size() ~ Int

Return

TypeDescription
Introw count