-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSlopeOne.php
50 lines (46 loc) · 1.88 KB
/
SlopeOne.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
class SlopeOne{
private $diffs = [];
private $freqs = [];
public function predict($userPrefs = []){
$preds = [];
$freqs = [];
$results = [];
foreach ($userPrefs as $item=>$rating){
foreach($this->diffs as $diffItem=>$diffRatings){
if(isset($this->freqs[$diffItem]) && isset($this->freqs[$diffItem][$item])){
$freq = $this->freqs[$diffItem][$item];
isset($preds[$diffItem]) || $preds[$diffItem] = 0.0;
isset($freqs[$diffItem]) || $freqs[$diffItem] = 0;
$preds[$diffItem] += $freq * ($diffRatings[$item] + $rating);
$freqs[$diffItem] += $freq;
}
}
}
foreach($preds as $item => $value){
if (!isset($userPrefs[$item]) && $freqs[$item] > 0){
$results[] = [$item=>$value/$freqs[$item]];
}
}
return $results;
}
public function update($userData){
foreach($userData as $ratings){
foreach($ratings as $item1=>$rating1){
isset($this->freqs[$item1]) || $this->freqs[$item1] = [];
isset($this->diffs[$item1]) || $this->diffs[$item1] = [];
foreach($ratings as $item2=>$rating2){
isset($this->freqs[$item1][$item2]) || $this->freqs[$item1][$item2] = 0;
isset($this->diffs[$item1][$item2]) || $this->diffs[$item1][$item2] = 0.0;
$this->freqs[$item1][$item2] += 1;
$this->diffs[$item1][$item2] += $rating1 - $rating2;
}
}
}
foreach($this->diffs as $item1 => &$ratings){
foreach($ratings as $item2=>$rating){
$ratings[$item2] /= $this->freqs[$item1][$item2];
}
}
}
}