Perceptron in pure PHP: standalone example
Classic Rosenblatt perceptron (standalone run)
A minimal implementation of the classic perceptron: weighted sum, threshold activation, and training with the Rosenblatt update rule.
Example of use
<?php
include 'code.php';
$X = [
[0, 0],
[0, 1],
[1, 0],
[1, 1],
];
$y = [0, 0, 0, 1];
$perceptron = new Perceptron(2, 0.1);
$perceptron->train($X, $y, 20);
echo 'Perceptron (Rosenblatt learning rule) for logical AND:' . PHP_EOL;
echo '-----------' . PHP_EOL;
foreach ($X as $sample) {
echo '[' . implode(', ', $sample) . '] => ' . $perceptron->predict($sample) . PHP_EOL;
}
echo PHP_EOL . 'Weights and bias:' . PHP_EOL;
echo '-----------' . PHP_EOL;
echo 'w1 = ' . $perceptron->getWeights()[0] . PHP_EOL;
echo 'w2 = ' . $perceptron->getWeights()[1] . PHP_EOL;
echo 'b = ' . $perceptron->getBias() . PHP_EOL;
How one perceptron makes a decision
The animation shows the signal flow: inputs are multiplied by weights, summed with bias, passed through a step function, and converted into a binary output for the AND rule.
Δw1 = lr · error · x1
Δw2 = lr · error · x2
Δb = lr · error
Epoch (epoch)
-
Sample (sample)
-
Target y (target y)
-
Error (error)
-
| # | x | y | ŷ | w1, w2, b |
|---|
Result:
Memory: 0.008 Mb
Time running: 0.001 sec.
Perceptron (Rosenblatt learning rule) for logical AND:
-----------
[0, 0] => 0
[0, 1] => 0
[1, 0] => 0
[1, 1] => 1
Weights and bias:
-----------
w1 = 0.2
w2 = 0.1
b = -0.2