Questions/Write a simple neural network in C++
·
•••Report content

Write a simple neural network in C++

Neural NetworkMachine LearningC++ProgrammingImplementation
Idyllic answer2024-05-10

Here is a simple neural network implementation in C++:

```cpp

#include <iostream>

#include <vector>

#include <cmath>

using namespace std;

class Neuron {

public:

double bias;

vector<double> weights;

Neuron(int num_inputs) {

for (int i = 0; i < num_inputs; i++) {

weights.push_back(rand() / (double)RAND_MAX); // random weights

}

bias = rand() / (double)RAND_MAX; // random bias

}

double sigmoid(double x) {

return 1 / (1 + exp(-x));

}

double activate(vector<double> inputs) {

double sum = bias;

for (int i = 0; i < inputs.size(); i++) {

sum += inputs[i] * weights[i];

}

return sigmoid(sum);

}

};

class NeuralNetwork {

public:

vector<Neuron> hidden_layer;

vector<Neuron> output_layer;

NeuralNetwork(int num_inputs, int hidden_layer_size) {

for (int i = 0; i < hidden_layer_size; i++) {

hidden_layer.push_back(Neuron(num_inputs));

}

for (int i = 0; i < 1; i++) { // assuming a single output neuron

output_layer.push_back(Neuron(hidden_layer_size));

}

}

vector<double> forward_propagation(vector<double> inputs) {

vector<double> hidden_layer_outputs;

for (int i = 0; i < hidden_layer.size(); i++) {

hidden_layer_outputs.push_back(hidden_layer[i].activate(inputs));

}

vector<double> output;

for (int i = 0; i < output_layer.size(); i++) {

output.push_back(output_layer[i].activate(hidden_layer_outputs));

}

return output;

}

};

int main() {

NeuralNetwork nn(2, 3); // 2 inputs, 3 neurons in hidden layer

vector<double> inputs = {0.5, 0.5}; // example inputs

vector<double> output = nn.forward_propagation(inputs);

cout << "Output: " << output[0] << endl;

return 0;

}

```

This implementation defines a `Neuron` class, which represents a single neuron in the network. Each neuron has a bias term and a set of weights, which are initialized randomly. The `activate` method computes the output of the neuron based on the input values and the weights.

The `NeuralNetwork` class represents the entire neural network. It consists of a hidden layer and an output layer, each composed of `Neuron` objects. The `forward_propagation` method computes the output of the network based on the input values.

In the `main` function, we create a neural network with 2 inputs and 3 neurons in the hidden layer. We then compute the output of the network for a sample input and print the result.

Note that this is a simple example and you may want to add more features such as backpropagation and optimization algorithms to train the network.

Sources

YOUR CREATION. YOUR CHOICE.

Made by you.
Seen by who?

Before you create, choose who gets to see it.

Generation visibility
18+ only

Show mature content?

Mature mode shows adults who turn it on tasteful 18+ creations.