Example 1. Parameter trajectory

Example 1. Parameter trajectory

The table below shows the trajectory of parameter $w$ during batch gradient descent on the data $y = 2x$.

 
<?php

$x 
= [1234];
$y = [2468];

$w 0.0;
$learningRate 0.1;
$epochs 20;
$n count($x);

echo 
"epoch\tw\tgradient\tloss\n";

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

    for (
$i 0$i $n$i++) {
        
$pred $w $x[$i];
        
$error $pred $y[$i];

        
$loss += $error ** 2;
        
$gradient += $x[$i] * $error;
    }

    
$loss /= $n;
    
$gradient = ($n) * $gradient;

    echo 
$epoch "\t" .
        
round($w4) . "\t" .
        
round($gradient4) . "\t\t" .
        
round($loss4) . PHP_EOL;

    
$w -= $learningRate $gradient;
}
Epoch: 1
w: 0 loss: 30
Speed

Learning rate:
Epochs:


Result: Memory: 0.001 Mb Time running: < 0.001 sec.
epoch	w		gradient	loss
1	0		-30		30
2	3		15		7.5
3	1.5		-7.5		1.875
4	2.25		3.75		0.469
5	1.875		-1.875		0.117
6	2.063		0.938		0.029
7	1.969		-0.469		0.007
8	2.016		0.234		0.002
9	1.992		-0.117		0
10	2.004		0.059		0
11	1.998		-0.029		0
12	2.001		0.015		0
13	2		-0.007		0
14	2		0.004		0
15	2		-0.002		0
16	2		0.001		0
17	2		-0		0
18	2		0		0
19	2		-0		0
20	2		0		0