推荐算法里我们经常会对特征做交叉操作,如wide&deep算法的wide侧,同时用户的行为序列特征又是非常重要的特征,将用户的行为序列与候选集id交叉往往会带来不错的效果。这里我们主要用tensorflow的cross_hashed函数实现。
下面是假设序列特征定长有padding,最后需要mask操作的情况:
import tensorflow as tf
ids = tf.constant([[1, 2, 3, 0, 0, 0], [2, 4, 7, 3, 1, 0], [1, 2, 3, 4, 5, 6], [0, 0, 0, 0, 0, 0]]) # 定长序列特征,0是填充
item = tf.constant([[3], [5], [1], [5]]) # 物料id
max_length = 6 # 序列最大长度
key_length = tf.constant([[3], [5], [6], [0]]) # 序列有效长度
keys_mask = tf.sequence_mask(key_length, max_length) # 根据序列有效长度制作mask
mask_factor = tf.reshape(tf.cast(keys_mask, tf.float32), [-1, max_length, 1])
y = tf.sparse.cross_hashed([ids, item], num_buckets=10, hash_key=None, name='test') # 这里我们将交叉后的新id取10的模,方便实现,实际越大越好
yy = tf.reshape(y.values, [-1, max_length]) # 因为是定长的且后面要做mask,所以取sparse的values部分
emb = tf.compat.v1.get_variable(name="test",
shape=[10, 16],
dtype=tf.float32,
initializer=tf.compat.v1.truncated_normal_initializer(0.02)) # 假设交叉后embedding维度为16
y_emb = tf.nn.embedding_lookup_sparse(emb, yy)
out = y_emb*mask_factor
out2 = tf.reduce_sum(out, axis=1)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
res =sess.run(out2)
print(res)
不定长没有mask的情况属于sparse类型,只要将tf.nn.embedding_lookup改成tf.nn.embedding_lookup_sparse且去掉mask部分即可。
实际业务中这种粗暴的交叉方式(笛卡尔积后做embedding)会很快的OOM,并不推荐使用,或者可以结合特征淘汰机制使用。



