Skip to content

Instantly share code, notes, and snippets.

@paralax
Last active January 12, 2018 10:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save paralax/97094594ccf1f6d811661c94ae7df775 to your computer and use it in GitHub Desktop.
Save paralax/97094594ccf1f6d811661c94ae7df775 to your computer and use it in GitHub Desktop.
i ported that "fizzbuzz in tensorflow" to F# and Accord.Net's DeepBeliefNetwork
// i ported that "fizzbuzz in tensorflow" to F# and Accord.Net's DeepBeliefNetwork
// http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/
#r "Debug/Accord.dll"
#r "Debug/Accord.Math.dll"
#r "Debug/Accord.Neuro.dll"
#I "Debug"
open Accord.Neuro
open Accord.Neuro.Networks
open Accord.Neuro.Learning
open AForge.Neuro.Learning
open Accord.Neuro.ActivationFunctions
open Accord.Math
let fizz_buzz_encode (n:int) : float [] =
match n%3, n%5 with
| 0,0 -> [|0.;0.;0.;1.|]
| 0,_ -> [|0.;0.;1.;0.|]
| _,0 -> [|0.;1.;0.;0.|]
| _ -> [|1.;0.;0.;0.|]
let binary_encode (n:int) : float [] =
System.Convert.ToString(n, 2).PadLeft(10, '0').ToCharArray()|>Array.map (fun x -> string(x) |> float )
let trX = [ 101..1024 ] |> List.map binary_encode |> List.toArray
let trY = [ 101..1024 ] |> List.map fizz_buzz_encode |> List.toArray
let network = new DeepBeliefNetwork(10, [|25;4|])
(new GaussianWeights(network)).Randomize()
let teacher = new BackPropagationLearning(network)
[ for _ in [0 .. 5000] -> teacher.RunEpoch(trX, trY) ]
network.UpdateVisibleWeights()
let keys = Map.ofList [ (1, "fizzbuzz");
(10, "fizz");
(100, "buzz");]
let bool2int b = if b then 1 else 0
let result (n:int) (a:float []) =
let m = Array.max a
let idx = Array.map (fun(x) -> x = m) a
|> Array.map bool2int
|> Array.map string
|> String.concat ""
|> int
match keys.TryFind idx with
| Some x -> x
| None -> string n
[ 1..100 ] |> List.map (fun(x) -> (x, network.Compute(binary_encode x)) ) |> List.map (fun(n, a) -> result n a)
(*
results - not too bad!
["1"; "2"; "fizz"; "4"; "buzz"; "fizz"; "7"; "buzz"; "buzz"; "buzz"; "11";
"12"; "13"; "14"; "fizzbuzz"; "16"; "17"; "fizz"; "19"; "buzz"; "fizz";
"22"; "23"; "buzz"; "buzz"; "26"; "fizz"; "28"; "29"; "fizzbuzz"; "31";
"32"; "fizz"; "34"; "buzz"; "fizz"; "37"; "38"; "fizz"; "buzz"; "41";
"fizz"; "43"; "44"; "fizzbuzz"; "46"; "47"; "fizz"; "49"; "buzz"; "fizz";
"52"; "53"; "fizz"; "buzz"; "56"; "fizz"; "58"; "59"; "fizzbuzz"; "61";
"62"; "fizz"; "64"; "buzz"; "fizz"; "67"; "fizz"; "fizz"; "buzz"; "71";
"72"; "73"; "74"; "fizzbuzz"; "76"; "77"; "fizz"; "79"; "buzz"; "fizz";
"82"; "83"; "fizz"; "buzz"; "86"; "fizz"; "88"; "89"; "fizzbuzz"; "91";
"92"; "fizz"; "94"; "buzz"; "fizz"; "97"; "98"; "fizz"; "buzz"]
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment