Created
April 14, 2014 23:49
-
-
Save MartinBodocky/10690774 to your computer and use it in GitHub Desktop.
Simple KNN
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
let distance v1 v2 = | |
Array.zip v1 v2 | |
|> Array.fold (fun sum e -> sum + pown (fst e - snd e) 2) 0.0 | |
|> sqrt | |
let classify subject dataSet labels k = | |
dataSet | |
|> Array.map (fun row -> distance row subject) | |
|> Array.zip labels | |
|> Array.sortBy snd | |
|> Array.toSeq | |
|> Seq.take k | |
|> Seq.groupBy fst | |
|> Seq.maxBy (fun g -> Seq.length (snd g)) | |
let createDataSet = | |
[| [| 1.0; 0.9 |] | |
[| 0.8; 1.0 |] | |
[| 0.8; 0.9 |] | |
[| 0.0; 0.1 |] | |
[| 0.3; 0.0 |] | |
[| 0.1; 0.1 |] |], | |
[| "A"; "A"; "A"; "B"; "B"; "B" |] | |
let data, labels = createDataSet | |
classify [| 0.2; 0.4 |] data labels 3 | |
classify [| 0.7; 0.4 |] data labels 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment