<?php
// Simulated ratings for books from input_database sample
// array (ratings:(0-->5), 'Name of book")
$input_data = array( // 2D array[indexes]
array(0, 'Van Helsing'), // [0]
array(3, 'Dracula'), // [1]
array(2, 'The Pearl'), // [2]
array(4, 'Pocahontas'), // [3]
array(0, 'How to be good'), // [4]
array(4, 'I know how to love'), // [5]
array(2, 'How to be millionaire'), // [6]
array(5, 'Eat, pray and love'), // [7]
array(4, 'How to follow God'), // [8]
array(5, 'Intro to Philosophy'), // [9]
array(2, 'Intro Algorithms'), // [10]
array(2, 'How to happy'), // [11]
array(4, 'How to have sex'), // [12]
array(0, 'Quantum Mechanics'), //[13]
array(3, 'Purpose Driven live') // [14]
);
// Calculat the distances or differences of points
$distance_matrix = $input_data;
//array_walk — Apply a user function to every member of an array
array_walk($distance_matrix, 'Euclid_Distance', $input_data);
// Specify the data point index, it would compute the #3NN automatically
$neighbors = KNN($distance_matrix, 13);
echo assoc_book_name($input_data, $neighbors); // red
// This is necessary for calculating the distance between ratings values
function Euclid_Distance(&$sourceCoords, $sourceKey, $input_data)
{
$distance_matrix = array();
list ($Xi, $Yi) = $sourceCoords;
foreach ($input_data as $destinationKey => $destinationCoords)
{
// Same point, ignore
if ($sourceKey == $destinationKey)
{
continue;
}
list ($X_2, $Y_2) = $destinationCoords;
//$distance_matrix[$destinationKey] = abs(pow($x1 - $x2, 2) + pow($y1 - $y2, 2));
$distance_matrix[$destinationKey] = sqrt(pow($Xi - $X_2, 2) + pow($Yi - $Y_2, 2));
}
asort($distance_matrix);
$sourceCoords = $distance_matrix;
}
// Returns n-nearest neighbors
function KNN($distance_matrix, $N)
{ // 3NN, K = 3
return array_slice($distance_matrix[$N], 0, 3, true);
}
/*
Gets result label from associated input_data
*/
function assoc_book_name($input_data, $neighbors)
{
$results = array();
$neighbors = array_keys($neighbors);
foreach ($neighbors as $neighbor)
{ // 2 (xi, yi) before, look at 1 data point
$results[] = $input_data[$neighbor][1];
}
$val = array_count_values($results);
$val = array_flip($val);
ksort($val);
return array_pop($val);
}