Last active
December 26, 2024 17:07
-
-
Save binler/5d6c006885e97f1ba581cb62071b12fd to your computer and use it in GitHub Desktop.
Page reocmmend algorithm
This file contains hidden or 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 | |
class PageRecommender | |
{ | |
private $userLikes; // [userId => [pageId, pageId, ...]] | |
private $similarUsers; | |
public function __construct(array $userLikes) | |
{ | |
$this->userLikes = $userLikes; | |
$this->similarUsers = []; | |
} | |
public function findSimilarUsers($userId) | |
{ | |
$userPages = $this->userLikes[$userId] ?? []; | |
$similarities = []; | |
foreach ($this->userLikes as $otherId => $otherPages) { | |
if ($otherId !== $userId) { | |
// Jaccard similarity = (A ∩ B) / (A ∪ B) | |
$intersection = count(array_intersect($userPages, $otherPages)); | |
$union = count(array_unique(array_merge($userPages, $otherPages))); | |
$similarities[$otherId] = $union > 0 ? $intersection / $union : 0; | |
} | |
} | |
arsort($similarities); | |
$this->similarUsers = $similarities; | |
return $similarities; | |
} | |
public function recommendPages($userId, $numRecommendations = 5) | |
{ | |
$userPages = $this->userLikes[$userId] ?? []; | |
$this->findSimilarUsers($userId); | |
$pageScores = []; | |
$maxSimilarity = max($this->similarUsers); | |
foreach ($this->similarUsers as $similarUserId => $similarity) { | |
$normalizedSimilarity = $similarity / $maxSimilarity; | |
$similarUserPages = $this->userLikes[$similarUserId] ?? []; | |
foreach ($similarUserPages as $pageId) { | |
if (!in_array($pageId, $userPages)) { | |
if (!isset($pageScores[$pageId])) { | |
$pageScores[$pageId] = 0; | |
} | |
$pageScores[$pageId] += $normalizedSimilarity; | |
} | |
} | |
} | |
arsort($pageScores); | |
return array_slice($pageScores, 0, $numRecommendations, true); | |
} | |
} | |
// Example usage | |
$userLikes = [ | |
'user1' => ['page1', 'page2', 'page3', 'page4', 'page5', 'page6', 'page7', 'page8', 'page9', 'page10'], | |
'user2' => ['page1', 'page2', 'page3', 'page11', 'page12'], | |
'user3' => ['page2', 'page3', 'page4', 'page13', 'page14'], | |
'user4' => ['page1', 'page2', 'page3', 'page4', 'page15', 'page16'] | |
]; | |
$recommender = new PageRecommender($userLikes); | |
$recommendedPages = $recommender->recommendPages('user1', 5); | |
print_r($recommendedPages); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Giải thích chi tiết thuật toán:
Thuật toán này hiệu quả vì: