You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tf_ncf.py 2.6 kB

4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import tensorflow as tf
  2. def neural_mf(user_input, item_input, y_, num_users, num_items, embed_partitioner=None):
  3. embed_dim = 8
  4. layers = [64, 32, 16, 8]
  5. learning_rate = 0.01
  6. with tf.compat.v1.variable_scope('nmf', dtype=tf.float32):
  7. with tf.device('/cpu:0'):
  8. User_Embedding = tf.compat.v1.get_variable(name="user_embed", shape=(
  9. num_users, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner)
  10. Item_Embedding = tf.compat.v1.get_variable(name="item_embed", shape=(
  11. num_items, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner)
  12. user_latent = tf.nn.embedding_lookup(User_Embedding, user_input)
  13. item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input)
  14. W1 = tf.compat.v1.get_variable(name='W1', shape=(
  15. layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1))
  16. W2 = tf.compat.v1.get_variable(name='W2', shape=(
  17. layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1))
  18. W3 = tf.compat.v1.get_variable(name='W3', shape=(
  19. layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1))
  20. W4 = tf.compat.v1.get_variable(name='W4', shape=(
  21. embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1))
  22. with tf.device('/gpu:0'):
  23. mf_user_latent, mlp_user_latent = tf.split(
  24. user_latent, [embed_dim, layers[0] // 2], 1)
  25. mf_item_latent, mlp_item_latent = tf.split(
  26. item_latent, [embed_dim, layers[0] // 2], 1)
  27. mf_vector = tf.multiply(mf_user_latent, mf_item_latent)
  28. mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1)
  29. fc1 = tf.matmul(mlp_vector, W1)
  30. relu1 = tf.nn.relu(fc1)
  31. fc2 = tf.matmul(relu1, W2)
  32. relu2 = tf.nn.relu(fc2)
  33. fc3 = tf.matmul(relu2, W3)
  34. relu3 = tf.nn.relu(fc3)
  35. concat_vector = tf.concat((mf_vector, relu3), 1)
  36. y = tf.reshape(tf.matmul(concat_vector, W4), (-1,))
  37. loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_)
  38. loss = tf.reduce_mean(loss)
  39. y = tf.sigmoid(y)
  40. optimizer = tf.compat.v1.train.GradientDescentOptimizer(
  41. learning_rate)
  42. return loss, y, optimizer