hot_recall.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. '''
  4. @filename : hot_recall.py
  5. @description : 热度召回算法
  6. @time : 2025/01/21/00
  7. @author : Sherlock1011 & Min1027
  8. @Version : 1.0
  9. '''
  10. import pandas as pd
  11. from dao.redis_db import Redis
  12. from dao.mysql_client import Mysql
  13. import random
  14. from tqdm import tqdm
  15. import joblib
  16. random.seed(12345)
  17. class HotRecallModel:
  18. def __init__(self):
  19. self._redis_db = Redis()
  20. self._hotkeys = self.get_hotkeys()
  21. self._order_data = self._load_data_from_dataset()
  22. def get_hotkeys(self):
  23. info = self._redis_db.redis.zrange("hotkeys", 0, -1, withscores=True)
  24. hotkeys = []
  25. for item, _ in info:
  26. hotkeys.append(item)
  27. return hotkeys
  28. def _load_data_from_dataset(self):
  29. """从数据库中读取数据"""
  30. client = Mysql()
  31. tablename = "mock_order"
  32. query_text = "*"
  33. df = client.load_data(tablename, query_text)
  34. # 去除重复值和填补缺失值
  35. df.drop_duplicates(inplace=True)
  36. df.fillna(0, inplace=True)
  37. return df
  38. def _calculate_hot_score(self, hot_name):
  39. """
  40. 根据热度指标计算热度得分
  41. :param hot_name: 热度指标A
  42. :type param: string
  43. :return: 所有热度指标的得分
  44. :rtype: list
  45. """
  46. results = self._order_data.groupby("BB_RETAIL_CUSTOMER_CODE")[hot_name].mean().reset_index()
  47. sorted_results = results.sort_values(by=hot_name, ascending=False).reset_index(drop=True)
  48. item_hot_score = []
  49. # mock热度召回最大分数
  50. max_score = 1.0
  51. total_score = sorted_results.loc[0, hot_name] / max_score
  52. for row in sorted_results.itertuples(index=True, name="Row"):
  53. item = {row[1]:(row[2]/total_score)*100}
  54. item_hot_score.append(item)
  55. return {"key":f"{hot_name}", "value":item_hot_score}
  56. def calculate_all_hot_score(self):
  57. """
  58. 计算所有的热度指标得分
  59. """
  60. # hot_datas = []
  61. for hotkey_name in tqdm(self._hotkeys, desc="hot_recall:正在计算热度分数"):
  62. self.to_redis(self._calculate_hot_score(hotkey_name))
  63. def to_redis(self, rec_content_score):
  64. hotkey_name = rec_content_score["key"]
  65. rec_item_id = "hot:" + str(hotkey_name) # 修正 rec_item_id 拼接方式
  66. res = {}
  67. # rec_content_score["value"] 是一个包含字典的列表
  68. for item in rec_content_score["value"]:
  69. for content, score in item.items(): # item 形如 {A001: 75.0}
  70. res[content] = float(score) # 确保 score 是 float 类型
  71. if res: # 只有当 res 不为空时才执行 zadd
  72. self._redis_db.redis.zadd(rec_item_id, res)
  73. if __name__ == "__main__":
  74. # 序列化
  75. model = HotRecallModel()
  76. model.calculate_all_hot_score()
  77. # joblib.dump(model, "hot_recall.model")