Skip to content

Instantly share code, notes, and snippets.

@vwrs
Last active July 30, 2018 05:15
Show Gist options
  • Save vwrs/24af9a4bdc9171a878a4819b57ae9173 to your computer and use it in GitHub Desktop.
Save vwrs/24af9a4bdc9171a878a4819b57ae9173 to your computer and use it in GitHub Desktop.
calc Jaccard Index in PHP
<?php
/**
* Return the degree of similarity (Jaccard Index) for each product
*
* @param array $mat user-item matrix $mat[product_id][user_id] 1|null
* @param integer $product_id
* @author Hideaki Kanehara
* @return array key: product_id value: degree of similarity
*/
function jaccard($mat,$product_id)
{
$items = [];
foreach ($mat as $pid => $row) {
$numerator = count(array_intersect_assoc($mat[$product_id],$row));
$denominator = count(array_merge(
array_intersect_assoc($mat[$product_id],$row),
array_diff_assoc($mat[$product_id],$row),
array_diff_assoc($row,$mat[$product_id]
)));
$items[$pid] = $numerator / $denominator;
}
arsort($items);
// for recommendation system
// $num_slice = 5;
// unset($items[$id]);
// $items = array_slice($items, 0, $num_slice, True);
return $items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment