在DeepFM介绍过当前ctr预估的深度模型有两种结构,并行结构和串行结构,DeepFM是典型的并行结构,本文所介绍的FNN和FNM都是串行结构
1、FNN原理
- FNN采用了FM经过预训练得到的隐含层和其权重(隐向量)作为DNN网络的初始值
-
FNN是FM+MLP的结构,但是并不是端到端的结构,MLP的输入是FM模型训练好之后的的向量作为MLP的输入
其结构为:
FNN结构.png
2、FNM原理
2.1 FM和FNM的比较
FNM模型在FM的二阶交互的基础上加入了一个DNN模型,FM的模型公式为:
FM公式.png
其中n为特征的个数,而其二阶表达式为:
FM二阶.png
观察二阶的推导公式,其中k为隐向量的维度,如果我们不把隐向量的维度进行相加,那么二阶特征组合输出的结果就是一个k为的向量,而这个k维的向量就是FNM模型中DNN的输入。
因此FNM的模型公式为
FNM公式.png
因为没有的存在,所以
括号中就是NFM模型的二阶特征交叉项,是一个k维的向量。将这个k维向量输入DNN结构中就得到了FNM的二阶交互的预测结果。
2.2 FNM的结构
FNM结构.png
图中显示的是二阶特征组合的DNN结构,也就是的结构模型。
- 在二阶特征交叉的时候使用交互池,论文中在交互池之后对数据做Batch Normalization处理。
- 当FNM的深层交互层为1的时候,也就是DNN没有隐层,那么NFM就变成了FM
- FNM和FNN的主要区别就是DNN层的输入向量不同,FNM的在深度层的输入为两两特征向量元素相乘之后叠加,其维度跟特征向量的维度是一样的,而FNN输入深度层的向量为特征向量的concatenate,因此深度层的参数FNM会少很多。
3、实验代码
本次只实现了NFM的代码,根据DeepFM的代码进行修改程序,评测采用了RMSE
3.1 数据预处理
def get_feature_dict(df,num_col):
'''
特征向量字典,其格式为{field:{特征:编号}}
:param df:
:return: {field:{特征:编号}}
'''
feature_dict={}
total_feature=0
df.drop('rate',axis=1,inplace=True)
for col in df.columns:
if col in num_col:
feature_dict[col]=total_feature
total_feature += 1
else:
unique_feature = df[col].unique()
feature_dict[col]=dict(zip(unique_feature,range(total_feature,total_feature+len(unique_feature))))
total_feature += len(unique_feature)
return feature_dict,total_feature
def get_data(df,feature_dict):
'''
:param df:
:return:
'''
y = df[['rate']].values
dd = df.drop('rate',axis=1)
df_index = dd.copy()
df_value = dd.copy()
for col in df_index.columns:
if col in num_col:
df_index[col] = feature_dict[col]
else:
df_index[col] = df_index[col].map(feature_dict[col])
df_value[col] = 1.0
xi=df_index.values.tolist()
xv=df_value.values.tolist()
return xi,xv,y
3.2 NFM模型
模型实验过程:
FNM.png
3.2.1 设置权重初始化
根据上述公式原理,NFM模型可以分成两个部分,FM部分和DNN部分,FM部分的权重有偏置项,一阶权重w,二阶权重v;DNN部分为全连接层权重
'''1、权重初始化分为FM部分和Deep部分'''
#FM权重
w_0 = tf.Variable(tf.constant(0.1),name='bias')
w = tf.Variable(tf.random_normal([feature_size, 1], mean=0, stddev=0.01),name='first_weight')
v = tf.Variable(tf.random_normal([feature_size, embedding_size], mean=0, stddev=0.01),name='second_weight')
#DeepLayer权重
weights={}
num_layer = len(deep_layers)
input_size = embedding_size
glorot = np.sqrt(2.0 / (input_size + deep_layers[0]))
weights['layer_0'] = tf.Variable(
np.random.normal(loc=0, scale=glorot, size=(input_size, deep_layers[0])), dtype=np.float32
)
weights['bias_0'] = tf.Variable(
np.random.normal(loc=0, scale=glorot, size=(1, deep_layers[0])), dtype=np.float32
)
for i in range(1, num_layer):
glorot = np.sqrt(2.0 / (deep_layers[i - 1] + deep_layers[i]))
weights["layer_%d" % i] = tf.Variable(
np.random.normal(loc=0, scale=glorot, size=(deep_layers[i - 1], deep_layers[i])),
dtype=np.float32) # layers[i-1] * layers[i]
weights["bias_%d" % i] = tf.Variable(
np.random.normal(loc=0, scale=glorot, size=(1, deep_layers[i])),
dtype=np.float32) # 1 * layer[i]
3.2.2 模型输入和Embedding层
#输入
feat_index = tf.placeholder(tf.int32,[None,None],name='feat_index')
feat_value = tf.placeholder(tf.float32,[None,None],name='feat_value')
label = tf.placeholder(tf.float32,shape=[None,1],name='label')
#Embedding Layer
embedding_first =tf.nn.embedding_lookup(w,feat_index) #None*F *1 F是field_size大小,也就是不同域的个数
embedding = tf.nn.embedding_lookup(v,feat_index) #None * F * embedding_size
feat_val = tf.reshape(feat_value,[-1,field_size,1])
3.2.3 模型输入和Embedding层
1)一阶和偏置项,得到的向量维度为None*1,None指的是输入的样本数
'''3、模型'''
# first_order term +偏置
y_first_order= tf.reduce_sum(tf.multiply(embedding_first,feat_val),2) # None*F
y_first_order_num = tf.reduce_sum(y_first_order,1,keepdims=True) # None*1
liner = tf.add(y_first_order_num, w_0) # None*1
2)二阶交互池,得到一个k为的向量None*k,输入到DNN模型当中
# second_order term
embeddings = tf.multiply(embedding,feat_val) #N*F*K
sum_square = tf.square(tf.reduce_sum(embedding,1)) #N*K
square_sum = tf.reduce_sum(tf.square(embedding),1) #N*k
y_second_order = 0.5* tf.subtract(sum_square,square_sum) #N*k
3)深度层,把交互池的结果经过神经网络,并输出结果N*1
#DeepLayer
y_deep = y_second_order
for i in range(len(deep_layers)):
y_deep = tf.add(tf.matmul(y_deep,weights['layer_%d'%i]),weights['bias_%d' %i])
y_deep = tf.nn.relu(y_deep)
y_deep = tf.nn.dropout(y_deep,dropout_deep[i]) #N*deep_layers[i]
4)最终输出
# 输出
out = tf.add(liner,tf.reduce_sum(y_deep,1,keepdims=True)) #N*1
5)损失函数
loss = tf.nn.l2_loss(tf.subtract(out,label))
optimizer = tf.train.AdamOptimizer(lr,beta1=0.9,beta2=0.999,epsilon=1e-8).minimize(loss)
完整代码见:
https://github.com/garfieldsun/recsys/tree/master/NFM
参考资料:
1、FNN论文
2、FNM论文
3、https://daiwk.github.io/posts/dl-dl-ctr-models.html
4、https://www.jianshu.com/p/4e65723ee632