推荐系统(五):基于深度学习的推荐模型

一、逻辑与模型

随着深度学习的发展,其研究已深入拓展到推荐系统领域,其作用主要体现在以下几个方面:
(1)能够直接从内容中提取特征,表征能力强;
(2)容易对噪声数据进行处理,抗噪能力强;
(3)可以使用循环神经网络对动态或者序列数据进行建模;
(4)可以更加准确地学习和的特征。

深度学习在推荐系统中的算法及其关系

推荐系统和类似的通用搜索排序问题共有的一大挑战为同时具备记忆能力泛化能力。记忆能力即学习那些经常同时出现的特征,发掘历史数据中的共现性;泛化能力则基于迁移相关性,探索之前未出现的新特征组合。
对工业界大规模线上推荐和排序系统中,广义线性模型得到了广泛应用,这类模型简单、可拓展、可解释,一般在二值稀疏特征上训练,这些特征一般采用独热编码。另一方面基于嵌入的模型(factorization machine,DNN等)对以前没有出现过的特征也具备泛化能力,通过为每个查询和条目特征学习一个低维稠密的嵌入向量,以减轻特征工程负担。
由此通过联合训练一个线性模型组件和一个深度神经网络组件得到模型,这样可以同时获得记忆能力和泛化能力。

Wide & Deep 模型

二、结构与框架

一般来说,整个推荐系统分为召回(matching)和排序(ranking)两个阶段。


推荐系统的召回和排序两个阶段

第一部分:召回阶段

将推荐问题建模为“超大规模多分类”问题,即在时刻,为用户(上下文信息)在视频库中准确预测出视频的类别,即:

深度神经网络就是在拟合函数。在这种超大规模分类问题上,至少几百万个类别,实际训练采用的是负采样,或者方法。
整个模型包含三个隐层得DNN结构,输入是用户浏览历史、搜索历史、人口统计学信息及其余上下文信息合并而成的输入向量;输出分线上和线下两个部分,离线训练阶段输出层为层,线上则直接利用向量查询相关产品。

召回模型结构

第二部分:排序阶段

排序阶段最重要任务是精确地预估用户对视频的喜好程度,面对的是百级别的数据集,因此可以更精细地刻画用户与视频的关系。

排序模型结构

排序阶段的模型和召回基本相似,不同的是模型最后一层是一个层,而线上服务阶段激励函数用的是。
神经网络对输入特征的尺度和分布都是十分敏感的,归一化方法对收敛很关键,考虑一种排序分位归一到区间的方法,即,累积分位点。除此之外还把归一后的的平方根和平方作为网络输入,以期能够更容易得到特征的次线性和超线性函数。
模型的目标是预测期望观看时长。有点击的为正样本,其权重为观看时长,无点击的为负样本,权重为1,的期望为:

其中为总的样本数目,为正样本数量,是第个正样本的观看时长,由于相对比较小,因此期望可以转化为,其中是点击率。
接下来几节将介绍几种方法具体实现的过程。

三、Wide and Deep实践

3.1 数据集准备

本文采用2017年Kaggle比赛中Porto Seguro’s Safe Driver Prediction的部分数据,举办者是巴西最大的汽车与住房保险公司之一:Porto Seguro。该比赛要求参赛者根据汽车保单持有人的数据建立机器学习模型,分析该持有人是否会在次年提出索赔。比赛所提供的数据均已进行处理,由于数据特征没有实际意义,因此无法根据常识或业界知识简单地进行特征工程。
在本例中训练集规模为,测试集规模为,这是由于测试集中不包含需要预测的目标变量。列变量的名称如下所示:

Index(['id', 'target', 'ps_ind_01', 'ps_ind_02_cat', 'ps_ind_03',
       'ps_ind_04_cat', 'ps_ind_05_cat', 'ps_ind_06_bin', 'ps_ind_07_bin',
       'ps_ind_08_bin', 'ps_ind_09_bin', 'ps_ind_10_bin', 'ps_ind_11_bin',
       'ps_ind_12_bin', 'ps_ind_13_bin', 'ps_ind_14', 'ps_ind_15',
       'ps_ind_16_bin', 'ps_ind_17_bin', 'ps_ind_18_bin', 'ps_reg_01',
       'ps_reg_02', 'ps_reg_03', 'ps_car_01_cat', 'ps_car_02_cat',
       'ps_car_03_cat', 'ps_car_04_cat', 'ps_car_05_cat', 'ps_car_06_cat',
       'ps_car_07_cat', 'ps_car_08_cat', 'ps_car_09_cat', 'ps_car_10_cat',
       'ps_car_11_cat', 'ps_car_11', 'ps_car_12', 'ps_car_13', 'ps_car_14',
       'ps_car_15', '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'],
      dtype='object')

原文对其描述如下:

In the train and test data, features that belong to similar groupings are tagged as such in the feature names (e.g., ind, reg, car, calc). In addition, feature names include the postfix bin to indicate binary features and cat to indicate categorical features. Features without these designations are either continuous or ordinal. Values of -1 indicate that the feature was missing from the observation. The target columns signifies whether or not a claim was filed for that policy holder.

由于数据中存在一些缺失项,且以表示,可通过缺失值可视化包missingno加以表示,更多关于原始数据的分析处理参见[4]。

import missingno as msno

train = pd.read_csv(TRAIN_FILE,na_values = -1)
col_missing = train.isnull().any()[train.isnull().any()].index
msno.matrix(df=train[col_missing],figsize=(14,8),color=(0.42,0.1,0.05),)
缺失值可视化表示
3.2 Wide and Deep 模型搭建

1. 包的调用
值得注意的是,sklearn.base自定义转换函器:创建一个类,实现fit()、transform()和fit_transform(),如果使用TransformerMixin作为基类,则自动实现fit_transform()函数,fit_transform() <==> fit().transform();如果添加BaseEstimator作为基类,,注意此时__init__函数不能接受 ∗args 和 ∗∗kwargs,还可以使用两个额外的方法(get_params()和set_params()),这两个函数对于自动超参数调优有用处。

import numpy as np
import tensorflow as tf
import pandas as pd
from sklearn.base import BaseEstimator,TransformerMixin

2. 类的定义及参数初始化
定义wide_and_deep类作为BaseEstimator,TransformerMixin的子类,以及参数的定义及初始化。

class wide_and_deep(BaseEstimator,TransformerMixin):
    def __init__(self,feature_size = 100,field_size=39, embedding_size=8,deep_layers=[512,256,1],
                 batch_size=256,learning_rate=0.001,optimizer='adam',random_seed=2020,l2_reg=0.0):
        self.feature_size = feature_size
        self.field_size = field_size
        self.embedding_size = embedding_size
        self.deep_layers = deep_layers
        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.train_result, self.valid_result = [],[]
        self.max_iteration = 100
        
        self._init_graph()

3. 图的构建
图的构建分为几个部分:
a) 参数定义,包括特征索引、特征值、标签、dropout、训练阶段。

    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')

b) 初始化嵌入层,权值包括特征嵌入、宽部分权值、宽部分偏置。

            #initializze embedding layer
            self.weights = dict()
            
            self.weights['feature_embeddings'] = tf.Variable(tf.random_normal([self.feature_size, self.embedding_size], 0.0, 0.01),name='feature_embeddings')
            self.weights['wide_weight'] = tf.Variable(tf.random_normal([self.field_size * self.embedding_size], 0.0, 1.0), name='wide_weight')
            self.weights['wide_bias'] = tf.Variable(tf.random_normal([1, 1], 0.0, 1.0), name='wide_weight')

c) 初始化深度网络层,包括输入、隐含、输出层共三层。

            # initialize deep layers
            input_size = self.field_size * self.embedding_size
            glorot = np.sqrt(2.0 / (input_size + self.deep_layers[0]))
            self.weights['layer_0'] = tf.Variable(np.random.normal(loc=0, scale=glorot,size=(input_size,self.deep_layers[0])),dtype=np.float32)
            self.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]))
            self.weights['layer_1'] = tf.Variable(np.random.normal(loc=0, scale=glorot,size=(self.deep_layers[0],self.deep_layers[1])),dtype=np.float32)
            self.weights['bias_1'] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(1,self.deep_layers[1])),dtype=np.float32)
            
            glorot = np.sqrt(2.0 / (self.deep_layers[1] + self.deep_layers[2]))
            self.weights['layer_2'] = tf.Variable(np.random.normal(loc=0, scale=glorot,size=(self.deep_layers[1],self.deep_layers[2])),dtype=np.float32)
            self.weights['bias_2'] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(1,self.deep_layers[2])),dtype=np.float32)

d) 模型实现,主要可分为嵌入、宽度、深度、组合四个部分

            # model
            self.embeddings = tf.nn.embedding_lookup(self.weights['feature_embeddings'], self.feat_index) # N * F * K
            feat_value = tf.reshape(self.feat_value, shape=[-1,self.field_size,1])
            self.embeddings = tf.multiply(self.embeddings,feat_value)
            self.embeddings = tf.reshape(self.embeddings,shape=[-1,self.field_size * self.embedding_size]) # N * (F * K)

            # wide part
            self.y_wide1 = tf.multiply(self.embeddings, self.weights['wide_weight'])
            self.y_wide1 = tf.add(self.y_wide1,self.weights['wide_bias'])
            self.y_wide = tf.reshape(tf.reduce_sum(self.y_wide1,1),shape=[-1,1])
            
            #deep part
            self.y_deep = tf.add(tf.matmul(self.embeddings,self.weights['layer_0']),self.weights['bias_0'])
            self.y_deep = tf.nn.relu(self.y_deep)
            self.y_deep = tf.add(tf.matmul(self.y_deep, self.weights['layer_1']),self.weights['bias_1'])
            self.y_deep = tf.nn.relu(self.y_deep)
            self.y_deep = tf.add(tf.matmul(self.y_deep, self.weights['layer_2']),self.weights['bias_2'])
            self.y_deep = tf.nn.relu(self.y_deep)
            
            # combine wide and deep part together by different weights
            self.weights['wide_weight'] = tf.Variable(tf.constant(0.01),dtype=np.float32)
            self.weights['deep_weight'] = tf.Variable(tf.constant(1.00),dtype=np.float32)
            self.out = tf.add(tf.multiply(self.weights['wide_weight'],self.y_wide),
                              tf.multiply(self.weights['deep_weight'],self.y_deep))

e) 损失函数的计算和优化函数对于损失值的最小化

            # loss part
            self.out = tf.nn.sigmoid(self.out)
            self.loss = tf.losses.log_loss(self.label, self.out)
            
            # optimizer part
            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)

f) 模型保存、初始化与tensorboard结构绘制

            self.save = tf.train.Saver()
            save_path = "model/model.ckpt"
            
            init = tf.global_variables_initializer() 
            self.sess = tf.Session()
            self.sess.run(init)
            save_path = self.save.save(self.sess, save_path, global_step=1)
            
            writer = tf.summary.FileWriter("D:/logs/", tf.get_default_graph())
            writer.close()

通过tensorboard存储及展示出的网络结构如下所示:

4. 训练函数
通过上述构建的图结构和模型,可以直接进行训练。

    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)))

5. 文件的加载
加载训练文件与测试文件,并列出数值列和忽略的列,经过处理后,total_feature 值为 254

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)

feature_dict 展示了不同特征的分布情况,如下显示了其中一部分

feature_dict 部分结果

6. 数据转换与训练
将训练集数据进行转换,得到适合训练的数据格式,并进行训练。

# 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]

wide_deep = wide_and_deep(feature_size=total_feature, field_size=field_size, embedding_size=8)
wide_deep.train(train_feature_index, train_feature_value, train_y)

将train_feature_index, train_feature_value的规模均为,部分结果展示如下所示;通过经过删除处理,field_size为37。

train_feature_value 部分结果
train_feature_index 部分结果

同时将以上数据输入到定义好的神经网络中进行训练,得到训练过程中的损失值如下:

epoch 0,loss is 0.18305999
epoch 1,loss is 0.17168762
epoch 2,loss is 0.16387627
epoch 3,loss is 0.161211
···
epoch 96,loss is 0.16079274
epoch 97,loss is 0.16078682
epoch 98,loss is 0.1607809
epoch 99,loss is 0.16077502

参考资料

[1]. Cheng H T , Koc L , Harmsen J , et al. Wide & Deep Learning for Recommender Systems[J]. 2016.
[2]. 推荐系统与深度学习. 黄昕等. 清华大学出版社. 2019.
[3]. Paul Covington, Jay Adams, Emre Sargin. Deep Neural Networks for YouTube Recommendations[J]. 2016.
[4]. https://blog.csdn.net/qq_37195507/article/details/78553581
[5]. https://github.com/wangby511/Recommendation_System

春潮带雨晚来急,野渡无人舟自横。——韦应物《滁州西涧》

你可能感兴趣的:(推荐系统(五):基于深度学习的推荐模型)