class Perceptron {
constructor(learningRate = 0.1) {
this.weights = [Math.random(), Math.random()];
this.bias = Math.random();
this.learningRate = learningRate;
}
predict(inputs) {
const sum = this.weights[0] * inputs[0] + this.weights[1] * inputs[1] + this.bias;
return sum >= 0 ? 1 : -1;
}
train(inputs, target) {
const prediction = this.predict(inputs);
const error = target - prediction;
this.weights[0] += this.learningRate * error * inputs[0];
this.weights[1] += this.learningRate * error * inputs[1];
this.bias += this.learningRate * error;
}
}
// Example usage
const perceptron = new Perceptron();
// Training data (x, y, label)
const data = [
[0, 0, -1],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1],
];
// Training loop
for (let i = 0; i < 100; i++) {
for (const [x, y, label] of data) {
perceptron.train([x, y], label);
}
}
// Test the perceptron
console.log(perceptron.predict([0, 0])); // Should output -1
console.log(perceptron.predict([0, 1])); // Should output 1
console.log(perceptron.predict([1, 0])); // Should output 1
console.log(perceptron.predict([1, 1])); // Should output 1
This perceptron learns to classify points in a 2D space based on their coordinates. The training data consists of four points: (0, 0), (0, 1), (1, 0), and (1, 1), each with a corresponding label of -1 or 1.
The perceptron has weights and a bias that are randomly initialized. During the training loop, the perceptron iteratively updates its weights and bias based on the prediction error for each training example.
After training, you can use the predict method to classify new points. The perceptron will output 1 if the weighted sum of the inputs plus the bias is greater than or equal to 0, and -1 otherwise.
This is a very basic example of a trainable AI algorithm. In practice, more complex algorithms and architectures, such as neural networks with multiple layers and non-linear activation functions, are used for more sophisticated tasks.