Skip to content

Instantly share code, notes, and snippets.

@waf
Last active December 21, 2015 14:19
Show Gist options
  • Save waf/6319057 to your computer and use it in GitHub Desktop.
Save waf/6319057 to your computer and use it in GitHub Desktop.
// see problem description and sample training CSVs here: https://gist.github.com/mathias-brandewinder/5558573
open System
open System.IO
let trainingPath = @"data\trainingsample.csv"
let validationPath = @"data\validationsample.csv"
type Example = { Label:int; Pixels:int[] }
// split by comma
// parse strings to ints
// create Example type, 0th index is label, everything else is Pixels
let parseToExample input =
let parsed = input |> Array.map int
{ Label = parsed.[0]; Pixels = parsed.[1..]}
let csvSplit (input:string) = input.Split(',')
let fileToExamples path =
File.ReadAllLines(path).[1..]
|> Array.map csvSplit
|> Array.map parseToExample
// create distance function
// distance = square root of sums of squares of difference
let distance (unknown:int[]) (e1:Example) =
Array.map2 (fun p1 p2 -> (float (p1 - p2))**2.0) e1.Pixels unknown
|> Array.sum
|> Math.Sqrt
let trainingDB = fileToExamples trainingPath
let validationDB = fileToExamples validationPath
// get record with minimum score
let classify (unknown:int[]) =
let winner = trainingDB |> Array.minBy (distance unknown)
winner.Label
let total = validationDB.Length
let classified = validationDB |> Seq.where (fun (r) -> r.Label = classify(r.Pixels)) |> Seq.length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment