Skip to content

Instantly share code, notes, and snippets.

@eggie5
Created June 24, 2020 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eggie5/3f986be7bb986a24980f57522611422b to your computer and use it in GitHub Desktop.
Save eggie5/3f986be7bb986a24980f57522611422b to your computer and use it in GitHub Desktop.
def bpr_mf(user_count, item_count, hidden_dim):
u = tf.placeholder(tf.int32, [None])
i = tf.placeholder(tf.int32, [None])
j = tf.placeholder(tf.int32, [None])
with tf.device("/cpu:0"):
user_emb_w = tf.get_variable("user_emb_w", [user_count+1, hidden_dim],
initializer=tf.random_normal_initializer(0, 0.1))
item_emb_w = tf.get_variable("item_emb_w", [item_count+1, hidden_dim],
initializer=tf.random_normal_initializer(0, 0.1))
item_b = tf.get_variable("item_b", [item_count+1, 1],
initializer=tf.constant_initializer(0.0))
u_emb = tf.nn.embedding_lookup(user_emb_w, u)
i_emb = tf.nn.embedding_lookup(item_emb_w, i)
i_b = tf.nn.embedding_lookup(item_b, i)
j_emb = tf.nn.embedding_lookup(item_emb_w, j)
j_b = tf.nn.embedding_lookup(item_b, j)
# MF predict: u_i > u_j
x = i_b - j_b + tf.reduce_sum(tf.mul(u_emb, (i_emb - j_emb)), 1, keep_dims=True)
mf_auc = tf.reduce_mean(tf.to_float(x > 0))
l2_norm = tf.add_n([
tf.reduce_sum(tf.mul(u_emb, u_emb)),
tf.reduce_sum(tf.mul(i_emb, i_emb)),
tf.reduce_sum(tf.mul(j_emb, j_emb))
])
regulation_rate = 0.0001
bprloss = regulation_rate * l2_norm - tf.reduce_mean(tf.log(tf.sigmoid(x)))
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(bprloss)
return u, i, j, mf_auc, bprloss, train_op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment