Case 1. Backpropagation by hand – one neuron in pure PHP

Implementation in pure PHP

Show Code

We implement the training of a single neuron ourselves – without RubixML, TensorFlow or PyTorch. The Neuron class does a forward pass, computes the loss, calculates gradients with the chain rule (backward) and updates weight and bias with gradient descent. The neuron learns on a toy phishing example: x is the number of suspicious factors in an email (0 – regular email, 1 – phishing email).

 
<?php

use app\classes\Neuron;

// x = number of suspicious factors, target: 0 = regular email, 1 = phishing email
$dataset = [
    [
0.0, 0.0],
    [
1.0, 1.0],
    [
2.0, 1.0],
];

mt_srand(42); // reproducible initial weight

$neuron = new Neuron();
$learningRate = 0.1;
$epochs = 1000;

echo 
'Training a single neuron:' . PHP_EOL;

for (
$epoch = 1; $epoch <= $epochs; $epoch++) {
    
$loss = 0.0;

    foreach (
$dataset as [$input, $target]) {
        
// Forward pass
        
$prediction = $neuron->forward($input);
        
// Loss
        
$loss += ($prediction - $target) ** 2;
        
// Backpropagation
        
$neuron->backward($target);
        
// Gradient descent
        
$neuron->update($learningRate);
    }

    if (
$epoch % 100 === 0) {
        echo 
sprintf('Epoch %d, loss: %.4f', $epoch, $loss) . PHP_EOL;
    }
}

echo 
PHP_EOL . 'Predictions after training:' . PHP_EOL;

foreach (
$dataset as [$input, $target]) {
    echo 
sprintf('x = %d => %.4f (target: %d)', $input, $neuron->forward($input), $target) . PHP_EOL;
}

echo 
PHP_EOL . 'Weight => ' . round($neuron->getWeight(), 4) . PHP_EOL;
echo 
'Bias => ' . round($neuron->getBias(), 4) . PHP_EOL;

Example:

x = 0 => 0
x = 1 => 1
x = 2 => 1

learning rate = 0.1
epochs = 1000
Result: Memory: 0.001 Mb Time running: 0.002 sec.
Training a single neuron:
Epoch 100, loss: 0.1546
Epoch 200, loss: 0.0894
Epoch 300, loss: 0.0608
Epoch 400, loss: 0.0453
Epoch 500, loss: 0.0358
Epoch 600, loss: 0.0294
Epoch 700, loss: 0.0248
Epoch 800, loss: 0.0214
Epoch 900, loss: 0.0188
Epoch 1000, loss: 0.0168

Predictions after training:
x = 0 => 0.1008 (target: 0)
x = 1 => 0.9190 (target: 1)
x = 2 => 0.9991 (target: 1)

Weight => 4.6178
Bias => -2.1885

Visualization: how the neuron fits the curve

The same training loop (forward → backward → update) runs in your browser. The blue curve is the neuron output sigmoid(wx + b) – at the start it is almost flat and wrong. With every epoch gradient descent shifts and steepens it until it passes through the points. Diamonds are the training data (green – regular email, red – phishing), orange dots are the current predictions, the dashed line marks where the output equals 0.5. Try a different learning rate: 10 overshoots and jitters, 0.1 is slow but stable.