Cosine   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B run() 0 24 5
1
<?php
2
3
namespace stojg\recommend\strategy;
4
5
/**
6
 * Cosine similarity is a measure of similarity between two vectors of an inner product space that measures the 
7
 * cosine of the angle between them. The cosine of 0° is 1, and it is less than 1 for any other angle. It is thus a 
8
 * judgement of orientation and not magnitude: two vectors with the same orientation have a Cosine similarity of 1, 
9
 * two vectors at 90° have a  similarity of 0, and two vectors diametrically opposed have a similarity of -1, 
10
 * independent of their magnitude.
11
 */
12
class Cosine
13
{
14
    /**
15
     * Use if the data is sparse.
16
     */
17
    public function run($rating1, $rating2)
18
    {
19
        $dotProduct = 0;
20
        $sqrLenght1 = 0;
21
        foreach ($rating1 as $item => $rating) {
22
            if (!isset($rating2[$item])) {
23
                continue;
24
            }
25
            $sqrLenght1 += pow($rating, 2);
26
            $dotProduct += $rating * $rating2[$item];
27
        }
28
        if (!$sqrLenght1) {
29
            return false;
30
        }
31
        $length1 = sqrt($sqrLenght1);
32
33
        $sqrLength2 = 0;
34
        foreach ($rating2 as $item => $rating) {
35
            $sqrLength2 += pow($rating, 2);
36
        }
37
        $length2 = sqrt($sqrLength2);
38
39
        return 1 - abs($dotProduct / ($length1 * $length2));
40
    }
41
}
42