Hello! I found this source code from github. its a NK-NN algorithm and is there a way to test it if its “working”? like put some data in an array?. I have very minimal experience with PHP. Thank you so much!
“`
**functions.php**
<?php
function ll_transpose($rows)
{
$columns = array();
for($i=0;$i<count($rows);$i++)
{
for($k = 0; $k<count($rows[$i]); $k++)
{
$columns[$k][$i] = $rows[$i][$k];
}
}
return $columns;
}
function ll_mean($array) {
return array_sum($array)/count($array);
}
function ll_variance($array) {
$mean = ll_mean($array);
$sum_difference = 0;
$n = count($array);
for($i=0; $i<$n; $i++) {
$sum_difference += pow(($array[$i] – $mean),2);
}
$variance = $sum_difference / $n;
return $variance;
}
function ll_euclidian_distance($a, $b) {
if(count($a) != count($b))
return false;
$distance = 0;
for($i=0;$i<count($a);$i++)
{
$distance += pow($a[$i] – $b[$i], 2);
}
return sqrt($distance);
}
?>
**knn.php**
<?php
require_once dirname(__FILE__) . “/../accessory/functions.php”;
// returns the predictions (sorted array) in an array (“bestprediction”=>count, “pred2″=>count2…)
function ll_nn_predict($xs, $ys, $row, $k)
{
$distances = ll_nearestNeighbors($xs, $row);
$distances = array_slice($distances, 0, $k); // get top k.
$predictions = array();
foreach($distances as $neighbor=>$distance)
{
$predictions[$ys[$neighbor]]++;
}
asort($predictions);
return $predictions;
}
// returns the nearest neighbors for the nth row of $xs (sorted euclidian distances).
function ll_nearestNeighbors($xs, $row) {
$testPoint = $xs[$row];
$distances = _ll_distances_to_point($xs, $testPoint);
return $distances;
}
function _ll_distances_to_point($xs, $x) {
$distances = array();
foreach($xs as $index=>$xi) {
$distances[$index] = ll_euclidian_distance($xi, $x);
}
asort($distances);
array_shift($distances); // has “self” as the smallest distance.
return $distances;
}
?>