爆款云主机2核4G限时秒杀,88元/年起!
查看详情

活动

天翼云最新优惠活动,涵盖免费试用,产品折扣等,助您降本增效!
热门活动
  • 618智算钜惠季 爆款云主机2核4G限时秒杀,88元/年起!
  • 免费体验DeepSeek,上天翼云息壤 NEW 新老用户均可免费体验2500万Tokens,限时两周
  • 云上钜惠 HOT 爆款云主机全场特惠,更有万元锦鲤券等你来领!
  • 算力套餐 HOT 让算力触手可及
  • 天翼云脑AOne NEW 连接、保护、办公,All-in-One!
  • 中小企业应用上云专场 产品组合下单即享折上9折起,助力企业快速上云
  • 息壤高校钜惠活动 NEW 天翼云息壤杯高校AI大赛,数款产品享受线上订购超值特惠
  • 天翼云电脑专场 HOT 移动办公新选择,爆款4核8G畅享1年3.5折起,快来抢购!
  • 天翼云奖励推广计划 加入成为云推官,推荐新用户注册下单得现金奖励
免费活动
  • 免费试用中心 HOT 多款云产品免费试用,快来开启云上之旅
  • 天翼云用户体验官 NEW 您的洞察,重塑科技边界

智算服务

打造统一的产品能力,实现算网调度、训练推理、技术架构、资源管理一体化智算服务
智算云(DeepSeek专区)
科研助手
  • 算力商城
  • 应用商城
  • 开发机
  • 并行计算
算力互联调度平台
  • 应用市场
  • 算力市场
  • 算力调度推荐
一站式智算服务平台
  • 模型广场
  • 体验中心
  • 服务接入
智算一体机
  • 智算一体机
大模型
  • DeepSeek-R1-昇腾版(671B)
  • DeepSeek-R1-英伟达版(671B)
  • DeepSeek-V3-昇腾版(671B)
  • DeepSeek-R1-Distill-Llama-70B
  • DeepSeek-R1-Distill-Qwen-32B
  • Qwen2-72B-Instruct
  • StableDiffusion-V2.1
  • TeleChat-12B

应用商城

天翼云精选行业优秀合作伙伴及千余款商品,提供一站式云上应用服务
进入甄选商城进入云市场创新解决方案
办公协同
  • WPS云文档
  • 安全邮箱
  • EMM手机管家
  • 智能商业平台
财务管理
  • 工资条
  • 税务风控云
企业应用
  • 翼信息化运维服务
  • 翼视频云归档解决方案
工业能源
  • 智慧工厂_生产流程管理解决方案
  • 智慧工地
建站工具
  • SSL证书
  • 新域名服务
网络工具
  • 翼云加速
灾备迁移
  • 云管家2.0
  • 翼备份
资源管理
  • 全栈混合云敏捷版(软件)
  • 全栈混合云敏捷版(一体机)
行业应用
  • 翼电子教室
  • 翼智慧显示一体化解决方案

合作伙伴

天翼云携手合作伙伴,共创云上生态,合作共赢
天翼云生态合作中心
  • 天翼云生态合作中心
天翼云渠道合作伙伴
  • 天翼云代理渠道合作伙伴
天翼云服务合作伙伴
  • 天翼云集成商交付能力认证
天翼云应用合作伙伴
  • 天翼云云市场合作伙伴
  • 天翼云甄选商城合作伙伴
天翼云技术合作伙伴
  • 天翼云OpenAPI中心
  • 天翼云EasyCoding平台
天翼云培训认证
  • 天翼云学堂
  • 天翼云市场商学院
天翼云合作计划
  • 云汇计划
天翼云东升计划
  • 适配中心
  • 东升计划
  • 适配互认证

开发者

开发者相关功能入口汇聚
技术社区
  • 专栏文章
  • 互动问答
  • 技术视频
资源与工具
  • OpenAPI中心
开放能力
  • EasyCoding敏捷开发平台
培训与认证
  • 天翼云学堂
  • 天翼云认证
魔乐社区
  • 魔乐社区

支持与服务

为您提供全方位支持与服务,全流程技术保障,助您轻松上云,安全无忧
文档与工具
  • 文档中心
  • 新手上云
  • 自助服务
  • OpenAPI中心
定价
  • 价格计算器
  • 定价策略
基础服务
  • 售前咨询
  • 在线支持
  • 在线支持
  • 工单服务
  • 建议与反馈
  • 用户体验官
  • 服务保障
  • 客户公告
  • 会员中心
增值服务
  • 红心服务
  • 首保服务
  • 客户支持计划
  • 专家技术服务
  • 备案管家

了解天翼云

天翼云秉承央企使命,致力于成为数字经济主力军,投身科技强国伟大事业,为用户提供安全、普惠云服务
品牌介绍
  • 关于天翼云
  • 智算云
  • 天翼云4.0
  • 新闻资讯
  • 天翼云APP
基础设施
  • 全球基础设施
  • 信任中心
最佳实践
  • 精选案例
  • 超级探访
  • 云杂志
  • 分析师和白皮书
  • 天翼云·创新直播间
市场活动
  • 2025智能云生态大会
  • 2024智算云生态大会
  • 2023云生态大会
  • 2022云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心

      推荐系统实战——自动化构建用户以及物料画像

      首页 知识中心 服务器 文章详情页

      推荐系统实战——自动化构建用户以及物料画像

      2024-11-13 09:09:40 阅读次数:27

      redis

      自动化构建用户以及物料画像

      推荐系统实战——自动化构建用户以及物料画像

      意义

      离线自动化构建用户和物料的画像,这部分内容在新闻推荐系统中是为系统源源不断添加新物料的途径,由于我们的物料是通过爬虫获取的,所以还需要对爬取的数据进行处理,也就是构造新闻的画像。对于用户侧的画像则是需要每天将新注册的用户添加到用户画像库中,对于在系统中产生了行为的用户,我们还需要定期的更新用户的画像(长短期)。下面分别从物料侧和用户侧两个方面来详细解释这两类画像在系统中是如何自动化构建的。

      新物料来源

      新物料的来源,物料是通过每天在新闻网站上爬取获取的

      物料画像的更新

      物料画像的更新主要有一下几个方面:

      新物料画像添加到物料库中
      旧物料画像,通过用户的交互记录进行更新
      首先说一下新物料添加到物料库的逻辑是什么,新物料添加到物料库这件事情肯定是发生在新闻爬取之后的,然后要将新物料添加到物料库还需要对新物料做一些简单的画像处理,目前我们定义的画像字段如下(处理后的画像存储在Mongodb):
      具体的逻辑就是遍历今天爬取的所有文章,然后通过文章的title来判断这篇文章是否已经在物料库中(新闻网站有可能有些相同的文章会出现在多天)来去重。然后再根据我们定义的一些字段,给画像相应的字段初始化,最后就是存入画像物料池中。

      关于旧物料画像的更新,这里就需要先了解一下旧物料哪些字段会被用户的行为更新。下面是新闻列表展示页,我们会发现前端会展示新闻的阅读、喜欢及收藏次数。而用户的交互(阅读、点赞和收藏)会改变这些值。

      为了能够实时的在前端显示新闻的这些动态行为信息,我们提前将新闻的动态信息存储到了redis中,线上获取的时候是直接从redis中获取新闻的数据,并且如果用户对新闻产生了交互,那么这些动态信息就会被更新,我们也是直接更新redis中的值,这样做主要是为了能够让前端可以实时的获取的新闻最新的动态画像信息。

      通过上面的内容我们了解到,新闻的动态画像的更新是在redis中进行的,而redis又是一个内存数据库,资源是非常宝贵的,我们不能一直将新闻的信息存储在里面,而是每天进行一次更新,只更新哪些今天可能会被用来展示的新闻(有些新闻可能从发表到现在太久了,由于新闻的时效性就没有必要再展示了)。所以为了能够保存新闻历史的动态信息,系统还需要每天将redis中的动态新闻信息更新到mongodb存储的新闻画像库中,这里的逻辑也是每天会定时触发,这里的逻辑会放在更新完新物料的画像之后,当然这里两个的先后顺序并没有什么影响,只需要注意更新物料动态画像的时候一定得再redis数据清空之前。

      其实这里还有个逻辑需要说明一下,新闻的画像库其实是有两个的,一个被称为是特征库FeatureProtrail, 它存储了物料的所有字段。还有一个是存储前端展示内容的画像库RedisProtrail, 这个画像库中的物料是一样的多,只不过每个物料存储的内容不一样,这个特征库的内容每天都会被更新,作为存储再redis中的新闻内容的备份内容。所以在完成了新、旧物料画像的更新之后,我们需要将最新的物料库中的新闻信息往RedisProtrail物料库中写一份,并去掉一些前端展示不需要的字段内容。

      # -*- coding: utf-8 -*-
      from re import S
      import sys
      import json
      sys.path.append("../")
      from material_process.utils import get_key_words
      from dao.mongo_server import MongoServer
      from dao.redis_server import RedisServer

      """
      新闻画像中包含的字段:
      0. news_id 新闻的id
      1. title 标题
      2. raw_key_words (爬下来的关键词,可能有缺失)
      3. manual_key_words (根据内容生成的关键词)
      4. ctime 时间
      5. content 新闻具体内容
      6. cate 新闻类别
      7. likes 新闻点赞数量
      8. collections 新闻收藏数量
      9. read_nums 阅读次数
      10. url 新闻原始链接
      """

      class NewsProtraitServer:
      def __init__(self):
      """初始化相关参数
      """
      self.mongo_server = MongoServer()
      self.sina_collection = self.mongo_server.get_sina_news_collection()
      self.material_collection = self.mongo_server.get_feature_protrail_collection()
      self.redis_mongo_collection = self.mongo_server.get_redis_mongo_collection()
      self.news_dynamic_feature_redis = RedisServer().get_dynamic_news_info_redis()

      def _find_by_title(self, collection, title):
      """从数据库中查找是否有相同标题的新闻数据
      数据库存在当前标题的数据返回True, 反之返回Flase
      """
      # find方法,返回的是一个迭代器
      find_res = collection.find({"title": title})
      if len(list(find_res)) != 0:
      return True
      return False

      def _generate_feature_protrail_item(self, item):
      """生成特征画像数据,返回一个新的字典
      """
      news_item = dict()
      news_item['news_id'] = item['news_id']
      news_item['title'] = item['title']
      # 从新闻内容中提取的关键词没有原始新闻爬取时的关键词准确,所以手动提取的关键词
      # 只是作为一个补充,当原始新闻中没有提供关键词的时候可以使用
      news_item['raw_key_words'] = item['raw_key_words']
      key_words_list = get_key_words(item['content'])
      news_item['manual_key_words'] = ",".join(key_words_list)
      news_item['ctime'] = item['ctime']
      news_item['content'] = item['content']
      news_item['cate'] = item['cate']
      news_item['url'] = item['url']
      news_item['likes'] = 0
      news_item['collections'] = 0
      news_item['read_num'] = 0
      news_item['hot_value'] = 1000 # 初始化一个比较大的热度值,会随着时间进行衰减

      return news_item

      def update_new_items(self):
      """将今天爬取的数据构造画像存入画像数据库中
      """
      # 遍历今天爬取的所有数据
      for item in self.sina_collection.find():
      # 根据标题进行去重
      if self._find_by_title(self.material_collection, item["title"]):
      continue
      news_item = self._generate_feature_protrail_item(item)
      # 插入物料池
      self.material_collection.insert_one(news_item)

      print("run update_new_items success.")

      def update_redis_mongo_protrail_data(self):
      """每天都需要将新闻详情更新到redis中,并且将前一天的redis数据删掉
      """
      # 每天先删除前一天的redis展示数据,然后再重新写入
      self.redis_mongo_collection.drop()
      print("delete RedisProtrail ...")
      # 遍历特征库
      for item in self.material_collection.find():
      news_item = dict()
      news_item['news_id'] = item['news_id']
      news_item['title'] = item['title']
      news_item['ctime'] = item['ctime']
      news_item['content'] = item['content']
      news_item['cate'] = item['cate']
      news_item['url'] = item['url']
      news_item['likes'] = 0
      news_item['collections'] = 0
      news_item['read_num'] = 0

      self.redis_mongo_collection.insert_one(news_item)
      print("run update_redis_mongo_protrail_data success.")

      def update_dynamic_feature_protrail(self):
      """用redis的动态画像更新mongodb的画像
      """
      # 遍历redis的动态画像,将mongodb中对应的动态画像更新
      news_list = self.news_dynamic_feature_redis.keys()
      for news_key in news_list:
      news_dynamic_info_str = self.news_dynamic_feature_redis.get(news_key)
      news_dynamic_info_str = news_dynamic_info_str.replace("'", '"' ) # 将单引号都替换成双引号
      news_dynamic_info_dict = json.loads(news_dynamic_info_str)

      # 查询mongodb中对应的数据,并将对应的画像进行修改
      news_id = news_key.split(":")[1]
      mongo_info = self.material_collection.find_one({"news_id": news_id})
      new_mongo_info = mongo_info.copy()
      new_mongo_info['likes'] = news_dynamic_info_dict["likes"]
      new_mongo_info['collections'] = news_dynamic_info_dict["collections"]
      new_mongo_info['read_num'] = news_dynamic_info_dict["read_num"]

      self.material_collection.replace_one(mongo_info, new_mongo_info, upsert=True) # upsert为True的话,没有就插入
      print("update_dynamic_feature_protrail success.")


      # 系统最终执行的不是这个脚本,下面的代码是用来测试的
      if __name__ == "__main__":
      news_protrait = NewsProtraitServer()
      # 新物料画像的更新
      news_protrait.update_new_items()
      # 更新动态特征
      news_protrait.update_dynamic_feature_protrail()
      # redis展示新闻内容的备份
      news_protrait.update_redis_mongo_protrail_data()

      物料更新添加入redis

      上面的内容说完了物料的更新,接下来介绍一下对于更新完的物料是如何添加到redis数据库中去的。关于新闻内容在redis中的存储,我们将新闻的信息拆成了两部分,一部分是新闻不会发生变化的属性(例如,创建时间、标题、新闻内容等),还有一部分是物料的动态属性,在redis中存储的key的标识分别为:static_news_detail:news_id和dynamic_news_detail:news_id 下面是redis中存储的真实内容

      推荐系统实战——自动化构建用户以及物料画像

       

      推荐系统实战——自动化构建用户以及物料画像

       

      这么做的目的是为了线上实时更改物料动态信息的时候更加高效一点。当需要获取某篇新闻的详细信息的时候需要查这两份数据并将数据这两部分数据拼起来最终才发送给前端展示。这部分的代码逻辑如下:

      import sys
      sys.path.append("../../")
      from dao.mongo_server import MongoServer
      from dao.redis_server import RedisServer


      class NewsRedisServer(object):
      def __init__(self):
      self.rec_list_redis = RedisServer().get_reclist_redis()
      self.static_news_info_redis = RedisServer().get_static_news_info_redis()
      self.dynamic_news_info_redis = RedisServer().get_dynamic_news_info_redis()

      self.redis_mongo_collection = MongoServer().get_redis_mongo_collection()

      # 删除前一天redis中的内容
      self._flush_redis_db()

      def _flush_redis_db(self):
      """每天都需要删除redis中的内容,更新当天新的内容上去
      """
      try:
      self.rec_list_redis.flushall()
      except Exception:
      print("flush redis fail ... ")

      def _get_news_id_list(self):
      """获取物料库中所有的新闻id
      """
      # 获取所有数据的news_id,
      # 暴力获取,直接遍历整个数据库,得到所有新闻的id
      # TODO 应该存在优化方法可以通过查询的方式只返回new_id字段
      news_id_list = []
      for item in self.redis_mongo_collection.find():
      news_id_list.append(item["news_id"])
      return news_id_list

      def _set_info_to_redis(self, redisdb, content):
      """将content添加到指定redis
      """
      try:
      redisdb.set(*content)
      except Exception:
      print("set content fail".format(content))

      def news_detail_to_redis(self):
      """将需要展示的画像内容存储到redis
      静态不变的特征存到static_news_info_db_num
      动态会发生改变的特征存到dynamic_news_info_db_num
      """
      news_id_list = self._get_news_id_list()

      for news_id in news_id_list:
      news_item_dict = self.redis_mongo_collection.find_one({"news_id": news_id}) # 返回的是一个列表里面套了一个字典
      news_item_dict.pop("_id")

      # 分离动态属性和静态属性
      static_news_info_dict = dict()
      static_news_info_dict['news_id'] = news_item_dict['news_id']
      static_news_info_dict['title'] = news_item_dict['title']
      static_news_info_dict['ctime'] = news_item_dict['ctime']
      static_news_info_dict['content'] = news_item_dict['content']
      static_news_info_dict['cate'] = news_item_dict['cate']
      static_news_info_dict['url'] = news_item_dict['url']
      static_content_tuple = "static_news_detail:" + str(news_id), str(static_news_info_dict)
      self._set_info_to_redis(self.static_news_info_redis, static_content_tuple)

      dynamic_news_info_dict = dict()
      dynamic_news_info_dict['likes'] = news_item_dict['likes']
      dynamic_news_info_dict['collections'] = news_item_dict['collections']
      dynamic_news_info_dict['read_num'] = news_item_dict['read_num']
      dynamic_content_tuple = "dynamic_news_detail:" + str(news_id), str(dynamic_news_info_dict)
      self._set_info_to_redis(self.dynamic_news_info_redis, dynamic_content_tuple)

      print("news detail info are saved in redis db.")


      if __name__ == "__main__":
      # 每次创建这个对象的时候都会把数据库中之前的内容删除
      news_redis_server = NewsRedisServer()
      # 将最新的前端展示的画像传到redis
      news_redis_server.news_detail_to_redis()

      **到此位置,离线物料画像的更新逻辑就介绍完了,最后把上面的逻辑用代码全部串起来的话就如下代码:**下面的代码是会在每天定时运行的,这样就将物料侧的画像构建逻辑穿起来了

      合并,物料画像构建逻辑

      from material_process.news_protrait import NewsProtraitServer
      from material_process.news_to_redis import NewsRedisServer

      def process_material():
      """物料处理函数
      """
      # 画像处理
      protrail_server = NewsProtraitServer()
      # 处理最新爬取新闻的画像,存入特征库
      protrail_server.update_new_items()
      # 更新新闻动态画像, 需要在redis数据库内容清空之前执行
      protrail_server.update_dynamic_feature_protrail()
      # 生成前端展示的新闻画像,并在mongodb中备份一份
      protrail_server.update_redis_mongo_protrail_data()

      # 新闻数据写入redis, 注意这里处理redis数据的时候是会将前一天的数据全部清空
      news_redis_server = NewsRedisServer()
      # 将最新的前端展示的画像传到redis
      news_redis_server.news_detail_to_redis()


      if __name__ == "__main__":
      process_material()

      用户侧画像的构建

      对于用户画像的更新来说主要分为两方面:

      新注册用户画像的更新

      老用户画像的更新

      由于我们系统中将所有注册过的用户都放到了一个表里面(新、老用户),所以每次更新画像的话只需要遍历一遍注册表中的所有用户。再说具体的画像构建逻辑之前,得先了解一下用户画像中包含哪些字段,下面是直接从mongo中查出来的

      推荐系统实战——自动化构建用户以及物料画像

       

      从上面可以看出,主要是用户的基本信息和用户历史信息相关的一些标签,对于用户的基本属性特征这个可以直接从注册表中获取,那么对于跟用户历史阅读相关的信息,需要统计用户历史的所有阅读、喜欢和收藏的新闻详细信息。为了得到跟用户历史兴趣相关的信息,我们需要对用户的历史阅读、喜欢和收藏这几个历史记录给存起来,其实这些信息都可以从日志信息中获取得到,但是这里有个工程上的事情得先说明一下,先看下面这个图,对于每个用户点进一篇新闻的详情页

      最底部有个喜欢和收藏,这个前端展示的结果是从后端获取的数据,那就意味着后端需要维护一个用户历史点击及收藏过的文章列表,这里我们使用了mysql来存储,主要是怕redis不够用。其实这两个表不仅仅可以用来前端展示用的,还可以用来分析用户的画像,这都给我们整理好了用户历史喜欢和收藏了。

      此外前面也提到了我们可以使用用户历史阅读的文章做用户画像,为了更好处理和理解,我们也维护了一份用户历史阅读过的所有文章的mysql表(维护表的核心逻辑就是每天跑一边用户日志,更新一下用户历史阅读的记录),那么此时我们其实已经有了用户的阅读、点赞和收藏三个用户行为表了,接下来就直接可以通过这三个表来做具体的用户兴趣相关的画像了,实现的具体逻辑如下:

      import sys
      import datetime
      from collections import Counter, defaultdict

      from sqlalchemy.sql.expression import table
      sys.path.append("../../")
      from dao.mongo_server import MongoServer
      from dao.mysql_server import MysqlServer
      from dao.entity.register_user import RegisterUser
      from dao.entity.user_read import UserRead
      from dao.entity.user_likes import UserLikes
      from dao.entity.user_collections import UserCollections


      class UserProtrail(object):
      def __init__(self):
      self.user_protrail_collection = MongoServer().get_user_protrail_collection()
      self.material_collection = MongoServer().get_feature_protrail_collection()
      self.register_user_sess = MysqlServer().get_register_user_session()
      self.user_collection_sess = MysqlServer().get_user_collection_session()
      self.user_like_sess = MysqlServer().get_user_like_session()
      self.user_read_sess = MysqlServer().get_user_read_session()

      def _user_info_to_dict(self, user):
      """将mysql查询出来的结果转换成字典存储
      """
      info_dict = dict()

      # 基本属性特征
      info_dict["userid"] = user.userid
      info_dict["username"] = user.username
      info_dict["passwd"] = user.passwd
      info_dict["gender"] = user.gender
      info_dict["age"] = user.age
      info_dict["city"] = user.city

      # 兴趣爱好
      behaviors=["like","collection"]
      time_range = 15
      _, feature_dict = self.get_statistical_feature_from_history_behavior(user.userid,time_range,behavior_types=behaviors)
      for type in feature_dict.keys():
      if feature_dict[type]:
      info_dict["{}_{}_intr_cate".format(type,time_range)] = feature_dict[type]["intr_cate"] # 历史喜欢最多的Top3的新闻类别
      info_dict["{}_{}_intr_key_words".format(type,time_range)] = feature_dict[type]["intr_key_words"] # 历史喜欢新闻的Top3的关键词
      info_dict["{}_{}_avg_hot_value".format(type,time_range)] = feature_dict[type]["avg_hot_value"] # 用户喜欢新闻的平均热度
      info_dict["{}_{}_news_num".format(type,time_range)] = feature_dict[type]["news_num"] # 用户15天内喜欢的新闻数量
      else:
      info_dict["{}_{}_intr_cate".format(type,time_range)] = "" # 历史喜欢最多的Top3的新闻类别
      info_dict["{}_{}_intr_key_words".format(type,time_range)] = "" # 历史喜欢新闻的Top3的关键词
      info_dict["{}_{}_avg_hot_value".format(type,time_range)] = 0 # 用户喜欢新闻的平均热度
      info_dict["{}_{}_news_num".format(type,time_range)] = 0 # 用户15天内喜欢的新闻数量

      return info_dict

      def update_user_protrail_from_register_table(self):
      """每天都需要将当天注册的用户添加到用户画像池中
      """
      # 遍历注册用户表
      for user in self.register_user_sess.query(RegisterUser).all():
      user_info_dict = self._user_info_to_dict(user)
      old_user_protrail_dict = self.user_protrail_collection.find_one({"username": user.username})
      if old_user_protrail_dict is None:
      self.user_protrail_collection.insert_one(user_info_dict)
      else:
      # 使用参数upsert设置为true对于没有的会创建一个
      # replace_one 如果遇到相同的_id 就会更新
      self.user_protrail_collection.replace_one(old_user_protrail_dict, user_info_dict, upsert=True)


      def get_statistical_feature_from_history_behavior(self, user_id, time_range, behavior_types):
      """获取用户历史行为的统计特征 ["read","like","collection"] """
      fail_type = []
      sess, table_obj, history = None, None, None
      feature_dict = defaultdict(dict)

      end = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
      start = (datetime.datetime.now()+datetime.timedelta(days=-time_range)).strftime("%Y-%m-%d %H:%M:%S")

      for type in behavior_types:
      if type == "read":
      sess = getattr(self,"user_{}_sess".format(type))
      table_obj = UserRead
      elif type == "like":
      sess = getattr(self,"user_{}_sess".format(type))
      table_obj = UserLikes
      elif type == "collection":
      sess = getattr(self,"user_{}_sess".format(type))
      table_obj = UserCollections
      try:
      history = sess.query(table_obj).filter(table_obj.userid==user_id).filter(table_obj.curtime>=start).filter(table_obj.curtime<=end).all()
      except Exception as e:
      print(str(e))
      fail_type.append(type)
      continue

      feature_dict[type] = self._gen_statistical_feature(history)

      return fail_type, feature_dict

      def _gen_statistical_feature(self,history):
      """"""
      # 为history 获取特征
      if not len(history): return None
      history_new_id = []
      history_hot_value = []
      history_new_cate = []
      history_key_word = []
      for h in history:
      news_id = h.newid
      newsquery = {"news_id":news_id}
      result = self.material_collection.find_one(newsquery)
      history_new_id.append(result["news_id"])
      history_hot_value.append(result["hot_value"])
      history_new_cate.append(result["cate"])
      history_key_word += result["manual_key_words"].split(",")

      feature_dict = dict()
      # 计算平均热度
      feature_dict["avg_hot_value"] = 0 if sum(history_hot_value) < 0.001 else sum(history_hot_value) / len(history_hot_value)

      # 计算Top3的类别
      cate_dict = Counter(history_new_cate)
      cate_list= sorted(cate_dict.items(),key = lambda d: d[1], reverse=True)
      cate_str = ",".join([item[0] for item in cate_list[:3]] if len(cate_list)>=3 else [item[0] for item in cate_list] )
      feature_dict["intr_cate"] = cate_str

      # 计算Top3的关键词
      word_dict = Counter(history_key_word)
      word_list= sorted(word_dict.items(),key = lambda d: d[1], reverse=True)
      # TODO 关键字属于长尾 如果关键字的次数都是一次 该怎么去前3
      word_str = ",".join([item[0] for item in word_list[:3]] if len(cate_list)>=3 else [item[0] for item in word_list] )
      feature_dict["intr_key_words"] = word_str
      # 新闻数目
      feature_dict["news_num"] = len(history_new_id)

      return feature_dict


      if __name__ == "__main__":
      user_protrail = UserProtrail().update_user_protrail_from_register_table()
      from user_process.user_to_mysql import UserMysqlServer
      from user_process.user_protrail import UserProtrail

      """
      1. 将用户的曝光数据从redis落到mysql中。
      2. 更新用户画像
      """

      def process_users():
      """将用户数据落 Mysql
      """
      # 用户mysql存储
      user_mysql_server = UserMysqlServer()
      # 用户曝光数据落mysql
      user_mysql_server.user_exposure_to_mysql()

      # 更新用户画像
      user_protrail = UserProtrail()
      user_protrail.update_user_protrail_from_register_table()


      if __name__ == "__main__":
      process_users()

      画像自动化构建

      上面分别对用户侧和物料侧的画像构建进行了介绍,接下来就是要将上面所有的过程都自动化运行,并且设置好定时任务,其实最核心的一点就是一定要在清除redis数据之前,完成用户和物料画像的构建,下面是构建整个自动化的流程。

      from material_process.news_protrait import NewsProtraitServer
      from material_process.news_to_redis import NewsRedisServer


      def process_material():
      """物料处理函数
      """
      # 画像处理
      protrail_server = NewsProtraitServer()
      # 处理最新爬取新闻的画像,存入特征库
      protrail_server.update_new_items()
      # 更新新闻动态画像, 需要在redis数据库内容清空之前执行
      protrail_server.update_dynamic_feature_protrail()
      # 生成前端展示的新闻画像,并在mongodb中备份一份
      protrail_server.update_redis_mongo_protrail_data()


      if __name__ == "__main__":
      process_material()

      用户画像更新脚本: process_user.py

      from user_process.user_to_mysql import UserMysqlServer
      from user_process.user_protrail import UserProtrail

      """
      1. 将用户的曝光数据从redis落到mysql中。
      2. 更新用户画像
      """


      def process_users():
      """将用户数据落 Mysql
      """
      # 用户mysql存储
      user_mysql_server = UserMysqlServer()
      # 用户曝光数据落mysql
      user_mysql_server.user_exposure_to_mysql()

      # 更新用户画像
      user_protrail = UserProtrail()
      user_protrail.update_user_protrail_from_register_table()


      if __name__ == "__main__":
      process_users()
      redis数据更新脚本:update_redis.py

      from material_process.news_protrait import NewsProtraitServer
      from material_process.news_to_redis import NewsRedisServer


      def update():
      """物料处理函数
      """
      # 新闻数据写入redis, 注意这里处理redis数据的时候是会将前一天的数据全部清空
      news_redis_server = NewsRedisServer()
      # 将最新的前端展示的画像传到redis
      news_redis_server.news_detail_to_redis()


      if __name__ == "__main__":
      update()

      最后将上面三个脚本穿起来的shell脚本offline_material_and_user_process.sh

      #!/bin/bash

      python=/home/recsys/miniconda3/envs/news_rec_py3/bin/python
      news_recsys_path="/home/recsys/news_rec_server"

      echo "$(date -d today +%Y-%m-%d-%H-%M-%S)"

      # 为了更方便的处理路径的问题,可以直接cd到我们想要运行的目录下面
      cd ${news_recsys_path}/materials

      # 更新物料画像
      ${python} process_material.py
      if [ $? -eq 0 ]; then
      echo "process_material success."
      else
      echo "process_material fail."
      fi

      # 更新用户画像
      ${python} process_user.py
      if [ $? -eq 0 ]; then
      echo "process_user.py success."
      else
      echo "process_user.py fail."
      fi

      # 清除前一天redis中的数据,更新最新今天最新的数据
      ${python} update_redis.py
      if [ $? -eq 0 ]; then
      echo "update_redis success."
      else
      echo "update_redis fail."
      fi


      echo " "

      crontab定时任务:

      0 0 * * * /home/recsys/news_rec_server/scheduler/crawl_news.sh >> /home/recsys/news_rec_server/logs/offline_material_process.log && 

      /home/recsys/news_rec_server/scheduler/offline_material_and_user_process.sh >> /home/recsys/news_rec_server/logs/material_and_user_process.log &&

      /home/recsys/news_rec_server/scheduler/run_offline.sh >> /home/recsys/news_rec_server/logs/offline_rec_list_to_redis.log
      版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/u_13859040/5814503,作者:qq5b42bed9cc7e9,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。

      上一篇:虚拟化数据恢复——Hyper-V虚拟机文件丢失导致Hyper-V服务瘫痪,虚拟机无法使用的数据恢复案例

      下一篇:推荐系统从入门到实战—— 推荐系统流程的构建.

      相关文章

      2025-05-06 09:19:12

      redis高可用集群搭建

      redis高可用集群搭建

      2025-05-06 09:19:12
      master , redis , 服务器 , 节点 , 集群
      2025-04-22 09:27:37

      【Redis】浅析 Redis 事务

      【Redis】浅析 Redis 事务

      2025-04-22 09:27:37
      redis , Redis , 事务 , 命令 , 执行
      2025-04-09 09:13:17

      解决tomcat部署项目中碰到的几个问题

      在tomcat上部署项目并进行测试,经常会碰到各种问题。在不同的操作系统上部署,对问题的解决也会有一些差异。

      2025-04-09 09:13:17
      data , redis , tomcat , 信息
      2025-04-09 09:11:38

      redis配置参数详细说明

      redis配置参数详细说明

      2025-04-09 09:11:38
      conf , redis , server , 默认
      2025-03-26 09:31:37

      Redis的发布订阅(消息队列,比如ActiveMQ,一方得到数据后,多方得到信息)

      发布和订阅是进程间的一种消息通信模式:发送者(publisher)将消息发送给一个第三方,订阅者(subscriber)从第三方那里接收消息。

      2025-03-26 09:31:37
      redis
      2025-03-18 08:27:10

      lepus监控redis执行python check_redis.py报错

      lepus监控redis执行python check_redis.py报错

      2025-03-18 08:27:10
      redis
      2025-03-17 07:49:59

      非openresty方式安装Nginx + Lua + Redis 环境

      非openresty方式安装Nginx + Lua + Redis 环境

      2025-03-17 07:49:59
      lua , nginx , Nginx , redis , 模块
      2025-03-17 07:49:59

      redis-cluster分布式集群安装部署

      redis-cluster分布式集群安装部署

      2025-03-17 07:49:59
      redis , Ruby , 安装 , 实例 , 集群
      2025-02-26 07:21:36

      简述Redis事务实现--------->负载均衡算法、类型

      MULTI命令的执行,标识着一个事务的开始。MULTI命令会将客户端状态的flag属性中打开REDIS_MULTI标识来完成的。

      2025-02-26 07:21:36
      redis , Redis , 事务 , 命令 , 客户端 , 服务器 , 节点
      2025-02-11 09:36:37

      【Redis】Redis 集群缓存测试要点--关于 线上 token 失效 BUG 的总结 --研读

      【Redis】Redis 集群缓存测试要点--关于 线上 token 失效 BUG 的总结 --研读

      2025-02-11 09:36:37
      redis , Redis , 分片 , 哈希 , 失效 , 服务器 , 缓存
      查看更多
      推荐标签

      作者介绍

      天翼云小翼
      天翼云用户

      文章

      33561

      阅读量

      5265050

      查看更多

      最新文章

      redis高可用集群搭建

      2025-05-06 09:19:12

      redis配置参数详细说明

      2025-04-09 09:11:38

      redis配置systemctl,并以普通用户运行

      2024-11-26 09:47:29

      【Flask项目2】项目基本架构配置(1)

      2024-11-20 09:45:47

      redis配置文件部分注解

      2024-10-22 06:54:48

      springboot中redis的配置

      2024-09-25 10:15:32

      查看更多

      热门文章

      redis-配置主从-实际操作-over

      2023-03-29 10:07:52

      找寻一款redis数据库可视化工具(RedisDesktopManager)

      2023-02-27 09:14:47

      ShiroConfig完整配置案例

      2022-12-28 07:22:30

      redis-配置说明-重要的几个配置

      2023-03-29 10:07:17

      k8s资源之namespace&replicaset&deployment

      2023-02-16 09:40:38

      Redis主从复制

      2023-05-10 06:05:03

      查看更多

      热门标签

      服务器 linux 虚拟机 Linux 数据库 运维 网络 日志 数据恢复 java python 配置 nginx centos mysql
      查看更多

      相关产品

      弹性云主机

      随时自助获取、弹性伸缩的云服务器资源

      天翼云电脑(公众版)

      便捷、安全、高效的云电脑服务

      对象存储

      高品质、低成本的云上存储服务

      云硬盘

      为云上计算资源提供持久性块存储

      查看更多

      随机文章

      ShiroConfig完整配置案例

      Redis-Cluster-开篇

      Redis主从复制

      一文教会你如何在Linux系统中使用Docker安装Redis 、以及如何使用可视化工具连接【详细过程+图解】

      linux查看服务安装目录server dir

      Redis未授权访问漏洞(三)Redis写入反弹连接定时任务

      • 7*24小时售后
      • 无忧退款
      • 免费备案
      • 专家服务
      售前咨询热线
      400-810-9889转1
      关注天翼云
      • 旗舰店
      • 天翼云APP
      • 天翼云微信公众号
      服务与支持
      • 备案中心
      • 售前咨询
      • 智能客服
      • 自助服务
      • 工单管理
      • 客户公告
      • 涉诈举报
      账户管理
      • 管理中心
      • 订单管理
      • 余额管理
      • 发票管理
      • 充值汇款
      • 续费管理
      快速入口
      • 天翼云旗舰店
      • 文档中心
      • 最新活动
      • 免费试用
      • 信任中心
      • 天翼云学堂
      云网生态
      • 甄选商城
      • 渠道合作
      • 云市场合作
      了解天翼云
      • 关于天翼云
      • 天翼云APP
      • 服务案例
      • 新闻资讯
      • 联系我们
      热门产品
      • 云电脑
      • 弹性云主机
      • 云电脑政企版
      • 天翼云手机
      • 云数据库
      • 对象存储
      • 云硬盘
      • Web应用防火墙
      • 服务器安全卫士
      • CDN加速
      热门推荐
      • 云服务备份
      • 边缘安全加速平台
      • 全站加速
      • 安全加速
      • 云服务器
      • 云主机
      • 智能边缘云
      • 应用编排服务
      • 微服务引擎
      • 共享流量包
      更多推荐
      • web应用防火墙
      • 密钥管理
      • 等保咨询
      • 安全专区
      • 应用运维管理
      • 云日志服务
      • 文档数据库服务
      • 云搜索服务
      • 数据湖探索
      • 数据仓库服务
      友情链接
      • 中国电信集团
      • 189邮箱
      • 天翼企业云盘
      • 天翼云盘
      ©2025 天翼云科技有限公司版权所有 增值电信业务经营许可证A2.B1.B2-20090001
      公司地址:北京市东城区青龙胡同甲1号、3号2幢2层205-32室
      • 用户协议
      • 隐私政策
      • 个人信息保护
      • 法律声明
      备案 京公网安备11010802043424号 京ICP备 2021034386号