Last active
February 16, 2017 16:49
-
-
Save nicklasos/4b09c108e7785b87653e13bbb9202f85 to your computer and use it in GitHub Desktop.
ML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$set = [ | |
[1, 1], | |
[2, 2], | |
[3, 3], | |
[4, 4], | |
[5, 5], | |
[6, 6], | |
[6, 6], | |
[7, 7], | |
[8, 8], | |
[9, 9], | |
[10, 10], | |
[10, 10], | |
[12, 12], | |
[11, 11], | |
[11, 11], | |
[18, 18], | |
]; | |
list($Q0, $Q1) = gradient_descend(0.01, $set); | |
var_dump(h($Q0, $Q1, 180)); | |
function h(float $Q0, float $Q1, float $x): float | |
{ | |
return $Q0 + $Q1 * $x; | |
} | |
function J(float $Q0, float $Q1, array $set): float | |
{ | |
$sum = 0; | |
foreach ($set as list($x, $y)) { | |
$sum += (h($Q0, $Q1, $x) - $y) ** 2; | |
} | |
return 1 / 2 * $sum; | |
} | |
function gradient_descend(float $a, array $set): array | |
{ | |
$Q0 = 0; | |
$Q1 = 0; | |
$prevJ = null; | |
$optimQ0 = null; | |
$optimQ1 = null; | |
while (true) { | |
$prevQ0 = $Q0; | |
$prevQ1 = $Q1; | |
$prevJ = $J ?? null; | |
list($Q0, $Q1) = gradient_step($Q0, $Q1, $a, $set); | |
$J = J($Q0, $Q1, $set); | |
// TODO: use bcmath | |
if ($prevJ != null && $J >= $prevJ || strpos((string) $J, 'E') !== false) { | |
return [$prevQ0, $prevQ1]; | |
} | |
} | |
} | |
function gradient_step(float $Q0, float $Q1, float $a, array $set): array | |
{ | |
$m = count($set); | |
$sumQ0 = 0; | |
foreach ($set as list($x, $y)) { | |
$sumQ0 += h($Q0, $Q1, $x) - $y; | |
} | |
$tempQ0 = $Q0 - ($a * 1 / $m) * $sumQ0; | |
$sumQ1 = 0; | |
foreach ($set as list($x, $y)) { | |
$sumQ1 += (h($Q0, $Q1, $x) - $y) * $x; | |
} | |
$tempQ1 = $Q1 - ($a * 1 / $m) * $sumQ1; | |
return [$tempQ0, $tempQ1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment