v2026.8.3
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.

KNearestNeighbors

k-nearest-neighbors classifier over a matrix of numeric feature rows. Each row of the matrix carries the label at the same index in the labels array. Query returns the k closest rows, and Classify reduces them to the majority label.

Example

knn := KNearestNeighbors->New(matrix, labels);
label := knn->Classify(3, query);

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();

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