电商推荐是最复杂的推荐场景之一,需要处理多类型用户行为(浏览/点击/加购/购买)、丰富的商品特征、实时价格变化、库存限制等。电商推荐直接关联商业指标,是推荐系统最重要的落地方向。
w_view=1, w_click=2, w_cart=3, w_buy=5
score = w₁·quality + w₂·cat_match + w₃·price + w₄·popularity
import numpy as np
from collections import defaultdict
np.random.seed(42)
print("="*60+"\n电商推荐项目\n"+"="*60)
n_users=40;n_products=35;n_categories=5
cats=["数码","服饰","食品","家居","美妆"]
# 商品特征
product_cat=np.random.randint(n_categories,size=n_products)
product_price=np.random.lognormal(3,1,n_products).astype(int)+10
product_brand=np.random.randint(5,size=n_products)
product_quality=np.random.random(n_products)*2+3
print(f"用户:{n_users} 商品:{n_products} 类目:{n_categories}")
# 用户行为序列
user_sequences=defaultdict(list)
user_profiles=np.random.randint(n_categories,size=n_users)
for u in range(n_users):
n_actions=np.random.randint(5,20)
seq=[]
for _ in range(n_actions):
cat=user_profiles[u]
cat_products=np.where(product_cat==cat)[0]
if len(cat_products)==0:cat_products=np.arange(n_products)
action=np.random.choice(cat_products)
action_type=np.random.choice(["浏览","点击","加购","购买"],p=[0.4,0.3,0.2,0.1])
seq.append((action,action_type))
user_sequences[u]=seq
print(f"总行为数:{sum(len(s)for s in user_sequences.values())}")
# 多路召回
print("\n--- 多路召回 ---")
target=0
# 1. 协同过滤召回
co_occurrence=defaultdict(int)
for u,seq in user_sequences.items():
purchased=[a for a,t in seq if t=="购买"]
for i in range(len(purchased)):
for j in range(i+1,len(purchased)):
co_occurrence[(purchased[i],purchased[j])]+=1
co_occurrence[(purchased[j],purchased[i])]+=1
# 基于用户历史购买召回
target_purchased=set(a for a,t in user_sequences[target]if t=="购买")
cf_candidates=set()
for p in target_purchased:
for(q,c)in co_occurrence.items():
if q[0]==p:cf_candidates.add(q[1])
print(f"CF召回:{len(cf_candidates)}个商品")
# 2. 类目召回
target_cat=user_profiles[target]
cat_candidates=set(np.where(product_cat==target_cat)[0])
print(f"类目召回:{len(cat_candidates)}个商品")
# 3. 热门召回
product_popularity=defaultdict(int)
for u,seq in user_sequences.items():
for a,t in seq:
weight={"浏览":1,"点击":2,"加购":3,"购买":5}[t]
product_popularity[a]+=weight
hot_candidates=set([i for i,_ in sorted(product_popularity.items(),key=lambda x:-x[1])[:10]])
print(f"热门召回:{len(hot_candidates)}个商品")
# 合并召回
all_candidates=cf_candidates|cat_candidates|hot_candidates
all_candidates-=target_purchased
print(f"合并召回:{len(all_candidates)}个商品")
# 精排
print("\n--- 精排 ---")
# 特征:商品质量+类目匹配+价格匹配+热度
scores={}
for p in all_candidates:
feat_quality=product_quality[p]/5
feat_cat=1 if product_cat[p]==user_profiles[target] else 0.3
feat_price=1-abs(product_price[p]-np.median(product_price))/np.max(product_price)
feat_pop=product_popularity.get(p,0)/max(product_popularity.values())
scores[p]=0.3*feat_quality+0.25*feat_cat+0.15*feat_price+0.3*feat_pop
ranked=sorted(scores.items(),key=lambda x:-x[1])
print(f"精排Top-10:")
for p,s in ranked[:10]:
print(f" 商品{p}:分数={s:.3f} 类目={cats[product_cat[p]]} 价格={product_price[p]}")
# 重排(类目打散)
print("\n--- 重排(类目打散) ---")
reranked=[];cat_count=defaultdict(int)
for p,s in ranked:
c=product_cat[p]
if cat_count[c]<3: # 每类目最多3个
reranked.append((p,s));cat_count[c]+=1
print(f"重排Top-10:")
for p,s in reranked[:10]:
print(f" 商品{p}:分数={s:.3f} 类目={cats[product_cat[p]]} 价格={product_price[p]}")
# 多样性评估
cat_coverage=len(set(product_cat[p]for p,_ in reranked[:10]))/n_categories
print(f"类目覆盖率:{cat_coverage:.2%}")
✅ 验证通过
本课代码涵盖了从数据生成、模型训练到效果评估的完整流程。以下是关键步骤的详细解读:
代码设计原则:简洁可读、关键步骤有注释、结果可复现(固定随机种子)。
| 组件 | 版本 | 说明 |
|---|---|---|
| Python | 3.8+ | 推荐3.10版本 |
| NumPy | 1.21+ | 核心数值计算库 |
| SciPy | 1.7+ | 统计检验(部分课程) |
本课是第26课:电商推荐项目,属于实战项目阶段。我们系统学习了本课的核心概念、数学原理和代码实现,并通过实机运行验证了算法的正确性。
练习1:实现DIN(Deep Interest Network)处理用户行为序列
练习2:实现多场景推荐(首页/详情页/购物车)
练习3:加入实时价格和促销特征
练习4:实现购买转化率预估模型
| 公司 | 场景 | 核心技术 |
|---|---|---|
| 字节跳动 | 抖音/TikTok | 多目标排序+实时特征+双塔召回 |
| 阿里巴巴 | 淘宝推荐 | DIN/DIEN序列模型+MIND多兴趣 |
| 腾讯 | 微信看一看 | DeepFM+图神经网络召回 |
| 美团 | 本地生活推荐 | 多场景多目标+时空特征 |
| Netflix | 视频推荐 | 矩阵分解+深度学习混合 |
✅ 理解电商推荐的特殊需求
✅ 实现多路召回+精排+重排Pipeline
✅ 处理商品属性和用户行为特征
✅ 评估电商推荐的商业效果