推荐系统(六):基于DeepFM的推荐算法

一、基本原理

除了Deep~\&~Wide模型,DeepFM也是被广泛应用在点击率预测中的深度学习模型,主要关注如何学习用户行为(user behavior)的组合特征(feature interactions),从而最大化推荐系统CTR。
DeepFM是一个集成了FM(factorization machine)和DNN的神经网络框架,分别承担widedeep的部分。DeepFM的widedeep部分共享相同的输入,可以提高训练效率,不需要额外的特征工程,用FM建模低阶的特征组合,用DNN建模高阶的特征组合,因此可以同时从原始特征中学习到高阶和低阶的特征交互。
\hat{y}=\operatorname{sigmoid}\left(y_{F M}+y_{D N N}\right)

DeepFM模型结构(左边为FM层,右边为DNN层)

1.1 FM 结构

FM 包括一阶项和二阶项,一阶项主要是讲特征分别乘上对应的系数,二阶项主要是对x_ix_j两两组合,并且找到其分别对应的特征向量。
y_{F M}=\langle w, x\rangle+\sum_{i=1}^{d} \sum_{j=i+1}^{d}\left\langle v_{i},v_{j}\right\rangle x_{i} \cdot x_{j}

FM模型结构

为了更方便实现二阶部分,可以转化为和平方平方和两个部分:
\begin{aligned} & \sum_{i=1}^{n-1} \sum_{j=i+1}^{n}\left\langle\mathbf{v}_{i}, \mathbf{v}_{j}\right\rangle x_{i} x_{j} \\ =& \frac{1}{2} \sum_{i=1}^{n} \sum_{j=i+1}^{n}\left\langle\mathbf{v}_{i}, \mathbf{v}_{j}\right\rangle x_{i} x_{j}-\frac{1}{2} \sum_{i=1}^{n}\left\langle\mathbf{v}_{i}, \mathbf{v}_{i}\right\rangle x_{i} x_{i} \\ =& \frac{1}{2}\left(\sum_{i=1}^{n} \sum_{j=1}^{n} \sum_{f=1}^{k} {v}_{i, f} v_{j, f} x_{i} x_{j}-\sum_{i=1}^{n} \sum_{f=1}^{k} v_{i, f} v_{i, f} x_{i} x_{i}\right) \\ =& \frac{1}{2} \sum_{f=1}^{k}\left(\left(\sum_{i=1}^{n} v_{i, f} x_{i}\right)\left(\sum_{j=1}^{n} v_{j, f} x_{j}\right)-\sum_{i=1}^{n} v_{i, f}^{2} x_{i}^{2}\right) \\ =& \frac{1}{2} \sum_{f=1}^{k}\left(\left(\sum_{i=1}^{n} v_{i, f} x_{i}\right)^{2}-\sum_{i=1}^{n} v_{i, f}^{2} x_{i}^{2}\right) \end{aligned}

1.2 DNN 结构

深度部分是一个前馈神经网络,CTR预估的原始特征输入向量具有高稀疏、超高维度,分类、连续数据混合,特征按照field分组等特征,因此在第一层隐含层之前,引入一个嵌入层来完成将输入向量压缩到低维稠密向量。

DNN 结构

嵌入层(embedding layer)的结构如下图所示。当前网络结构有两个有趣的特性,1)尽管不同field的输入长度不同,但是embedding之后向量的长度均为K。2)在FM里得到的隐变量v_{i,k}现在作为了嵌入层网络的权重。

嵌入层结构

二、算法实践

仍然采用Porto Seguro’s Safe Driver Prediction 的数据,数据的介绍可见上期:推荐系统(五):基于深度学习的推荐模型。数据的加载与处理如上期相同,即:

TRAIN_FILE = "Driver_Prediction_Data/train.csv"
TEST_FILE = "Driver_Prediction_Data/test.csv"

NUMERIC_COLS = [
    "ps_reg_01", "ps_reg_02", "ps_reg_03",
    "ps_car_12", "ps_car_13", "ps_car_14", "ps_car_15"
]

IGNORE_COLS = [
    "id", "target",
    "ps_calc_01", "ps_calc_02", "ps_calc_03", "ps_calc_04",
    "ps_calc_05", "ps_calc_06", "ps_calc_07", "ps_calc_08",
    "ps_calc_09", "ps_calc_10", "ps_calc_11", "ps_calc_12",
    "ps_calc_13", "ps_calc_14",
    "ps_calc_15_bin", "ps_calc_16_bin", "ps_calc_17_bin",
    "ps_calc_18_bin", "ps_calc_19_bin", "ps_calc_20_bin"
]

train_data = pd.read_csv(TRAIN_FILE)
test_data = pd.read_csv(TEST_FILE)
data = pd.concat([train_data,test_data])

feature_dict = {}
total_feature = 0
for col in data.columns:
    if col in IGNORE_COLS:
        continue
    elif col in NUMERIC_COLS:
        feature_dict[col] = total_feature
        total_feature += 1
    else:
        unique_val = data[col].unique()
        feature_dict[col] = dict(zip(unique_val,range(total_feature,len(unique_val)+total_feature)))
        total_feature += len(unique_val)
        
# convert train dataset
train_y = train_data[['target']].values.tolist()
train_data.drop(['target','id'],axis=1, inplace=True)
train_feature_index = train_data.copy()
train_feature_value = train_data.copy()

for col in train_feature_index.columns:
    if col in IGNORE_COLS:
        train_feature_index.drop(col,axis=1, inplace=True)
        train_feature_value.drop(col,axis=1, inplace=True)
        continue
    elif col in NUMERIC_COLS:
        train_feature_index[col] = feature_dict[col]
    else:
        train_feature_index[col] = train_feature_index[col].map(feature_dict[col])
        train_feature_value[col] = 1
        
field_size = train_feature_value.shape[1] 

包的调用与上期完全一致,类的定义也基本一致,略有差别的是增加了self.use_fm,self.use_deep两个变量。

class DeepFM(BaseEstimator,TransformerMixin):
    def __init__(self, feature_size=100, embedding_size=8, deep_layers=[32,32],batch_size=256,
                 learning_rate=0.001,optimizer='adam',random_seed=2020,used_fm=True,
                 use_deep=True,loss_type='logloss',l2_reg=0.0, field_size=39):
        self.feature_size = feature_size
        self.field_size = field_size
        self.embedding_size = embedding_size
        
        self.deep_layers = deep_layers
        self.deep_layers_activation = tf.nn.relu
        self.use_fm = used_fm
        self.use_deep = use_deep
        self.l2_reg = l2_reg
        
        self.batch_size = batch_size
        self.learning_rate = learning_rate
        self.optimizer_type = optimizer
        
        self.random_seed = random_seed
        self.loss_type = loss_type
        self.train_result, self.valid_result = [], []
        self.max_iteration = 200
        
        self._init_graph()

初始化权值,包括嵌入层、深度层、连接层。

    def _initialize_weights(self):
        weights = dict()
        
        # embeddings layer
        weights['feature_embeddings'] = tf.Variable(tf.random_normal([self.feature_size,self.embedding_size],0.0,0.01), name='feature_embeddings')
        weights['feature_bias'] = tf.Variable(tf.random_normal([self.feature_size,1],0.0,1.0),name='feature_bias')
        
        # deep layers
        input_size = self.field_size * self.embedding_size
        glorot = np.sqrt(2.0/(input_size + self.deep_layers[0]))
        weights['layer_0'] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(input_size, self.deep_layers[0])),dtype=np.float32)
        weights['bias_0'] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(1,self.deep_layers[0])),dtype=np.float32)
        
        glorot = np.sqrt(2.0 / (self.deep_layers[0]+self.deep_layers[1]))
        weights['layer_1'] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(self.deep_layers[0], self.deep_layers[1])), dtype=np.float32)
        weights['bias_1'] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(1, self.deep_layers[1])),dtype=np.float32)
        
        # final concat projection layer
        if self.use_fm and self.use_deep:
            input_size = self.field_size + self.embedding_size + self.deep_layers[1]
        elif self.use_fm:
            input_size = self.field_size + self.embedding_size
        elif self.use_deep:
            input_size = self.deep_layers[1]
        
        glorot = np.sqrt(2.0 / (input_size+1))
        weights['concat_projection'] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(input_size, 1)),dtype=np.float32)
        weights['concat_bias'] = tf.Variable(tf.constant(0.01), dtype=np.float32)
        
        return weights

初始化图,其结构如理论部分所示,其中FM部分结构分为一阶和二阶部分,并分别计算。

    def _init_graph(self):
        self.graph = tf.Graph()
        with self.graph.as_default():
            tf.set_random_seed(self.random_seed)
            
            self.feat_index = tf.placeholder(tf.int32, shape=[None,None], name='feat_index')
            self.feat_value = tf.placeholder(tf.float32, shape=[None,None], name='feat_value')
            
            self.label = tf.placeholder(tf.float32, shape=[None,1], name='label')
            self.dropout_keep_deep = tf.placeholder(tf.float32, shape=[None], name='dropout_keep_deep')
            self.train_phase = tf.placeholder(tf.bool, name='train_phase')
            
            self.weights = self._initialize_weights()
            
            # model 
            self.embeddings = tf.nn.embedding_lookup(self.weights['feature_embeddings'], self.feat_index)  
            feat_value = tf.reshape(self.feat_value, shape=[-1, self.field_size, 1])
            self.embeddings = tf.multiply(self.embeddings, feat_value)
            
            # first order term
            self.y_first_order = tf.nn.embedding_lookup(self.weights['feature_bias'], self.feat_index)
            self.y_first_order = tf.reduce_sum(tf.multiply(self.y_first_order, feat_value), 2)
            
            # second order term   (sum-square-part)
            self.summed_features_emb = tf.reduce_sum(self.embeddings,1)  # None * K
            self.summed_features_emb_square = tf.square(self.summed_features_emb)  # None * K
            
            # squre-sum-part
            self.squared_features_emb = tf.square(self.embeddings)
            self.squared_sum_features_emb = tf.reduce_sum(self.squared_features_emb, 1) # None * K
            
            # second order
            self.y_second_order = 0.5 * tf.subtract(self.summed_features_emb_square, self.squared_sum_features_emb)
            
            # deep component
            self.y_deep = tf.reshape(self.embeddings, shape=[-1, self.field_size * self.embedding_size])
            self.y_deep = tf.add(tf.matmul(self.y_deep, self.weights['layer_0']), self.weights['bias_0'])
            self.y_deep = self.deep_layers_activation(self.y_deep)
            
            self.y_deep = tf.add(tf.matmul(self.y_deep, self.weights['layer_1']),self.weights['bias_1'])
            self.y_deep = self.deep_layers_activation(self.y_deep)
                 
            # -----DeepFM-----
            self.concat_input = tf.concat([self.y_first_order, self.y_second_order, self.y_deep], axis=1)
            self.out = tf.add(tf.matmul(self.concat_input, self.weights['concat_projection']), self.weights['concat_bias'])

本文提供了多种损失函数和优化方法可供选择,同时也对模型进行了保存和记录。

            # loss
            if self.loss_type == 'logloss':
                self.out = tf.nn.sigmoid(self.out)
                self.loss = tf.losses.log_loss(self.label, self.out)
            elif self.loss_type == 'mse':
                self.loss = tf.nn.l2_loss(tf.subtract(self.label, self.out))
                
            # l2 regularization on weights
            if self.l2_reg > 0:
                self.loss += tf.contrib.layers.l2_regularizer(self.l2_reg)(self.weights['concat_projection'])
                if self.use_deep:
                    self.loss += tf.contrib.layers.l2_regularizer(self.l2_reg)(self.weights['layer_0'])
                    self.loss += tf.contrib.layers.l2_regularizer(self.l2_reg)(self.weights['layer_1'])
                    
            # optimize
            if self.optimizer_type == 'adam':
                self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-8).minimize(self.loss)
            elif self.optimizer_type == 'adagrad':
                self.optimizer = tf.train.AdagradDAOptimizer(learning_rate=self.learning_rate, initial_accumulator_value=1e-8).minimize(self.loss)
            elif self.optimizer_type == 'gd':
                self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(self.loss)
            elif self.optimizer_type == 'momentum':
                self.optimizer = tf.train.MomentumOptimizer(learning_rate=self.learning_rate, momentum=0.95).minimize(self.loss)
        
            # init
            self.saver = tf.train.Saver()
            save_path = "deepfm/model.ckpt"
            
            init = tf.global_variables_initializer()
            self.sess = tf.Session()
            self.sess.run(init)
            
            save_path = self.saver.save(self.sess, save_path, global_step=1)
            
            writer = tf.summary.FileWriter("D:/logs/deepfm/", tf.get_default_graph())
            writer.close()        

根据保存的网络结构,可通过tensorboard查看网络结构,如下所示:


定义训练函数,及实例化类并完成训练。

    def train(self, train_feature_index, train_feature_value, train_y):
        with tf.Session(graph=self.graph) as sess:
            sess.run(tf.global_variables_initializer())
            for i in range(self.max_iteration):
                epoch_loss, _ = sess.run([self.loss, self.optimizer],feed_dict={self.feat_index:train_feature_index,
                                                                                self.feat_value:train_feature_value,
                                                                                self.label:train_y})
                print('epoch %s, loss is %s' % (str(i), str(epoch_loss)))

deepfm = DeepFM(feature_size=total_feature, field_size=field_size, embedding_size=8)  
deepfm.train(train_feature_index, train_feature_value, train_y) 

结果如下所示:

epoch 0, loss is 1.2481447
epoch 1, loss is 1.2091292
epoch 2, loss is 1.1717732
epoch 3, loss is 1.1359197
epoch 4, loss is 1.1009481
epoch 5, loss is 1.0666977
···
epoch 195, loss is 0.15519407
epoch 196, loss is 0.15500054
epoch 197, loss is 0.15480281
epoch 198, loss is 0.15460847
epoch 199, loss is 0.15441668

参考资料

[1]. Guo, Huifeng, Tang, Ruiming, Ye, Yunming, Li, Zhenguo, & He, Xiuqiang. . Deepfm: a factorization-machine based neural network for ctr prediction.
[2]. 推荐系统与深度学习. 黄昕等. 清华大学出版社. 2019.
[3]. https://github.com/wangby511/Recommendation_System

春天,遂想起江南,
唐诗里的江南,九岁时
采桑叶于其中,捉蜻蜓于其中
——余光中《春天,遂想起》

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容