FM模型相比普通的線性模型,多了二階項,是一個二階多項式模型。
從實際經(jīng)驗來看,線上有很多id類特征,categorical特征,這種特征是很稀疏的,對于求解w具有一定的困難。所以FM模型引入了輔助向量v
來表示上式中的w權重。



FM推導公式
所以就可以愉快地優(yōu)化了~~
代碼實現(xiàn)
fm代碼實現(xiàn)起來比較簡單
def build_model(self):
self.x = tf.placeholder(tf.float32, shape=[None, self.input_dim])
self.y = tf.placeholder(tf.float32, shape=[None, 1])
self.w0 = tf.Variable(np.zeros(1), name="w0", dtype=tf.float32)
self.w = tf.Variable(np.zeros(self.input_dim), name="linear_weight", dtype=tf.float32)
self.v = tf.Variable(tf.random_normal(shape=[self.input_dim, self.v_dim], mean=0, stddev=0.01), name='pair_weight', dtype=tf.float32)
# 根據(jù)fm公式計算模型輸出
linear_items = tf.add(self.w0, tf.reduce_sum(tf.multiply(self.w, self.x), axis=1, keep_dims=True))
x_square = tf.square(self.x)
v_square = tf.square(self.v)
pairwise_items = 0.5 * tf.reduce_sum(tf.square(tf.matmul(self.x, self.v)) - tf.matmul(x_square, v_square),
axis=1, keep_dims=True)
y_hat = tf.add(linear_items, pairwise_items)
with tf.name_scope("loss"):
self.loss = tf.reduce_mean(tf.square(self.y - y_hat))
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
self.train_step = optimizer.minimize(self.loss)