Conditions | 5 |
Paths | 9 |
Total Lines | 39 |
Code Lines | 25 |
Lines | 0 |
Ratio | 0 % |
Changes | 3 | ||
Bugs | 1 | Features | 0 |
1 | <?php |
||
18 | public function run($ratings1, $ratings2) |
||
19 | { |
||
20 | $numCoRatedItems = 0; |
||
21 | $dotProduct = 0; |
||
22 | $rating1Sum = 0; |
||
23 | $rating1SumSqr = 0; |
||
24 | $rating2Sum = 0; |
||
25 | $rating2SumSqr = 0; |
||
26 | foreach ($ratings1 as $item => $rating1) { |
||
27 | if (!isset($ratings2[$item])) { |
||
28 | continue; |
||
29 | } |
||
30 | $numCoRatedItems += 1; |
||
31 | $dotProduct += $rating1 * $ratings2[$item]; |
||
32 | $rating1Sum += $rating1; |
||
33 | $rating1SumSqr += pow($rating1, 2); |
||
34 | $rating2Sum += $ratings2[$item]; |
||
35 | $rating2SumSqr += pow($ratings2[$item], 2); |
||
36 | } |
||
37 | |||
38 | // There is no correlation at all |
||
39 | if ($numCoRatedItems == 0) { |
||
40 | return false; |
||
41 | } |
||
42 | |||
43 | $denominator = sqrt( |
||
44 | ($rating1SumSqr - (pow($rating1Sum, 2) / $numCoRatedItems)) * |
||
45 | ($rating2SumSqr - (pow($rating2Sum, 2) / $numCoRatedItems)) |
||
46 | ); |
||
47 | |||
48 | if ($denominator == 0) { |
||
49 | return false; |
||
50 | } |
||
51 | |||
52 | // the closer abs(paerson) is to 1 to better correlation is it |
||
53 | $paerson = ($dotProduct - ($rating1Sum * $rating2Sum / $numCoRatedItems)) / $denominator; |
||
54 | |||
55 | return 1 - abs($paerson); |
||
56 | } |
||
57 | } |
||
58 |