Advertisement
Guest User

Untitled

a guest
Apr 13th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.46 KB | None | 0 0
  1. module DigitRecognizerModule
  2.  
  3. open System
  4. open System.IO
  5.  
  6. // type represents sample from dataset
  7. type Sample = {Label:int; Vector:int[] }
  8.  
  9.  
  10. // load CSV and return Sample array
  11. let loadCSVLines(fn:string) = File.ReadAllLines(fn)
  12. let lineToIntArr(line:string) = Array.map (fun s->s|>int) (line.Split(','))
  13. let getData(fn:string) =
  14.     loadCSVLines(fn)
  15.     |> (fun x->x.[1..])
  16.     |> Array.map (fun x->let arr=lineToIntArr x in {Label=arr.[0]; Vector=arr.[1..]})
  17.  
  18.  
  19. // distance between two vectors
  20. let dist (v1:int[], v2:int[]) =
  21.     Array.zip v1 v2
  22.     |> Array.map (fun x->((fst x-snd x)|>float)**2.0)
  23.     |> Array.sum
  24.  
  25.  
  26. // classify test sample by looking for most similar training sample
  27. let classify(train:Sample[], test:Sample)=
  28.     Array.map (fun x->dist(x.Vector, test.Vector)) train
  29.     |> Array.zip [|0..(train|>Array.length)-1|]
  30.     |> Array.fold (fun acc x->if (snd acc) > (snd x) then x else acc) (0, System.Double.MaxValue)
  31.     |> fst
  32.     |> (fun i->train.[i].Label)
  33.  
  34.  
  35. // evaluate the digit classifier
  36. let eval()=
  37.         // load data
  38.         let dir="../../../../"
  39.         let test=getData(dir+"test.csv")
  40.         let train=getData(dir+"train.csv")
  41.         let len=test |> Array.length
  42.  
  43.         // classify samples from test set, calc accuracy
  44.         let accuracy=(Array.map (fun i->if classify(train, test.[i])=test.[i].Label then 1.0 else 0.0) [|0..len-1|] )|> Array.sum |> (fun x->x/(len|>float))
  45.         printfn "Accuracy: %f" accuracy
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement