Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. class NeuralNetwork
  2. {
  3. List<Matrix<float>> w;
  4. List<Matrix<float>> b;
  5.  
  6. public NeuralNetwork(params int[] layers)
  7. {
  8. w = new List<Matrix<float>>();
  9. b = new List<Matrix<float>>();
  10.  
  11. for (int i = 0; i < layers.Count() - 1; i++) {
  12. w.Add(CreateMatrix.Random<float>(layers[i + 1], layers[i]));
  13. b.Add(CreateMatrix.Random<float>(layers[i + 1], 1));
  14. }
  15. }
  16.  
  17. public Matrix<float> Forward(Matrix<float> input)
  18. {
  19. Matrix<float> r = input;
  20. for(int i = 0; i < w.Count(); i++) {
  21. r = Sigmoid(w[i] * r + b[i]);
  22. }
  23. return r;
  24. }
  25.  
  26. public (Matrix<float> Output, List<Matrix<float>> Layers) ForwardWithLayers(Matrix<float> input)
  27. {
  28. Matrix<float> r = input;
  29. List<Matrix<float>> l = new List<Matrix<float>>();
  30. for (int i = 0; i < w.Count() - 1; i++) {
  31. r = Sigmoid(w[i] * r + b[i]);
  32. l.Add(r);
  33. }
  34. r = Sigmoid(w.Last() * r + b.Last());
  35. return (r, l);
  36. }
  37.  
  38. public double Backprop(Matrix<float> target, Matrix<float> input, float learning_rate = .01f)
  39. {
  40. var (xL, x) = ForwardWithLayers(input);
  41. var error = (xL - target).FrobeniusNorm();
  42.  
  43. Dictionary<int, Matrix<float>> delta = new Dictionary<int, Matrix<float>>();
  44. delta[w.Count() - 1] = (xL - target).PointwiseMultiply(Sigmoid(w.Last() * x.Last() + b.Last(), true));
  45. for(int i = w.Count() - 2; i > 0; i--) {
  46. delta[i] = w[i + 1].TransposeThisAndMultiply(delta[i + 1]).PointwiseMultiply(Sigmoid(w[i] * x[i - 1] + b[i], true));
  47. }
  48. delta[0] = w[1].TransposeThisAndMultiply(delta[1]).PointwiseMultiply(Sigmoid(w[0] * input + b[0], true));
  49.  
  50. for(int i = 0; i < w.Count(); i++) {
  51. w[i] -= learning_rate * delta[i] * (i == 0 ? input.Transpose() : x[i - 1].Transpose());
  52. }
  53.  
  54. return error;
  55. }
  56.  
  57. private Matrix<float> Sigmoid(Matrix<float> x, bool derivative=false)
  58. {
  59. if (derivative)
  60. return x.PointwiseMultiply(1 - x);
  61. else
  62. return x.Map<float>(f => 1 / (1 + (float)Math.Exp(-f)));
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement