阿里巴巴的 Deep Interest Network (DIN) 是一种用于点击率预测(CTR)的深度学习模型,特别针对电商场景中用户兴趣多样化和动态变化的特性设计。其核心思想是通过 注意力机制 动态捕捉用户历史行为中与当前候选商品相关的兴趣。
1.DIN 模型原理
1. 核心问题
传统推荐模型(如Embedding + MLP)将用户历史行为视为固定长度的向量,忽略了用户兴趣的多样性。例如,用户历史行为中可能包含多个互不相关的兴趣点,而只有部分兴趣与当前候选商品相关。
2. 注意力机制
DIN 引入 局部激活单元(Local Activation Unit),通过计算候选商品与用户历史行为中每个商品的相似性,动态分配权重,聚焦于相关行为:
输入:候选商品嵌入(Candidate Item Embedding) + 用户历史行为商品嵌入(Historical Item Embedding)。
计算权重:通过一个小型神经网络(通常是全连接层)生成注意力分数。
加权求和:根据注意力分数对历史行为嵌入加权求和,生成用户兴趣表示。
3. 模型结构
Embedding Layer:将稀疏特征(如商品ID、用户ID)转换为稠密向量。
Activation Unit:计算候选商品与历史行为商品的注意力权重。
Weighted Sum Pooling:根据注意力权重聚合用户行为序列。
Concatenate Features:拼接用户兴趣表示、候选商品特征、上下文特征等。
MLP:多层感知机输出预测概率。
2.Python 代码实现(基于 TensorFlow/Keras)
以下是一个简化的 DIN 实现示例:
1. 数据预处理
假设输入数据包含:
用户历史行为序列(
hist_item_ids
,如 [item1, item2, ...])候选商品ID(
target_item_id
)用户画像特征(如性别、年龄)
上下文特征(如时间、位置)
2. 模型代码(python)
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
def build_din_model(num_items, embedding_dim=64, hidden_units=[128, 64]):
# 输入定义
target_item = Input(shape=(1,), name='target_item') # 候选商品
hist_items = Input(shape=(None,), name='hist_items') # 用户历史行为序列(变长)
user_features = Input(shape=(2,), name='user_features') # 用户特征(如性别、年龄)
# Embedding Layer
item_embedding = Embedding(num_items, embedding_dim, mask_zero=True) # 商品嵌入层
target_embed = Flatten()(item_embedding(target_item)) # 候选商品嵌入
hist_embed = item_embedding(hist_items) # 历史行为序列嵌入
# 注意力机制(Local Activation Unit)
attention_input = tf.concat([
tf.tile(tf.expand_dims(target_embed, 1), [1, tf.shape(hist_embed)[1], 1]),
hist_embed
], axis=-1) # 拼接候选商品与历史商品嵌入
# 注意力得分计算(小型全连接网络)
attention_score = Dense(1, activation='sigmoid')(attention_input)
attention_score = tf.squeeze(attention_score, axis=-1) # 形状: (batch_size, seq_len)
# 加权求和(考虑变长序列的mask)
mask = tf.cast(tf.not_equal(hist_items, 0), dtype=tf.float32) # 生成mask
attention_score *= mask # 应用mask
attention_score = tf.nn.softmax(attention_score, axis=1)
user_interest = tf.reduce_sum(hist_embed * tf.expand_dims(attention_score, -1), axis=1)
# 拼接所有特征
concat_features = tf.concat([
user_interest,
target_embed,
user_features
], axis=1)
# MLP 层
x = concat_features
for units in hidden_units:
x = Dense(units, activation='relu')(x)
output = Dense(1, activation='sigmoid')(x)
# 构建模型
model = Model(inputs=[target_item, hist_items, user_features], outputs=output)
return model
# 示例模型初始化
num_items = 10000 # 商品总数
model = build_din_model(num_items)
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['AUC'])
model.summary()
3. 关键点说明
注意力机制:通过
Dense(1)
计算注意力分数,sigmoid
激活函数输出权重。变长序列处理:使用
mask_zero=True
在 Embedding 层处理填充的0值。特征拼接:用户兴趣表示(加权和)、候选商品特征、用户特征共同输入 MLP。
3.DIN 的改进与变体
DIEN (Deep Interest Evolution Network):引入序列模型(如GRU)建模用户兴趣的演化过程。
DSIN (Deep Session Interest Network):考虑用户会话(Session)划分,捕捉会话内兴趣。
4.应用场景
电商推荐(如淘宝猜你喜欢)
广告点击率预测
个性化排序