NeuralNetwork.hpp 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright (c) 2014 Joshua Bowren
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any damages
  5. arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it
  8. freely, subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not
  10. claim that you wrote the original software. If you use this software
  11. in a product, an acknowledgment in the product documentation would be
  12. appreciated but is not required.
  13. 2. Altered source versions must be plainly marked as such, and must not be
  14. misrepresented as being the original software.
  15. 3. This notice may not be removed or altered from any source distribution.
  16. */
  17. #ifndef NEURALNETWORK_HPP_INCLUDED
  18. #define NEURALNETWORK_HPP_INCLUDED
  19. #include <random>
  20. #include <iostream>
  21. #include <fstream>
  22. #include <string>
  23. #include <cmath>
  24. const static double E = 2.718281828;
  25. const static double LEARNING_RATE = 1.0;
  26. const static double ACCEPTED_ERROR = 0.006;
  27. struct NeuronLayer
  28. {
  29. int size;
  30. double* biasWeights;
  31. double* deltas;
  32. double* values;
  33. double* dotProducts;
  34. double** weights;
  35. };
  36. class NeuralNetwork
  37. {
  38. public:
  39. NeuralNetwork(int inputCount, int hiddenLayerCount, int hiddenNeuronCounts[], int outputCount);
  40. NeuralNetwork(const char* fileName);
  41. ~NeuralNetwork();
  42. void CalculateOutputs();
  43. void Train(double** trainingInputs, double** labels, int size);
  44. void Save(const char* fileName);
  45. double GetGuess(double* inputs, int index);
  46. private:
  47. void Construct(int inputCount, int hiddenLayerCount, int hiddenNeuronCounts[], int outputCount);
  48. inline double Sigmoid(double x)
  49. {
  50. return 1.0 / (1.0 + std::pow(E, -x));
  51. }
  52. inline bool AboveAcceptedError(double** trainingInputs, double** labels, int size)
  53. {
  54. for (int x = 0; x < size; x++)
  55. {
  56. for (int y = 0; y < neuronLayers[0].size; y++)
  57. neuronLayers[0].values[y] = trainingInputs[x][y];
  58. CalculateOutputs();
  59. for (int n = 0; n < neuronLayers[lastIndex].size; n++)
  60. {
  61. double error = labels[x][n] - neuronLayers[lastIndex].values[n];
  62. if (std::abs(error) > ACCEPTED_ERROR)
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. int layerCount;
  69. int lastIndex;
  70. NeuronLayer* neuronLayers;
  71. };
  72. #endif // NEURALNETWORK_HPP_INCLUDED