PHP实现推荐
PHP 推荐系统实现方法
基于内容的推荐
内容推荐通过分析用户历史行为和项目特征匹配相似内容。在PHP中可使用TF-IDF算法计算文本相似度。
// 计算TF-IDF
function tfidf($terms, $documents) {
$tf = array_count_values($terms);
array_walk($tf, function(&$value, $key) use ($terms) {
$value = $value / count($terms);
});
$idf = [];
$total_docs = count($documents);
foreach(array_unique($terms) as $term) {
$docs_with_term = 0;
foreach($documents as $doc) {
if(in_array($term, $doc)) $docs_with_term++;
}
$idf[$term] = log($total_docs / ($docs_with_term + 1));
}
$tfidf = [];
foreach($tf as $term => $value) {
$tfidf[$term] = $value * $idf[$term];
}
return $tfidf;
}
协同过滤推荐
协同过滤分为用户协同和项目协同两种方式,通过PHP数组实现用户评分矩阵:
$userRatings = [
'User1' => ['ItemA' => 5, 'ItemB' => 3],
'User2' => ['ItemA' => 4, 'ItemC' => 2]
];
// 计算余弦相似度
function cosineSimilarity($vec1, $vec2) {
$dotProduct = $magnitude1 = $magnitude2 = 0;
$keys = array_unique(array_merge(array_keys($vec1), array_keys($vec2)));
foreach($keys as $key) {
$v1 = $vec1[$key] ?? 0;
$v2 = $vec2[$key] ?? 0;
$dotProduct += $v1 * $v2;
$magnitude1 += $v1 * $v1;
$magnitude2 += $v2 * $v2;
}
return $dotProduct / (sqrt($magnitude1) * sqrt($magnitude2));
}
混合推荐系统
结合内容推荐和协同过滤的优势:
class HybridRecommender {
private $contentWeights;
private $cfWeights;
public function __construct($contentWeight = 0.5, $cfWeight = 0.5) {
$this->contentWeights = $contentWeight;
$this->cfWeights = $cfWeight;
}
public function recommend($userId) {
$contentScores = $this->getContentScores($userId);
$cfScores = $this->getCFScores($userId);
$combined = [];
foreach($contentScores as $item => $score) {
$combined[$item] = $score * $this->contentWeights
+ ($cfScores[$item] ?? 0) * $this->cfWeights;
}
arsort($combined);
return array_slice($combined, 0, 5, true);
}
}
数据库设计
推荐系统通常需要以下基本表结构:
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50)
);
CREATE TABLE items (
id INT PRIMARY KEY,
title VARCHAR(100),
description TEXT
);
CREATE TABLE user_actions (
user_id INT,
item_id INT,
action_type ENUM('view','purchase','rating'),
value FLOAT,
timestamp DATETIME,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (item_id) REFERENCES items(id)
);
性能优化建议
使用Redis缓存热门推荐结果:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$cacheKey = "recs:$userId";
if(!$redis->exists($cacheKey)) {
$recommendations = $recommender->generate($userId);
$redis->setex($cacheKey, 3600, json_encode($recommendations));
}
return json_decode($redis->get($cacheKey), true);
实现推荐系统时需要考虑冷启动问题,可通过热门内容填充、用户注册信息收集等方式解决。对于大规模数据,建议使用专门的推荐引擎如Mahout或TensorFlow Serving,PHP通过API调用获取推荐结果。







