KNN.Array Module

Functions and values

Function or value Description

predict distance labeledPoints k x

Full Usage: predict distance labeledPoints k x

Parameters:
    distance : Distance<'a> - the distance function, e.g. `euclidean`
    labeledPoints : ('a * 'l) array - the array of classified (or labeled) points [in the format (point, label)], used for the classification
    k : int - The _positive_ number of nearest neighbors from x to look for.
    x : 'a - The point to classify

Returns: 'l option The most common label from the k nearest neighbors for x.
Modifiers: inline
Type parameters: 'a, 'l

The [k-nearest neighbors algorithm (KNN)](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm) to classify a new data point into the target class, depending on the features of its neighboring data points.

May mutate the order of `labeledPoints`.

distance : Distance<'a>

the distance function, e.g. `euclidean`

labeledPoints : ('a * 'l) array

the array of classified (or labeled) points [in the format (point, label)], used for the classification

k : int

The _positive_ number of nearest neighbors from x to look for.

x : 'a

The point to classify

Returns: 'l option

The most common label from the k nearest neighbors for x.

Example


 let reds  = [| [ 2.0; 4.0 ]; [ 1.0; 3.0 ]; [ 2.0; 4.0 ]; [ 3.0; 2.0 ]; [ 2.0; 1.0 ] |] |> Array.map (fun p -> (p, "red"))
 let blues = [| [ 5.0; 6.0 ]; [ 4.0; 5.0 ]; [ 4.0; 6.0 ]; [ 6.0; 6.0 ]; [ 5.0; 4.0 ] |] |> Array.map (fun p -> (p, "blue"))

 let labeledPoints = Array.append reds blues
 let prediction = FSharp.Stats.ML.Unsupervised.KNN.Array.predict FSharp.Stats.DistanceMetrics.euclidean labeledPoints 3

 let color = prediction [3.0; 3.0] // should be: Some "red"
 let color = prediction [6.0; 6.0] // should be: Some "blue"