Last active
July 30, 2018 05:15
-
-
Save vwrs/24af9a4bdc9171a878a4819b57ae9173 to your computer and use it in GitHub Desktop.
calc Jaccard Index in PHP
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 | |
/** | |
* 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