You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

FunctionApproximation.fs 4.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. module FunctionApproximation
  2. //reduced example from https://github.com/tirthajyoti/Machine-Learning-with-Python/blob/master/Function%20Approximation%20by%20Neural%20Network/Function%20approximation%20by%20linear%20model%20and%20deep%20network.ipynb
  3. open NumSharp
  4. open Tensorflow
  5. open System
  6. let run()=
  7. let N_points = 75 // Number of points for constructing function
  8. let x_min = 1.0 // Min of the range of x (feature)
  9. let x_max = 15.0 // Max of the range of x (feature)
  10. let noise_mean = 0.0 // Mean of the Gaussian noise adder
  11. let noise_sd = 10.0 // Std.Dev of the Gaussian noise adder
  12. let linspace points = [| for i in 0 .. (points - 1) -> x_min + (x_max - x_min)/(float)points * (float)i |]
  13. let func_trans(xAr:float []) =
  14. xAr
  15. |>Array.map (fun (x:float) -> (20.0 * x+3.0 * System.Math.Pow(x,2.0)+0.1 * System.Math.Pow(x,3.0))*sin(x)*exp(-0.1*x))
  16. let X_raw = linspace N_points
  17. let Y_raw = func_trans(X_raw)
  18. let X_mtr = Array2D.init X_raw.Length 1 (fun i j -> X_raw.[i])
  19. let X = np.array(X_mtr)
  20. let noise_x = np.random.normal(noise_mean,noise_sd,N_points)
  21. let y = np.array(Y_raw)+noise_x
  22. let X_train = X
  23. let y_train = y
  24. let learning_rate = 0.00001
  25. let training_epochs = 35000
  26. let n_input = 1 // Number of features
  27. let n_output = 1 // Regression output is a number only
  28. let n_hidden_layer_1 = 25 // Hidden layer 1
  29. let n_hidden_layer_2 = 25 // Hidden layer 2
  30. let x = tf.placeholder(tf.float64, new TensorShape(N_points,n_input))
  31. let y = tf.placeholder(tf.float64, new TensorShape(n_output))
  32. let weights = dict[
  33. "hidden_layer_1", tf.Variable(tf.random_normal([|n_input; n_hidden_layer_1|],dtype=tf.float64))
  34. "hidden_layer_2", tf.Variable(tf.random_normal([|n_hidden_layer_1; n_hidden_layer_2|],dtype=tf.float64))
  35. "out", tf.Variable(tf.random_normal([|n_hidden_layer_2; n_output|],dtype=tf.float64))
  36. ]
  37. let biases = dict[
  38. "hidden_layer_1", tf.Variable(tf.random_normal([|n_hidden_layer_1|],dtype=tf.float64))
  39. "hidden_layer_2", tf.Variable(tf.random_normal([|n_hidden_layer_2|],dtype=tf.float64))
  40. "out", tf.Variable(tf.random_normal([|n_output|],dtype=tf.float64))
  41. ]
  42. // Hidden layer with RELU activation
  43. let layer_1 = tf.add(tf.matmul(x, weights.["hidden_layer_1"]._AsTensor()),biases.["hidden_layer_1"])
  44. let layer_1 = tf.nn.relu(layer_1)
  45. let layer_2 = tf.add(tf.matmul(layer_1, weights.["hidden_layer_2"]._AsTensor()),biases.["hidden_layer_2"])
  46. let layer_2 = tf.nn.relu(layer_2)
  47. // Output layer with linear activation
  48. let ops = tf.add(tf.matmul(layer_2, weights.["out"]._AsTensor()), biases.["out"])
  49. // Define loss and optimizer
  50. let cost = tf.reduce_mean(tf.square(tf.squeeze(ops)-y))
  51. let gs = tf.Variable(1, trainable= false, name= "global_step")
  52. let optimizer = tf.train.GradientDescentOptimizer(learning_rate=(float32)learning_rate).minimize(cost,global_step = gs)
  53. let init = tf.global_variables_initializer()
  54. Tensorflow.Python.``with``(tf.Session(), fun (sess:Session) ->
  55. sess.run(init) |> ignore
  56. // Loop over epochs
  57. for epoch in [0..training_epochs] do
  58. // Run optimization process (backprop) and cost function (to get loss value)
  59. let result=sess.run([|optimizer:>ITensorOrOperation; gs._AsTensor():>ITensorOrOperation; cost:>ITensorOrOperation|], new FeedItem(x, X_train), new FeedItem(y, y_train))
  60. let loss_value = (double) result.[2];
  61. let step = (int) result.[1];
  62. if epoch % 1000 = 0 then
  63. sprintf "Step %d loss: %f" step loss_value |> Console.WriteLine
  64. let w=sess.run(weights |> Array.ofSeq |> Array.map (fun pair -> pair.Value))
  65. let b = sess.run(biases |> Array.ofSeq |> Array.map (fun pair -> pair.Value))
  66. let yhat=sess.run([|ops:>ITensorOrOperation|],new FeedItem(x,X_train))
  67. for i in [0..(N_points-1)] do
  68. sprintf "pred %f real: %f" ((double)(yhat.[0].[i].[0])) ((double)Y_raw.[i]) |> Console.WriteLine
  69. )