1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
| """ DIEN (深度兴趣演化网络) 排序模型实现,用于 FunRec。
在 funrec 中自包含。构建与统一训练/评估管道兼容的单一排序模型(返回 (model, None, None))。
两个关键层: 1) InterestExtractorLayer: 对行为序列使用 GRU,可选辅助损失 2) InterestEvolutionLayer: 双线性注意力 + AIGRU/AGRU/AUGRU """
import tensorflow as tf from tensorflow.keras import layers
from .utils import ( build_input_layer, build_group_feature_embedding_table_dict, concat_group_embedding, get_linear_logits, add_tensor_func, concat_func, parse_dien_feature_columns as _parse_dien_feature_columns, ) from .layers import DNNs, PredictLayer
class InterestExtractorLayer(tf.keras.layers.Layer): """ DIEN 模型的兴趣提取层。
该层使用带辅助损失的 GRU 从行为序列中提取用户兴趣。 辅助损失通过使用下一个行为来监督当前兴趣状态,帮助 GRU 隐藏状态更好地表示用户兴趣。
参数: hidden_units (int): GRU 中的隐藏单元数 (默认: 128) use_auxiliary_loss (bool): 是否使用辅助损失 (默认: True) auxiliary_loss_weight (float): 辅助损失的权重 (默认: 0.1) dropout_rate (float): 正则化的 dropout 率 (默认: 0.0) """
def __init__( self, hidden_units=128, use_auxiliary_loss=True, auxiliary_loss_weight=0.1, dropout_rate=0.0, **kwargs, ): super(InterestExtractorLayer, self).__init__(**kwargs) self.hidden_units = hidden_units self.use_auxiliary_loss = use_auxiliary_loss self.auxiliary_loss_weight = auxiliary_loss_weight self.dropout_rate = dropout_rate
self.interest_gru = tf.keras.layers.GRU( units=hidden_units, return_sequences=True, return_state=False, name="interest_extractor_gru", )
if self.use_auxiliary_loss: self.auxiliary_mlp = tf.keras.Sequential( [ tf.keras.layers.Dense(64, activation="relu", name="aux_dense_1"), tf.keras.layers.Dropout(dropout_rate), tf.keras.layers.Dense(32, activation="relu", name="aux_dense_2"), tf.keras.layers.Dropout(dropout_rate), tf.keras.layers.Dense(1, activation="sigmoid", name="aux_output"), ], name="auxiliary_mlp", ) else: self.auxiliary_mlp = None
if dropout_rate > 0: self.dropout = tf.keras.layers.Dropout(dropout_rate) else: self.dropout = None
def build(self, input_shape): """构建方法,如果需要则初始化辅助 MLP。""" super(InterestExtractorLayer, self).build(input_shape)
if self.auxiliary_mlp is not None: if isinstance(input_shape, list) and len(input_shape) > 0: embedding_dim = input_shape[0][-1] else: embedding_dim = 8
aux_input_shape = (None, self.hidden_units + embedding_dim) self.auxiliary_mlp.build(aux_input_shape)
def call(self, inputs, training=None, mask=None): """ 兴趣提取层的前向传播。
参数: inputs: 包含 [behavior_embeddings, neg_behavior_embeddings (可选)] 的列表 - behavior_embeddings: 形状为 [batch_size, seq_len, embedding_dim] 的张量 - neg_behavior_embeddings: 形状为 [batch_size, seq_len, embedding_dim] 的张量 (用于辅助损失) training: 训练模式标志 mask: 序列的填充掩码
返回: interest_states: 形状为 [batch_size, seq_len, hidden_units] 的张量 表示每个时间步用户兴趣的隐藏状态 """ behavior_embeddings = inputs[0]
interest_states = self.interest_gru( behavior_embeddings, mask=mask, training=training )
if self.dropout is not None: interest_states = self.dropout(interest_states, training=training)
if ( self.use_auxiliary_loss and training and len(inputs) > 1 and self.auxiliary_mlp is not None ): neg_behavior_embeddings = inputs[ 1 ] aux_loss = self._compute_auxiliary_loss( interest_states, behavior_embeddings, neg_behavior_embeddings, mask ) self.add_loss(self.auxiliary_loss_weight * aux_loss)
return interest_states
def _compute_auxiliary_loss( self, interest_states, pos_behaviors, neg_behaviors, mask ): """ 计算兴趣提取的辅助损失。
辅助损失使用下一个行为来监督当前兴趣状态: - 正样本: 当前兴趣应该预测下一个正行为 - 负样本: 当前兴趣不应该预测下一个负行为
参数: interest_states: 形状为 [batch_size, seq_len, hidden_units] 的张量 pos_behaviors: 形状为 [batch_size, seq_len, embedding_dim] 的张量 neg_behaviors: 形状为 [batch_size, seq_len, embedding_dim] 的张量 mask: 填充掩码
返回: aux_loss: 标量辅助损失 """ current_interests = interest_states[:, :-1, :] next_pos_behaviors = pos_behaviors[:, 1:, :] next_neg_behaviors = neg_behaviors[:, 1:, :]
pos_input = tf.concat([current_interests, next_pos_behaviors], axis=-1) neg_input = tf.concat([current_interests, next_neg_behaviors], axis=-1)
pos_probs = self.auxiliary_mlp(pos_input) neg_probs = self.auxiliary_mlp(neg_input)
pos_loss = -tf.math.log(pos_probs + 1e-8) neg_loss = -tf.math.log( 1 - neg_probs + 1e-8 )
if mask is not None: loss_mask = mask[:, 1:] loss_mask = tf.expand_dims( loss_mask, axis=-1 ) loss_mask = tf.cast(loss_mask, tf.float32)
pos_loss = pos_loss * loss_mask neg_loss = neg_loss * loss_mask
aux_loss = tf.reduce_mean(pos_loss + neg_loss)
return aux_loss
class InterestEvolutionLayer(tf.keras.layers.Layer): """ DIEN 模型的兴趣演化层。
该层使用双线性注意力结合 GRU 变体来建模用户兴趣随时间的演化。支持三种演化类型: 1. AIGRU: 基于注意力的输入 GRU 2. AGRU: 基于注意力的 GRU 3. AUGRU: 基于注意力的更新 GRU(推荐)
注意力机制遵循原始 DIEN 论文使用双线性形式: a_t = exp(h_t * W * e_a) / sum(exp(h_j * W * e_a))
参数: hidden_units (int): 演化 GRU 中的隐藏单元数 (默认: 128) evolution_type (str): 演化机制类型 ('AIGRU', 'AGRU', 'AUGRU') (默认: 'AUGRU') dropout_rate (float): Dropout 率 (默认: 0.0) """
def __init__( self, hidden_units=128, evolution_type="AUGRU", dropout_rate=0.0, **kwargs ): super(InterestEvolutionLayer, self).__init__(**kwargs) self.hidden_units = hidden_units self.evolution_type = evolution_type self.dropout_rate = dropout_rate
if evolution_type not in ["AIGRU", "AGRU", "AUGRU"]: raise ValueError( f"evolution_type 必须是 ['AIGRU', 'AGRU', 'AUGRU'] 之一,得到 {evolution_type}" )
self.bilinear_weight = None
if evolution_type == "AIGRU": self.evolution_gru = tf.keras.layers.GRU( units=hidden_units, return_sequences=False, return_state=False, name="evolution_gru", ) elif evolution_type == "AGRU": self.evolution_gru = self._build_agru() elif evolution_type == "AUGRU": self.evolution_gru = self._build_augru()
if dropout_rate > 0: self.dropout = tf.keras.layers.Dropout(dropout_rate) else: self.dropout = None
def build(self, input_shape): """构建方法,初始化双线性权重矩阵。""" super(InterestEvolutionLayer, self).build(input_shape)
if isinstance(input_shape, list) and len(input_shape) > 1: embedding_dim = ( input_shape[1][-1] if len(input_shape[1]) > 1 else input_shape[1][0] ) else: embedding_dim = 8
self.bilinear_weight = self.add_weight( name="bilinear_attention_weight", shape=(self.hidden_units, embedding_dim), initializer="glorot_uniform", trainable=True, )
def _build_agru(self): """构建自定义 AGRU 单元。""" return AGRULayer(self.hidden_units, name="agru_evolution")
def _build_augru(self): """构建自定义 AUGRU 单元。""" return AUGRULayer(self.hidden_units, name="augru_evolution")
def call(self, inputs, training=None, mask=None): """ 兴趣演化层的前向传播。
参数: inputs: 包含 [interest_states, target_item_embedding] 的列表 - interest_states: 形状为 [batch_size, seq_len, hidden_units] 的张量 - target_item_embedding: 形状为 [batch_size, embedding_dim] 的张量 training: 训练模式标志 mask: 序列的填充掩码
返回: final_interest: 形状为 [batch_size, hidden_units] 的张量 最终演化的兴趣表示 """ interest_states = inputs[0] target_item_embedding = inputs[1]
attention_scores = self._compute_attention_scores( interest_states, target_item_embedding )
if self.evolution_type == "AIGRU": attended_interests = interest_states * attention_scores final_interest = self.evolution_gru( attended_interests, mask=mask, training=training )
elif self.evolution_type in ["AGRU", "AUGRU"]: final_interest = self.evolution_gru( [interest_states, attention_scores], mask=mask, training=training )
if self.dropout is not None: final_interest = self.dropout(final_interest, training=training)
return final_interest
def _compute_attention_scores(self, interest_states, target_item_embedding): """ 使用双线性形式计算兴趣状态与目标物品之间的注意力分数。
遵循原始 DIEN 论文: a_t = exp(h_t * W * e_a) / sum(exp(h_j * W * e_a))
参数: interest_states: 形状为 [batch_size, seq_len, hidden_units] 的张量 target_item_embedding: 形状为 [batch_size, 1, embedding_dim] 或 [batch_size, embedding_dim] 的张量
返回: attention_scores: 形状为 [batch_size, seq_len, 1] 的张量 """ if len(target_item_embedding.shape) == 3: target_item_embedding = tf.squeeze(target_item_embedding, axis=1)
h_W = tf.tensordot(interest_states, self.bilinear_weight, axes=[[2], [0]])
target_expanded = tf.expand_dims(target_item_embedding, axis=1)
attention_scores = tf.reduce_sum( h_W * target_expanded, axis=2 )
attention_scores = tf.nn.softmax(attention_scores, axis=1)
attention_scores = tf.expand_dims(attention_scores, axis=2)
return attention_scores
class AGRULayer(tf.keras.layers.Layer): """ 基于注意力的 GRU 层。
在 AGRU 中,注意力分数直接替换更新门值。 这是一种简化的方法,但可能会失去一些表示能力。
参数: units (int): 隐藏单元数 """
def __init__(self, units, **kwargs): super(AGRULayer, self).__init__(**kwargs) self.units = units
self.dense_input_reset = tf.keras.layers.Dense(units, name="input_reset") self.dense_hidden_reset = tf.keras.layers.Dense(units, name="hidden_reset") self.dense_input_candidate = tf.keras.layers.Dense( units, name="input_candidate" ) self.dense_hidden_candidate = tf.keras.layers.Dense( units, name="hidden_candidate" )
def call(self, inputs, mask=None, training=None): """ AGRU 的前向传播。
参数: inputs: [interest_states, attention_scores] 的列表 - interest_states: 形状为 [batch_size, seq_len, units] 的张量 - attention_scores: 形状为 [batch_size, seq_len, 1] 的张量 mask: 填充掩码 training: 训练模式标志
返回: final_state: 形状为 [batch_size, units] 的张量 """ interest_states, attention_scores = inputs batch_size = tf.shape(interest_states)[0] seq_len = tf.shape(interest_states)[1]
hidden_state = tf.zeros([batch_size, self.units])
for t in range(seq_len): current_input = interest_states[:, t, :] current_attention = attention_scores[:, t, 0]
reset_gate = tf.nn.sigmoid( self.dense_input_reset(current_input) + self.dense_hidden_reset(hidden_state) )
candidate_state = tf.nn.tanh( self.dense_input_candidate(current_input) + self.dense_hidden_candidate(reset_gate * hidden_state) )
update_gate = tf.expand_dims(current_attention, axis=1) update_gate = tf.tile(update_gate, [1, self.units])
hidden_state = ( 1 - update_gate ) * hidden_state + update_gate * candidate_state
return hidden_state
class AUGRULayer(tf.keras.layers.Layer): """ 基于注意力的更新 GRU 层。
AUGRU 保持更新门的多维性质,同时通过注意力分数对其进行缩放。 这是 DIEN 中推荐的方法。
参数: units (int): 隐藏单元数 """
def __init__(self, units, **kwargs): super(AUGRULayer, self).__init__(**kwargs) self.units = units
self.dense_input_update = tf.keras.layers.Dense(units, name="input_update") self.dense_hidden_update = tf.keras.layers.Dense(units, name="hidden_update") self.dense_input_reset = tf.keras.layers.Dense(units, name="input_reset") self.dense_hidden_reset = tf.keras.layers.Dense(units, name="hidden_reset") self.dense_input_candidate = tf.keras.layers.Dense( units, name="input_candidate" ) self.dense_hidden_candidate = tf.keras.layers.Dense( units, name="hidden_candidate" )
def call(self, inputs, mask=None, training=None): """ AUGRU 的前向传播。
参数: inputs: [interest_states, attention_scores] 的列表 - interest_states: 形状为 [batch_size, seq_len, units] 的张量 - attention_scores: 形状为 [batch_size, seq_len, 1] 的张量 mask: 填充掩码 training: 训练模式标志
返回: final_state: 形状为 [batch_size, units] 的张量 """ interest_states, attention_scores = inputs batch_size = tf.shape(interest_states)[0] seq_len = tf.shape(interest_states)[1]
hidden_state = tf.zeros([batch_size, self.units])
for t in range(seq_len): current_input = interest_states[:, t, :] current_attention = attention_scores[:, t, 0]
update_gate = tf.nn.sigmoid( self.dense_input_update(current_input) + self.dense_hidden_update(hidden_state) )
reset_gate = tf.nn.sigmoid( self.dense_input_reset(current_input) + self.dense_hidden_reset(hidden_state) )
candidate_state = tf.nn.tanh( self.dense_input_candidate(current_input) + self.dense_hidden_candidate(reset_gate * hidden_state) )
attention_expanded = tf.expand_dims(current_attention, axis=1) attention_expanded = tf.tile(attention_expanded, [1, self.units]) attention_update_gate = attention_expanded * update_gate
hidden_state = ( 1 - attention_update_gate ) * hidden_state + attention_update_gate * candidate_state
return hidden_state
def build_dien_model(feature_columns, model_config): """ 构建 DIEN (深度兴趣演化网络) 模型。
DIEN 通过两个关键组件捕获用户兴趣演化: 1. 兴趣提取层: 从行为序列中提取兴趣 2. 兴趣演化层: 使用双线性注意力建模兴趣随时间的演化
参数: feature_columns: 特征列规范列表 dnn_units: 最终 DNN 层的隐藏单元列表 (默认: [256, 128, 64, 1]) interest_hidden_units: 兴趣提取的隐藏单元 (默认: 128) evolution_type: 演化机制类型 ('AIGRU', 'AGRU', 'AUGRU') (默认: 'AUGRU') use_auxiliary_loss: 是否使用辅助损失 (默认: True) auxiliary_loss_weight: 辅助损失的权重 (默认: 0.1) dropout_rate: 正则化的 dropout 率 (默认: 0.0) linear_logits: 是否包含线性 logits (默认: True)
返回: (model, None, None): 统一接口的排序模型元组 """ dnn_units = model_config.get("dnn_units", [200, 80, 1]) interest_hidden_units = model_config.get("interest_hidden_units", 64) evolution_type = model_config.get("evolution_type", "AUGRU") use_auxiliary_loss = model_config.get("use_auxiliary_loss", True) auxiliary_loss_weight = model_config.get("auxiliary_loss_weight", 0.1) dropout_rate = model_config.get("dropout_rate", 0.1) use_linear_logits = model_config.get("linear_logits", True) input_layer_dict = build_input_layer(feature_columns)
group_embedding_feature_dict = build_group_feature_embedding_table_dict( feature_columns, input_layer_dict, prefix="embedding/" )
dnn_inputs = concat_group_embedding(group_embedding_feature_dict, "dnn")
dien_feature_list = _parse_dien_feature_columns(feature_columns)
if len(dien_feature_list) == 0: raise ValueError( "未找到 DIEN 序列特征。请在 combiner 中添加包含 'dien' 的序列特征。" )
dien_outputs = [] for target_feature, sequence_feature in dien_feature_list: target_embedding = group_embedding_feature_dict["dien_sequence"][target_feature]
behavior_embeddings = group_embedding_feature_dict["dien_sequence"][ sequence_feature ]
if use_auxiliary_loss: neg_behavior_embeddings = tf.random.shuffle(behavior_embeddings) interest_extractor_inputs = [behavior_embeddings, neg_behavior_embeddings] else: interest_extractor_inputs = [behavior_embeddings]
interest_extractor = InterestExtractorLayer( hidden_units=interest_hidden_units, use_auxiliary_loss=use_auxiliary_loss, auxiliary_loss_weight=auxiliary_loss_weight, dropout_rate=dropout_rate, name=f"{sequence_feature}_interest_extractor", ) interest_states = interest_extractor(interest_extractor_inputs)
interest_evolution = InterestEvolutionLayer( hidden_units=interest_hidden_units, evolution_type=evolution_type, dropout_rate=dropout_rate, name=f"{sequence_feature}_interest_evolution", ) evolved_interest = interest_evolution([interest_states, target_embedding])
dien_outputs.append(evolved_interest)
if len(dien_outputs) > 1: dien_output = concat_func(dien_outputs, axis=1, flatten=True) else: dien_output = dien_outputs[0]
final_dnn_inputs = concat_func([dnn_inputs, dien_output], axis=-1)
dnn_logits = DNNs(dnn_units, use_bn=True, dropout_rate=dropout_rate)( final_dnn_inputs )
if use_linear_logits: linear_logit = get_linear_logits(input_layer_dict, feature_columns) dnn_logits = add_tensor_func( [dnn_logits, linear_logit], name="dien_linear_logits" )
final_logits = tf.keras.layers.Flatten()(dnn_logits) output = tf.keras.layers.Dense(1, activation="sigmoid", name="dien_output")( final_logits ) output = tf.keras.layers.Flatten()(output)
model = tf.keras.models.Model( inputs=list(input_layer_dict.values()), outputs=output )
return model, None, None
|