Raver | d789517 | 2025-06-18 17:54:38 +0800 | [diff] [blame] | 1 | import pymysql |
| 2 | from typing import List, Tuple, Dict |
| 3 | import numpy as np |
| 4 | |
| 5 | class HotRecall: |
| 6 | """ |
| 7 | 热度召回算法实现 |
| 8 | 基于物品的热度(热度分数、交互次数等)进行召回 |
| 9 | """ |
| 10 | |
| 11 | def __init__(self, db_config: dict): |
| 12 | """ |
| 13 | 初始化热度召回模型 |
| 14 | |
| 15 | Args: |
| 16 | db_config: 数据库配置 |
| 17 | """ |
| 18 | self.db_config = db_config |
| 19 | self.hot_items = [] |
| 20 | |
| 21 | def _calculate_heat_scores(self): |
| 22 | """计算物品热度分数""" |
| 23 | conn = pymysql.connect(**self.db_config) |
| 24 | try: |
| 25 | cursor = conn.cursor() |
| 26 | |
| 27 | # 综合考虑多个热度指标 |
| 28 | cursor.execute(""" |
| 29 | SELECT |
| 30 | p.id, |
| 31 | p.heat, |
| 32 | COUNT(DISTINCT CASE WHEN b.type = 'like' THEN b.user_id END) as like_count, |
| 33 | COUNT(DISTINCT CASE WHEN b.type = 'favorite' THEN b.user_id END) as favorite_count, |
| 34 | COUNT(DISTINCT CASE WHEN b.type = 'comment' THEN b.user_id END) as comment_count, |
| 35 | COUNT(DISTINCT CASE WHEN b.type = 'view' THEN b.user_id END) as view_count, |
| 36 | COUNT(DISTINCT CASE WHEN b.type = 'share' THEN b.user_id END) as share_count, |
| 37 | DATEDIFF(NOW(), p.created_at) as days_since_created |
| 38 | FROM posts p |
| 39 | LEFT JOIN behaviors b ON p.id = b.post_id |
| 40 | WHERE p.status = 'published' |
| 41 | GROUP BY p.id, p.heat, p.created_at |
| 42 | """) |
| 43 | |
| 44 | results = cursor.fetchall() |
| 45 | |
| 46 | # 计算综合热度分数 |
| 47 | items_with_scores = [] |
| 48 | for row in results: |
| 49 | post_id, heat, like_count, favorite_count, comment_count, view_count, share_count, days_since_created = row |
| 50 | |
| 51 | # 处理None值 |
| 52 | heat = heat or 0 |
| 53 | like_count = like_count or 0 |
| 54 | favorite_count = favorite_count or 0 |
| 55 | comment_count = comment_count or 0 |
| 56 | view_count = view_count or 0 |
| 57 | share_count = share_count or 0 |
| 58 | days_since_created = days_since_created or 0 |
| 59 | |
| 60 | # 综合热度分数计算 |
| 61 | # 基础热度 + 加权的用户行为 + 时间衰减 |
| 62 | behavior_score = ( |
| 63 | like_count * 1.0 + |
| 64 | favorite_count * 2.0 + |
| 65 | comment_count * 3.0 + |
| 66 | view_count * 0.1 + |
| 67 | share_count * 5.0 |
| 68 | ) |
| 69 | |
| 70 | # 时间衰减因子(越新的内容热度越高) |
| 71 | time_decay = np.exp(-days_since_created / 30.0) # 30天半衰期 |
| 72 | |
| 73 | # 最终热度分数 |
| 74 | final_score = (heat * 0.3 + behavior_score * 0.7) * time_decay |
| 75 | |
| 76 | items_with_scores.append((post_id, final_score)) |
| 77 | |
| 78 | # 按热度排序 |
| 79 | self.hot_items = sorted(items_with_scores, key=lambda x: x[1], reverse=True) |
| 80 | |
| 81 | finally: |
| 82 | cursor.close() |
| 83 | conn.close() |
| 84 | |
| 85 | def train(self): |
| 86 | """训练热度召回模型""" |
| 87 | print("开始计算热度分数...") |
| 88 | self._calculate_heat_scores() |
| 89 | print(f"热度召回模型训练完成,共{len(self.hot_items)}个物品") |
| 90 | |
| 91 | def recall(self, user_id: int, num_items: int = 50) -> List[Tuple[int, float]]: |
| 92 | """ |
| 93 | 为用户召回热门物品 |
| 94 | |
| 95 | Args: |
| 96 | user_id: 用户ID |
| 97 | num_items: 召回物品数量 |
| 98 | |
| 99 | Returns: |
| 100 | List of (item_id, score) tuples |
| 101 | """ |
| 102 | # 如果尚未训练,先进行训练 |
| 103 | if not hasattr(self, 'hot_items') or not self.hot_items: |
| 104 | self.train() |
| 105 | |
| 106 | # 获取用户已交互的物品,避免重复推荐 |
| 107 | conn = pymysql.connect(**self.db_config) |
| 108 | try: |
| 109 | cursor = conn.cursor() |
| 110 | cursor.execute(""" |
| 111 | SELECT DISTINCT post_id |
| 112 | FROM behaviors |
| 113 | WHERE user_id = %s AND type IN ('like', 'favorite', 'comment') |
| 114 | """, (user_id,)) |
| 115 | |
| 116 | user_interacted_items = set(row[0] for row in cursor.fetchall()) |
| 117 | |
| 118 | finally: |
| 119 | cursor.close() |
| 120 | conn.close() |
| 121 | |
| 122 | # 过滤掉用户已交互的物品 |
| 123 | filtered_items = [ |
| 124 | (item_id, score) for item_id, score in self.hot_items |
| 125 | if item_id not in user_interacted_items |
| 126 | ] |
| 127 | |
| 128 | # 如果过滤后没有足够的候选,放宽条件:只过滤强交互(like, favorite, comment) |
| 129 | if len(filtered_items) < num_items: |
| 130 | print(f"热度召回:过滤后候选不足({len(filtered_items)}),放宽过滤条件") |
| 131 | conn = pymysql.connect(**self.db_config) |
| 132 | try: |
| 133 | cursor = conn.cursor() |
| 134 | cursor.execute(""" |
| 135 | SELECT DISTINCT post_id |
| 136 | FROM behaviors |
| 137 | WHERE user_id = %s AND type IN ('like', 'favorite', 'comment') |
| 138 | """, (user_id,)) |
| 139 | |
| 140 | strong_interacted_items = set(row[0] for row in cursor.fetchall()) |
| 141 | |
| 142 | finally: |
| 143 | cursor.close() |
| 144 | conn.close() |
| 145 | |
| 146 | filtered_items = [ |
| 147 | (item_id, score) for item_id, score in self.hot_items |
| 148 | if item_id not in strong_interacted_items |
| 149 | ] |
| 150 | |
| 151 | return filtered_items[:num_items] |
| 152 | |
| 153 | def get_top_hot_items(self, num_items: int = 100) -> List[Tuple[int, float]]: |
| 154 | """ |
| 155 | 获取全局热门物品(不考虑用户个性化) |
| 156 | |
| 157 | Args: |
| 158 | num_items: 返回物品数量 |
| 159 | |
| 160 | Returns: |
| 161 | List of (item_id, score) tuples |
| 162 | """ |
| 163 | return self.hot_items[:num_items] |