|
| 1 | +import tensorflow as tf |
| 2 | +import numpy as np |
| 3 | +from sklearn.metrics import roc_auc_score |
| 4 | + |
| 5 | + |
| 6 | +class RippleNet(object): |
| 7 | + def __init__(self, args, n_entity, n_relation): |
| 8 | + self._parse_args(args, n_entity, n_relation) |
| 9 | + self._build_inputs() |
| 10 | + self._build_embeddings() |
| 11 | + self._build_model() |
| 12 | + self._build_loss() |
| 13 | + self._build_train() |
| 14 | + |
| 15 | + def _parse_args(self, args, n_entity, n_relation): |
| 16 | + self.n_entity = n_entity |
| 17 | + self.n_relation = n_relation |
| 18 | + self.dim = args.dim |
| 19 | + self.n_hop = args.n_hop |
| 20 | + self.kge_weight = args.kge_weight |
| 21 | + self.l2_weight = args.l2_weight |
| 22 | + self.lr = args.lr |
| 23 | + self.n_memory = args.n_memory |
| 24 | + self.item_update_mode = args.item_update_mode |
| 25 | + self.using_all_hops = args.using_all_hops |
| 26 | + |
| 27 | + def _build_inputs(self): |
| 28 | + self.items = tf.placeholder(dtype=tf.int32, shape=[None], name="items") |
| 29 | + self.labels = tf.placeholder(dtype=tf.float64, shape=[None], name="labels") |
| 30 | + self.memories_h = [] |
| 31 | + self.memories_r = [] |
| 32 | + self.memories_t = [] |
| 33 | + |
| 34 | + for hop in range(self.n_hop): |
| 35 | + self.memories_h.append( |
| 36 | + tf.placeholder(dtype=tf.int32, shape=[None, self.n_memory], name="memories_h_" + str(hop))) |
| 37 | + self.memories_r.append( |
| 38 | + tf.placeholder(dtype=tf.int32, shape=[None, self.n_memory], name="memories_r_" + str(hop))) |
| 39 | + self.memories_t.append( |
| 40 | + tf.placeholder(dtype=tf.int32, shape=[None, self.n_memory], name="memories_t_" + str(hop))) |
| 41 | + |
| 42 | + def _build_embeddings(self): |
| 43 | + self.entity_emb_matrix = tf.get_variable(name="entity_emb_matrix", dtype=tf.float64, |
| 44 | + shape=[self.n_entity, self.dim], |
| 45 | + initializer=tf.contrib.layers.xavier_initializer()) |
| 46 | + self.relation_emb_matrix = tf.get_variable(name="relation_emb_matrix", dtype=tf.float64, |
| 47 | + shape=[self.n_relation, self.dim, self.dim], |
| 48 | + initializer=tf.contrib.layers.xavier_initializer()) |
| 49 | + |
| 50 | + def _build_model(self): |
| 51 | + # transformation matrix for updating item embeddings at the end of each hop |
| 52 | + self.transform_matrix = tf.get_variable(name="transform_matrix", shape=[self.dim, self.dim], dtype=tf.float64, |
| 53 | + initializer=tf.contrib.layers.xavier_initializer()) |
| 54 | + |
| 55 | + # [batch size, dim] |
| 56 | + self.item_embeddings = tf.nn.embedding_lookup(self.entity_emb_matrix, self.items) |
| 57 | + |
| 58 | + self.h_emb_list = [] |
| 59 | + self.r_emb_list = [] |
| 60 | + self.t_emb_list = [] |
| 61 | + for i in range(self.n_hop): |
| 62 | + # [batch size, n_memory, dim] |
| 63 | + self.h_emb_list.append(tf.nn.embedding_lookup(self.entity_emb_matrix, self.memories_h[i])) |
| 64 | + |
| 65 | + # [batch size, n_memory, dim, dim] |
| 66 | + self.r_emb_list.append(tf.nn.embedding_lookup(self.relation_emb_matrix, self.memories_r[i])) |
| 67 | + |
| 68 | + # [batch size, n_memory, dim] |
| 69 | + self.t_emb_list.append(tf.nn.embedding_lookup(self.entity_emb_matrix, self.memories_t[i])) |
| 70 | + |
| 71 | + o_list = self._key_addressing() |
| 72 | + |
| 73 | + self.scores = tf.squeeze(self.predict(self.item_embeddings, o_list)) |
| 74 | + self.scores_normalized = tf.sigmoid(self.scores) |
| 75 | + |
| 76 | + def _key_addressing(self): |
| 77 | + o_list = [] |
| 78 | + for hop in range(self.n_hop): |
| 79 | + # [batch_size, n_memory, dim, 1] |
| 80 | + h_expanded = tf.expand_dims(self.h_emb_list[hop], axis=3) |
| 81 | + # [batch_size, n_memory, dim] |
| 82 | + Rh = tf.squeeze(tf.matmul(self.r_emb_list[hop], h_expanded), axis=3) |
| 83 | + # [batch_size, dim, 1] |
| 84 | + v = tf.expand_dims(self.item_embeddings, axis=2) |
| 85 | + # [batch_size, n_memory] |
| 86 | + probs = tf.squeeze(tf.matmul(Rh, v), axis=2) |
| 87 | + # [batch_size, n_memory] |
| 88 | + probs_normalized = tf.nn.softmax(probs) |
| 89 | + # [batch_size, n_memory, 1] |
| 90 | + probs_expanded = tf.expand_dims(probs_normalized, axis=2) |
| 91 | + # [batch_size, dim] |
| 92 | + o = tf.reduce_sum(self.t_emb_list[hop] * probs_expanded, axis=1) |
| 93 | + |
| 94 | + self.item_embeddings = self.update_item_embedding(self.item_embeddings, o) |
| 95 | + o_list.append(o) |
| 96 | + return o_list |
| 97 | + |
| 98 | + def update_item_embedding(self, item_embeddings, o): |
| 99 | + if self.item_update_mode == "replace": |
| 100 | + item_embeddings = o |
| 101 | + elif self.item_update_mode == "plus": |
| 102 | + item_embeddings = item_embeddings + o |
| 103 | + elif self.item_update_mode == "replace_transform": |
| 104 | + item_embeddings = tf.matmul(o, self.transform_matrix) |
| 105 | + elif self.item_update_mode == "plus_transform": |
| 106 | + item_embeddings = tf.matmul(item_embeddings + o, self.transform_matrix) |
| 107 | + else: |
| 108 | + raise Exception("Unknown item updating mode: " + self.item_update_mode) |
| 109 | + return item_embeddings |
| 110 | + |
| 111 | + def predict(self, item_embeddings, o_list): |
| 112 | + y = o_list[-1] |
| 113 | + if self.using_all_hops: |
| 114 | + for i in range(self.n_hop - 1): |
| 115 | + y += o_list[i] |
| 116 | + |
| 117 | + # [batch_size] |
| 118 | + scores = tf.reduce_sum(item_embeddings * y, axis=1) |
| 119 | + return scores |
| 120 | + |
| 121 | + def _build_loss(self): |
| 122 | + self.base_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=self.labels, logits=self.scores)) |
| 123 | + |
| 124 | + self.kge_loss = 0 |
| 125 | + for hop in range(self.n_hop): |
| 126 | + h_expanded = tf.expand_dims(self.h_emb_list[hop], axis=2) |
| 127 | + t_expanded = tf.expand_dims(self.t_emb_list[hop], axis=3) |
| 128 | + hRt = tf.squeeze(tf.matmul(tf.matmul(h_expanded, self.r_emb_list[hop]), t_expanded)) |
| 129 | + self.kge_loss += tf.reduce_mean(tf.sigmoid(hRt)) |
| 130 | + self.kge_loss = -self.kge_weight * self.kge_loss |
| 131 | + |
| 132 | + self.l2_loss = 0 |
| 133 | + for hop in range(self.n_hop): |
| 134 | + self.l2_loss += tf.reduce_mean(tf.reduce_sum(self.h_emb_list[hop] * self.h_emb_list[hop])) |
| 135 | + self.l2_loss += tf.reduce_mean(tf.reduce_sum(self.t_emb_list[hop] * self.t_emb_list[hop])) |
| 136 | + self.l2_loss += tf.reduce_mean(tf.reduce_sum(self.r_emb_list[hop] * self.r_emb_list[hop])) |
| 137 | + if self.item_update_mode == "replace nonlinear" or self.item_update_mode == "plus nonlinear": |
| 138 | + self.l2_loss += tf.nn.l2_loss(self.transform_matrix) |
| 139 | + self.l2_loss = self.l2_weight * self.l2_loss |
| 140 | + |
| 141 | + self.loss = self.base_loss + self.kge_loss + self.l2_loss |
| 142 | + |
| 143 | + def _build_train(self): |
| 144 | + self.optimizer = tf.train.AdamOptimizer(self.lr).minimize(self.loss) |
| 145 | + |
| 146 | + def train(self, sess, feed_dict): |
| 147 | + return sess.run([self.optimizer, self.loss], feed_dict) |
| 148 | + |
| 149 | + def eval(self, sess, feed_dict): |
| 150 | + labels, scores = sess.run([self.labels, self.scores_normalized], feed_dict) |
| 151 | + auc = roc_auc_score(y_true=labels, y_score=scores) |
| 152 | + predictions = [1 if i >= 0.5 else 0 for i in scores] |
| 153 | + acc = np.mean(np.equal(predictions, labels)) |
| 154 | + return auc, acc |
0 commit comments