Paerson   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 5
c 3
b 1
f 0
lcom 0
cbo 0
dl 0
loc 50
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B run() 0 39 5
1
<?php
2
3
namespace stojg\recommend\strategy;
4
5
/**
6
 * Use if the data is subject to grade-inflation (different users may be using different scales).
7
 */
8
class Paerson
9
{
10
    /**
11
     * Single pass version of the paerson.
12
     * 
13
     * @param array $ratings1
14
     * @param array $ratings2
15
     *
16
     * @return float
17
     */
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