Advertisement
Guest User

Untitled

a guest
Apr 30th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using MathNet.Numerics;
  4. using MathNet.Numerics.LinearAlgebra;
  5.  
  6. namespace NNet
  7. {
  8. class Program
  9. {
  10. public static void Main (string[] args)
  11. {
  12. var input = new List<Vector<double>> () {
  13. Vector<double>.Build.DenseOfArray(new double[] {-1.0, -1.0}),
  14. Vector<double>.Build.DenseOfArray(new double[] {1.0, 1.0})
  15. };
  16. var output = new List<Vector<double>> () {
  17. Vector<double>.Build.DenseOfArray(new double[] {-1.0}),
  18. Vector<double>.Build.DenseOfArray(new double[] {1.0})
  19. };
  20.  
  21. NeuralNetwork net = new NeuralNetwork (2, 1);
  22. for (int epoch = 0; epoch < 10; epoch++) {
  23. for (int i = 0; i < input.Count; i++) {
  24. var result = net.Feed (input[i]);
  25. net.Train (output [i].Subtract (result));
  26. Console.WriteLine (result);
  27. }
  28. Console.ReadLine ();
  29. }
  30. }
  31. }
  32.  
  33. public class NeuralNetwork
  34. {
  35. Vector<double> input;
  36. Vector<double> output;
  37. Matrix<double> weight;
  38. Matrix<double> rmsprp;
  39.  
  40. Func<double, double> Activate = Math.Tanh;
  41. Func<double, double> dActivate = Differentiate.DerivativeFunc (Math.Tanh, 1);
  42.  
  43. public NeuralNetwork (int inputs, int outputs)
  44. {
  45. weight = Matrix<double>.Build.Random (rows: outputs, columns: inputs);
  46. rmsprp = Matrix<double>.Build.Random (rows: outputs, columns: inputs).Map(Math.Abs);
  47. }
  48.  
  49. // input = -1.0 to 1.0 range
  50. public Vector<double> Feed (Vector<double> input)
  51. {
  52. this.input = input;
  53. output = weight.Multiply (input);
  54. return output.Map (Activate);
  55. }
  56.  
  57. // error = expected - output
  58. public Vector<double> Train(Vector<double> error)
  59. {
  60. Vector<double> deriv = error.PointwiseMultiply (output.Map (dActivate));
  61. Matrix<double> delta = deriv.OuterProduct (input);
  62. delta.PointwiseMultiply (delta).Multiply (0.05).Add(rmsprp.Multiply(0.95),rmsprp);
  63. weight.Add (delta.PointwiseDivide(rmsprp.Map(Math.Sqrt)).Multiply(0.1), weight);
  64. return weight.LeftMultiply (deriv);
  65. }
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement