Skip to content

Instantly share code, notes, and snippets.

@shwars
Created September 17, 2016 13:22
Show Gist options
  • Save shwars/7c57ca4fe980b86b5f147840f1a2b017 to your computer and use it in GitHub Desktop.
Save shwars/7c57ca4fe980b86b5f147840f1a2b017 to your computer and use it in GitHub Desktop.
Short solution to F# Coding Dojo
open System
open System.IO
let read fn = File.ReadAllLines(sprintf "%s\%s" __SOURCE_DIRECTORY__ fn)
let data = read @"trainingsample.csv"
type Example = { Label:int; Pixels:int[] }
let prepare (x:string[]) =
let res =
x.[1..]
|> Array.map (fun x-> x.Split(',')|>Array.map int)
res |> Array.map (fun x->{Label=x.[0];Pixels=x.[1..]})
let d = prepare data
let dist (P1: int[]) (P2: int[]) =
Array.map2 (fun p1 p2 -> (p1-p2)*(p1-p2)) P1 P2
|> Array.sum
let classify (x:int[]) =
d |> Array.minBy(fun z -> dist x z.Pixels)
|> fun t -> t.Label
read "validationsample.csv"
|> prepare
|> Array.fold (fun (correct,total) z ->
if z.Label = classify(z.Pixels) then (correct+1,total+1)
else (correct,total+1)) (0,0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment