Skip to content

Instantly share code, notes, and snippets.

@greydnls
Last active August 29, 2015 14:06
Show Gist options
  • Save greydnls/59aac4504230677552d6 to your computer and use it in GitHub Desktop.
Save greydnls/59aac4504230677552d6 to your computer and use it in GitHub Desktop.
Gradient Descent
<?php
function computeErrorForLineGivenPoints($b, $m, array $points)
{
$total_error = 0;
foreach ($points as $point)
{
$total_error += pow(($point['y'] - ($m * $point['x'] + $b)), 2);
}
return $total_error/count($points);
}
function stepGradient($b_current, $m_current, array $points, $learning_rate)
{
$b_gradient = 0;
$m_gradient = 0;
$n = (float)count($points);
foreach ($points as $point)
{
$b_gradient += -(2 / $n) * ($point['y'] - (($m_current * $point['x']) + $b_current));
$m_gradient += -(2 / $n) * $point['x'] * ($point['y'] - (($m_current * $point['x']) + $b_current));
}
$new_b = $b_current - ($learning_rate * $b_gradient);
$new_m = $m_current - ($learning_rate * $m_gradient);
return [$new_b, $new_m];
}
@greydnls
Copy link
Author

Functions for performing linear regression via gradient descent.

Ported from python samples seen here:
http://spin.atomicobject.com/2014/06/24/gradient-descent-linear-regression/

@redknitin
Copy link

I'm mixing platforms too - I wrote a Python based code generator to write Laravel (PHP) code. It's a bit rough around the edges, but it does a decent job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment