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

Implementation in pure PHP

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).

Example of code: Class Neuron:

 
<?php

namespace app\classes;

class 
Neuron {
    private 
float $weight;
    private 
float $bias;
    private 
float $lastInput = 0.0;
    private 
float $lastOutput = 0.0;
    private 
float $weightGradient = 0.0;
    private 
float $biasGradient = 0.0;

    public function 
__construct() {
        
$this->weight = mt_rand(-100, 100) / 100;
        
$this->bias = 0.0;
    }

    public function 
getWeight(): float {
        return 
$this->weight;
    }

    public function 
getBias(): float {
        return 
$this->bias;
    }

    public function 
forward(float $input): float {
        
$this->lastInput = $input;
        
$z = $this->weight * $input + $this->bias;
        
$this->lastOutput = $this->sigmoid($z);

        return 
$this->lastOutput;
    }

    public function 
backward(float $target): void {
        
$dL_da = 2 * ($this->lastOutput - $target);
        
$da_dz = $this->sigmoidDerivative($this->lastOutput);
        
$dz_dw = $this->lastInput;

        
$this->weightGradient = $dL_da * $da_dz * $dz_dw;
        
$this->biasGradient = $dL_da * $da_dz;
    }

    public function 
update(float $learningRate): void {
        
$this->weight -= $learningRate * $this->weightGradient;
        
$this->bias -= $learningRate * $this->biasGradient;
    }

    private function 
sigmoid(float $x): float {
        return 
1 / (1 + exp(-$x));
    }

    
// σ'(z) = a(1 - a): the already computed output is enough
    
private function sigmoidDerivative(float $a): float {
        return 
$a * (1 - $a);
    }
}