Perceptron
Let's write a simple example of an AI in C++ that uses the perceptron algorithm, a building block for neural networks. This AI will be a binary classifier that learns to decide if a given set of two inputs sums to a number greater than a certain threshold.
Here is a basic C++ program that implements a simple perceptron:
#include <iostream>
#include <vector>
class Perceptron {
private:
std::vector<double> weights;
double learningRate;
// Activation function (Heaviside step function)
int activation(double input) {
return (input > 0) ? 1 : 0;
}
public:
Perceptron(int numInputs, double learningRate) : learningRate(learningRate) {
// Initialize weights with small random values
for (int i = 0; i < numInputs + 1; ++i) { // +1 for the bias weight
weights.push_back((double)rand() / (RAND_MAX / 2) - 1); // Range -1 to 1
}
}
// Predict function
int predict(const std::vector<double>& inputs) {
double sum = weights.back(); // Start with the bias
for (size_t i = 0; i < inputs.size(); ++i) {
sum += inputs[i] * weights[i];
}
return activation(sum);
}
// Train function
void train(const std::vector<double>& inputs, int desiredOutput) {
int prediction = predict(inputs);
int error = desiredOutput - prediction;
// Adjust weights based on error and learning rate
for (size_t i = 0; i < inputs.size(); ++i) {
weights[i] += learningRate * error * inputs[i];
}
// Adjust the bias weight
weights.back() += learningRate * error;
}
};
int main() {
// Create a perceptron with 2 inputs and a learning rate of 0.1
Perceptron perceptron(2, 0.1);
// Example training data: inputs and whether their sum is greater than 1.5
std::vector<std::vector<double>> trainingData = {
{0.5, 0.5}, // Sum is 1.0, so the desired output is 0
{1.5, 0.5}, // Sum is 2.0, so the desired output is 1
{0.1, 0.2}, // Sum is 0.3, so the desired output is 0
{1.0, 0.8} // Sum is 1.8, so the desired output is 1
};
std::vector<int> labels = {0, 1, 0, 1};
// Train the perceptron
for (int i = 0; i < 100; ++i) { // Train for 100 iterations
for (size_t j = 0; j < trainingData.size(); ++j) {
perceptron.train(trainingData[j], labels[j]);
}
}
// Predict new data
std::vector<double> newInput = {1.0, 0.4};
std::cout << "Prediction for input {1.0, 0.4}: " << perceptron.predict(newInput) << std::endl;
return 0;
}
This code sets up a simple perceptron model with two inputs. It's used to predict whether the sum of the two inputs exceeds a threshold (in our case, we implicitly trained it to see if it's greater than 1.5, as shown by the training data).
Remember to compile with a C++11 or later standard enabled:
g++ -std=c++11 perceptron.cpp -o perceptron
./perceptron
This code is a very simplified representation of AI, serving as a foundational concept. Modern AI, especially deep learning, involves much more complexity, with multiple layers and advanced optimization techniques.