How to implement a Neural Network in C++

Original question

I am working on a simple C++ library. I'm trying to implement a Neural Network. I've got two questions:

  1. Are there any tutorials which explain how they can be implemented?

  2. Do I really need to plot a graph when I implement the Neural Network?


The code that I have written so far is:

#ifndef NEURAL_NETWORK_H
#define NEURAL_NETWORK_H

#include <ctime>
#include <cstdlib>

class NeuralNetwork {
    public :
        void SetWeight(double tempWeights [15]) {
            for (int i = 0; i < (sizeof(tempWeights) / sizeof(double)); ++i) {
                weights[i] = tempWeights[i];
            }
        }

        double GetWeights() {
            return weights;
        }

        void Train(int numInputs, int numOutputs, double inputs[], double outputs[]) {
            double tempWeights[numOutputs];

            int iterator = 0;

            while (iterator < 10000) {
                  // This loop will train the Neural Network
            }

            SetWeights(tempWeights);
        }

        double[] Calculate(double inputs[]) {
             // Calculate Outputs...

             return outputs;
        }

        NeuralNetwork(double inputs[], double outputs[]) {
            int numberOfInputs = sizeof(inputs) / sizeof(double);
            int numberOfOutputs = sizeof(outputs) / sizeof(double);

            Train(numberOfInputs, numberOfOutputs, inputs[], outputs[]);
        }
    private :
        double weights[15];
};

#endif // NEURAL_NETWORK_H

Edited and updated question

Thanks to the help from the comments, I managed to implement the Neural Network.

Now, I'm currently struggling with a performance issue. srand has actually started becoming unhelpful a bit...

Are there better random functions?

Upvotes: 0

Views: 2817

Answers (1)

Firstly, I learnt a lot about how we think from this project, I learnt about std::uniform_real_distribution<>, std::vector<> and syntax structure.

srand and time are C functions. Therefore, for the best optimisation, they should not be used.

So, what should we use? std::uniform_real_distribution because it is more flexible and stable.

std::vector<double> set_random_weights()
{ 
    std::default_random_engine generator; 
    std::uniform_real_distribution<double> distribution(0.0,1.0);

    std::vector<double> temp_weights;

    for (unsigned int i = 0; i < (num_input_nodes * num_hidden_nodes); ++i)
    {
        temp_weights.push_back(distribution(generator));
    }

   return temp_weights;
}

However to use std::uniform_real_distribution and std::default_random_engine we need to include the random header:

#include <random>

And to use std::vectors, we must in the vector header:

#include <vector>

Upvotes: 2

Related Questions