code
stringlengths
17
6.64M
def train(args, adj_list, features, train_data, train_label, test_data, test_label, paras): with tf.Session() as sess: adj_data = adj_list net = GAS(session=sess, nodes=paras[0], class_size=paras[4], embedding_r=paras[1], embedding_u=paras[2], embedding_i=paras[3], h_u_size=paras[6], h_i_size=para...
class GEM(Algorithm): def __init__(self, session, nodes, class_size, meta, embedding, encoding, hop): self.nodes = nodes self.meta = meta self.class_size = class_size self.embedding = embedding self.encoding = encoding self.hop = hop self.placeholders = {'a...
def arg_parser(): parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=123, help='Random seed.') parser.add_argument('--dataset_str', type=str, default='dblp', help="['dblp','example']") parser.add_argument('--epoch_num', type=int, default=30, help='Number of epochs to tr...
def set_env(args): tf.reset_default_graph() np.random.seed(args.seed) tf.set_random_seed(args.seed)
def get_data(ix, int_batch, train_size): if ((ix + int_batch) >= train_size): ix = (train_size - int_batch) end = train_size else: end = (ix + int_batch) return (train_data[ix:end], train_label[ix:end])
def load_data(args): if (args.dataset_str == 'dblp'): (adj_list, features, train_data, train_label, test_data, test_label) = load_data_dblp() if (args.dataset_str == 'example'): (adj_list, features, train_data, train_label, test_data, test_label) = load_example_gem() node_size = features.s...
def train(args, adj_list, features, train_data, train_label, test_data, test_label, paras): with tf.Session() as sess: adj_data = adj_list meta_size = len(adj_list) net = GEM(session=sess, class_size=paras[2], encoding=args.k, meta=meta_size, nodes=paras[0], embedding=paras[1], hop=args.ho...
def arg_parser(): parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=123, help='Random seed.') parser.add_argument('--dataset_str', type=str, default='dblp', help="['dblp','example']") parser.add_argument('--epoch_num', type=int, default=30, help='Number of epochs to tr...
def set_env(args): tf.reset_default_graph() np.random.seed(args.seed) tf.set_random_seed(args.seed)
def get_data(ix, int_batch, train_size): if ((ix + int_batch) >= train_size): ix = (train_size - int_batch) end = train_size else: end = (ix + int_batch) return (train_data[ix:end], train_label[ix:end])
def load_data(args): if (args.dataset_str == 'dblp'): (adj_list, features, train_data, train_label, test_data, test_label) = load_data_dblp() node_size = features.shape[0] node_embedding = features.shape[1] class_size = train_label.shape[1] train_size = len(train_data) ...
def train(args, adj_list, features, train_data, train_label, test_data, test_label, paras): with tf.Session() as sess: adj_data = adj_list net = GeniePath(session=sess, out_dim=paras[2], dim=args.dim, lstm_hidden=args.lstm_hidden, nodes=paras[0], in_dim=paras[1], heads=args.heads, layer_num=args.l...
class MeanAggregator(Layer): '\n Aggregates via mean followed by matmul and non-linearity.\n ' def __init__(self, input_dim, output_dim, neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(MeanAggregator, self).__init__(**kwargs) self...
class HeteMeanAggregator(Layer): '\n Aggregates via mean followed by matmul and non-linearity.\n ' def __init__(self, input_dim, output_dim, neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(MeanAggregator, self).__init__(**kwargs) ...
class GCNAggregator(Layer): '\n Aggregates via mean followed by matmul and non-linearity.\n Same matmul parameters are used self vector and neighbor vectors.\n ' def __init__(self, input_dim, output_dim, neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs...
class MaxPoolingAggregator(Layer): ' Aggregates via max-pooling over MLP functions.\n ' def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(MaxPoolingAggregator, self).__init__(**kwar...
class MeanPoolingAggregator(Layer): ' Aggregates via mean-pooling over MLP functions.\n ' def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(MeanPoolingAggregator, self).__init__(**k...
class TwoMaxLayerPoolingAggregator(Layer): ' Aggregates via pooling over two MLP functions.\n ' def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(TwoMaxLayerPoolingAggregator, self)...
class SeqAggregator(Layer): ' Aggregates via a standard LSTM.\n ' def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(SeqAggregator, self).__init__(**kwargs) self.dropout = dr...
def uniform(shape, scale=0.05, name=None): 'Uniform init.' initial = tf.random_uniform(shape, minval=(- scale), maxval=scale, dtype=tf.float32) return tf.Variable(initial, name=name)
def glorot(shape, name=None): 'Glorot & Bengio (AISTATS 2010) init.' init_range = np.sqrt((6.0 / (shape[0] + shape[1]))) initial = tf.random_uniform(shape, minval=(- init_range), maxval=init_range, dtype=tf.float32) return tf.Variable(initial, name=name)
def zeros(shape, name=None): 'All zeros.' initial = tf.zeros(shape, dtype=tf.float32) return tf.Variable(initial, name=name)
def ones(shape, name=None): 'All ones.' initial = tf.ones(shape, dtype=tf.float32) return tf.Variable(initial, name=name)
def get_layer_uid(layer_name=''): 'Helper function, assigns unique layer IDs.' if (layer_name not in _LAYER_UIDS): _LAYER_UIDS[layer_name] = 1 return 1 else: _LAYER_UIDS[layer_name] += 1 return _LAYER_UIDS[layer_name]
class Layer(object): 'Base layer class. Defines basic API for all layer objects.\n Implementation inspired by keras (http://keras.io).\n # Properties\n name: String, defines the variable scope of the layer.\n logging: Boolean, switches Tensorflow histogram logging on/off\n\n # Methods\n ...
class Dense(Layer): 'Dense layer.' def __init__(self, input_dim, output_dim, dropout=0.0, act=tf.nn.relu, placeholders=None, bias=True, featureless=False, sparse_inputs=False, **kwargs): super(Dense, self).__init__(**kwargs) self.dropout = dropout self.act = act self.featurele...
def masked_logit_cross_entropy(preds, labels, mask): 'Logit cross-entropy loss with masking.' loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=preds, labels=labels) loss = tf.reduce_sum(loss, axis=1) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.maximum(tf.reduce_sum(mask), tf.constant([1...
def masked_softmax_cross_entropy(preds, labels, mask): 'Softmax cross-entropy loss with masking.' loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.maximum(tf.reduce_sum(mask), tf.constant([1.0])) loss *= mask return t...
def masked_l2(preds, actuals, mask): 'L2 loss with masking.' loss = tf.nn.l2(preds, actuals) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) loss *= mask return tf.reduce_mean(loss)
def masked_accuracy(preds, labels, mask): 'Accuracy with masking.' correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1)) accuracy_all = tf.cast(correct_prediction, tf.float32) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) accuracy_all *= mask return...
class UniformNeighborSampler(Layer): '\n Uniformly samples neighbors.\n Assumes that adj lists are padded with random re-sampling\n ' def __init__(self, adj_info, **kwargs): super(UniformNeighborSampler, self).__init__(**kwargs) self.adj_info = adj_info def _call(self, inputs): ...
class DistanceNeighborSampler(Layer): '\n Sampling neighbors based on the feature consistency.\n ' def __init__(self, adj_info, **kwargs): super(DistanceNeighborSampler, self).__init__(**kwargs) self.adj_info = adj_info self.num_neighs = adj_info.shape[(- 1)] def _call(self...
class BipartiteEdgePredLayer(Layer): def __init__(self, input_dim1, input_dim2, placeholders, dropout=False, act=tf.nn.sigmoid, loss_fn='xent', neg_sample_weights=1.0, bias=False, bilinear_weights=False, **kwargs): '\n Basic class that applies skip-gram-like loss\n (i.e., dot product of nod...
class SupervisedGraphconsis(models.SampleAndAggregate): 'Implementation of supervised GraphConsis.' def __init__(self, num_classes, placeholders, features, adj, degrees, layer_infos, concat=True, aggregator_type='mean', model_size='small', sigmoid_loss=False, identity_dim=0, num_re=3, **kwargs): '\n ...
def calc_f1(y_true, y_pred): if (not FLAGS.sigmoid): y_true = np.argmax(y_true, axis=1) y_pred = np.argmax(y_pred, axis=1) else: y_pred[(y_pred > 0.5)] = 1 y_pred[(y_pred <= 0.5)] = 0 return (metrics.f1_score(y_true, y_pred, average='micro'), metrics.f1_score(y_true, y_pred...
def calc_auc(y_true, y_pred): return metrics.roc_auc_score(y_true, y_pred)
def evaluate(sess, model, minibatch_iter, size=None): t_test = time.time() (feed_dict_val, labels) = minibatch_iter.node_val_feed_dict(size) node_outs_val = sess.run([model.preds, model.loss], feed_dict=feed_dict_val) (mic, mac) = calc_f1(labels, node_outs_val[0]) auc = calc_auc(labels, node_outs_...
def incremental_evaluate(sess, model, minibatch_iter, size, test=False): t_test = time.time() finished = False val_losses = [] val_preds = [] labels = [] iter_num = 0 finished = False while (not finished): (feed_dict_val, batch_labels, finished, _) = minibatch_iter.incremental_...
def construct_placeholders(num_classes): placeholders = {'labels': tf.placeholder(tf.float32, shape=(None, num_classes), name='labels'), 'batch': tf.placeholder(tf.int32, shape=None, name='batch1'), 'dropout': tf.placeholder_with_default(0.0, shape=(), name='dropout'), 'batch_size': tf.placeholder(tf.int32, name=...
def train(train_data, test_data=None): G = train_data[0] features = train_data[1] id_map = train_data[2] class_map = train_data[4] gs = train_data[5] num_relations = len(gs) if isinstance(list(class_map.values())[0], list): num_classes = len(list(class_map.values())[0]) else: ...
def main(argv=None): print('Loading training data..') file_name = FLAGS.file_name train_perc = FLAGS.train_perc relations = ['net_rur', 'net_rtr', 'net_rsr'] train_data = load_data(FLAGS.train_prefix, file_name, relations, train_perc) print('Done loading training data..') train(train_data)...
class MeanAggregator(Layer): '\n Aggregates via mean followed by matmul and non-linearity.\n ' def __init__(self, input_dim, output_dim, neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(MeanAggregator, self).__init__(**kwargs) self...
class GCNAggregator(Layer): '\n Aggregates via mean followed by matmul and non-linearity.\n Same matmul parameters are used self vector and neighbor vectors.\n ' def __init__(self, input_dim, output_dim, neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs...
class MaxPoolingAggregator(Layer): ' Aggregates via max-pooling over MLP functions.\n ' def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(MaxPoolingAggregator, self).__init__(**kwar...
class MeanPoolingAggregator(Layer): ' Aggregates via mean-pooling over MLP functions.\n ' def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(MeanPoolingAggregator, self).__init__(**k...
class TwoMaxLayerPoolingAggregator(Layer): ' Aggregates via pooling over two MLP functions.\n ' def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(TwoMaxLayerPoolingAggregator, self)...
class SeqAggregator(Layer): ' Aggregates via a standard LSTM.\n ' def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(SeqAggregator, self).__init__(**kwargs) self.dropout = dr...
def uniform(shape, scale=0.05, name=None): 'Uniform init.' initial = tf.random_uniform(shape, minval=(- scale), maxval=scale, dtype=tf.float32) return tf.Variable(initial, name=name)
def glorot(shape, name=None): 'Glorot & Bengio (AISTATS 2010) init.' init_range = np.sqrt((6.0 / (shape[0] + shape[1]))) initial = tf.random_uniform(shape, minval=(- init_range), maxval=init_range, dtype=tf.float32) return tf.Variable(initial, name=name)
def zeros(shape, name=None): 'All zeros.' initial = tf.zeros(shape, dtype=tf.float32) return tf.Variable(initial, name=name)
def ones(shape, name=None): 'All ones.' initial = tf.ones(shape, dtype=tf.float32) return tf.Variable(initial, name=name)
def get_layer_uid(layer_name=''): 'Helper function, assigns unique layer IDs.' if (layer_name not in _LAYER_UIDS): _LAYER_UIDS[layer_name] = 1 return 1 else: _LAYER_UIDS[layer_name] += 1 return _LAYER_UIDS[layer_name]
class Layer(object): 'Base layer class. Defines basic API for all layer objects.\n Implementation inspired by keras (http://keras.io).\n # Properties\n name: String, defines the variable scope of the layer.\n logging: Boolean, switches Tensorflow histogram logging on/off\n\n # Methods\n ...
class Dense(Layer): 'Dense layer.' def __init__(self, input_dim, output_dim, dropout=0.0, act=tf.nn.relu, placeholders=None, bias=True, featureless=False, sparse_inputs=False, **kwargs): super(Dense, self).__init__(**kwargs) self.dropout = dropout self.act = act self.featurele...
def masked_logit_cross_entropy(preds, labels, mask): 'Logit cross-entropy loss with masking.' loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=preds, labels=labels) loss = tf.reduce_sum(loss, axis=1) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.maximum(tf.reduce_sum(mask), tf.constant([1...
def masked_softmax_cross_entropy(preds, labels, mask): 'Softmax cross-entropy loss with masking.' loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.maximum(tf.reduce_sum(mask), tf.constant([1.0])) loss *= mask return t...
def masked_l2(preds, actuals, mask): 'L2 loss with masking.' loss = tf.nn.l2(preds, actuals) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) loss *= mask return tf.reduce_mean(loss)
def masked_accuracy(preds, labels, mask): 'Accuracy with masking.' correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1)) accuracy_all = tf.cast(correct_prediction, tf.float32) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) accuracy_all *= mask return...
class UniformNeighborSampler(Layer): '\n Uniformly samples neighbors.\n Assumes that adj lists are padded with random re-sampling\n ' def __init__(self, adj_info, **kwargs): super(UniformNeighborSampler, self).__init__(**kwargs) self.adj_info = adj_info def _call(self, inputs): ...
class BipartiteEdgePredLayer(Layer): def __init__(self, input_dim1, input_dim2, placeholders, dropout=False, act=tf.nn.sigmoid, loss_fn='xent', neg_sample_weights=1.0, bias=False, bilinear_weights=False, **kwargs): '\n Basic class that applies skip-gram-like loss\n (i.e., dot product of nod...
class SupervisedGraphsage(models.SampleAndAggregate): 'Implementation of supervised GraphSAGE.' def __init__(self, num_classes, placeholders, features, adj, degrees, layer_infos, concat=True, aggregator_type='mean', model_size='small', sigmoid_loss=False, identity_dim=0, **kwargs): '\n Args:\n...
def calc_f1(y_true, y_pred): if (not FLAGS.sigmoid): y_true = np.argmax(y_true, axis=1) y_pred = np.argmax(y_pred, axis=1) else: y_pred[(y_pred > 0.5)] = 1 y_pred[(y_pred <= 0.5)] = 0 return (metrics.f1_score(y_true, y_pred, average='micro'), metrics.f1_score(y_true, y_pred...
def evaluate(sess, model, minibatch_iter, size=None): t_test = time.time() (feed_dict_val, labels) = minibatch_iter.node_val_feed_dict(size) node_outs_val = sess.run([model.preds, model.loss], feed_dict=feed_dict_val) (mic, mac) = calc_f1(labels, node_outs_val[0]) return (node_outs_val[1], mic, ma...
def log_dir(): log_dir = ((FLAGS.base_log_dir + '/sup-') + FLAGS.train_prefix.split('/')[(- 2)]) log_dir += '/{model:s}_{model_size:s}_{lr:0.4f}/'.format(model=FLAGS.model, model_size=FLAGS.model_size, lr=FLAGS.learning_rate) if (not os.path.exists(log_dir)): os.makedirs(log_dir) return log_di...
def incremental_evaluate(sess, model, minibatch_iter, size, test=False): t_test = time.time() finished = False val_losses = [] val_preds = [] labels = [] iter_num = 0 finished = False while (not finished): (feed_dict_val, batch_labels, finished, _) = minibatch_iter.incremental_...
def construct_placeholders(num_classes): placeholders = {'labels': tf.placeholder(tf.float32, shape=(None, num_classes), name='labels'), 'batch': tf.placeholder(tf.int32, shape=None, name='batch1'), 'dropout': tf.placeholder_with_default(0.0, shape=(), name='dropout'), 'batch_size': tf.placeholder(tf.int32, name=...
def train(train_data, test_data=None): G = train_data[0] features = train_data[1] id_map = train_data[2] class_map = train_data[4] if isinstance(list(class_map.values())[0], list): num_classes = len(list(class_map.values())[0]) else: num_classes = len(set(class_map.values())) ...
def main(argv=None): print('Loading training data..') train_data = load_data(FLAGS.train_prefix) print('Done loading training data..') train(train_data)
def calc_f1(y_true, y_pred): y_true = np.argmax(y_true, axis=1) y_pred = np.argmax(y_pred, axis=1) return (metrics.f1_score(y_true, y_pred, average='micro'), metrics.f1_score(y_true, y_pred, average='macro'))
def cal_acc(y_true, y_pred): y_true = np.argmax(y_true, axis=1) y_pred = np.argmax(y_pred, axis=1) return metrics.accuracy_score(y_true, y_pred)
class Model(object): def __init__(self, data_config, pretrain_data, args): self.model_type = 'hacud' self.adj_type = args.adj_type self.early_stop = args.early_stop self.pretrain_data = pretrain_data os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu self.n_nodes = data...
def parse_args(): parser = argparse.ArgumentParser(description='Run HACUD.') parser.add_argument('--weights_path', nargs='?', default='', help='Store model path.') parser.add_argument('--data_path', nargs='?', default='../Data/', help='Input data path.') parser.add_argument('--proj_path', nargs='?', d...
class Player2Vec(Algorithm): def __init__(self, session, meta, nodes, class_size, gcn_output1, embedding, encoding): self.meta = meta self.nodes = nodes self.class_size = class_size self.gcn_output1 = gcn_output1 self.embedding = embedding self.encoding = encoding ...
def arg_parser(): parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=123, help='Random seed.') parser.add_argument('--dataset_str', type=str, default='dblp', help="['dblp','example']") parser.add_argument('--epoch_num', type=int, default=30, help='Number of epochs to tr...
def set_env(args): tf.reset_default_graph() np.random.seed(args.seed) tf.set_random_seed(args.seed)
def get_data(ix, int_batch, train_size): if ((ix + int_batch) >= train_size): ix = (train_size - int_batch) end = train_size else: end = (ix + int_batch) return (train_data[ix:end], train_label[ix:end])
def load_data(args): if (args.dataset_str == 'dblp'): (adj_list, features, train_data, train_label, test_data, test_label) = load_data_dblp() node_size = features.shape[0] node_embedding = features.shape[1] class_size = train_label.shape[1] train_size = len(train_data) ...
def train(args, adj_list, features, train_data, train_label, test_data, test_label, paras): with tf.Session() as sess: adj_data = [normalize_adj(adj) for adj in adj_list] meta_size = len(adj_list) net = Player2Vec(session=sess, class_size=paras[2], gcn_output1=args.hidden1, meta=meta_size,...
class SemiGNN(Algorithm): def __init__(self, session, nodes, class_size, semi_encoding1, semi_encoding2, semi_encoding3, init_emb_size, meta, ul, alpha, lamtha): self.nodes = nodes self.meta = meta self.class_size = class_size self.semi_encoding1 = semi_encoding1 self.semi...
def arg_parser(): parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=123, help='Random seed.') parser.add_argument('--dataset_str', type=str, default='example', help="['dblp','example']") parser.add_argument('--epoch_num', type=int, default=30, help='Number of epochs to...
def set_env(args): tf.reset_default_graph() np.random.seed(args.seed) tf.set_random_seed(args.seed)
def get_data(ix, int_batch, train_size): if ((ix + int_batch) >= train_size): ix = (train_size - int_batch) end = train_size else: end = (ix + int_batch) return (train_data[ix:end], train_label[ix:end])
def load_data(args): if (args.dataset_str == 'example'): (adj_list, features, train_data, train_label, test_data, test_label) = load_example_semi() node_size = features.shape[0] node_embedding = features.shape[1] class_size = train_label.shape[1] train_size = len(train_data...
def train(args, adj_list, features, train_data, train_label, test_data, test_label, paras): with tf.Session() as sess: adj_nodelists = [matrix_to_adjlist(adj, pad=False) for adj in adj_list] meta_size = len(adj_list) pairs = [random_walks(adj_nodelists[i], 2, 3) for i in range(meta_size)] ...
class Algorithm(object): def __init__(self, **kwargs): self.nodes = None def forward_propagation(self): pass def save(self, sess=None): if (not sess): raise AttributeError('TensorFlow session not provided.') saver = tf.train.Saver() save_path = saver....
def uniform(shape, scale=0.05, name=None): 'Uniform init.' initial = tf.random_uniform(shape, minval=(- scale), maxval=scale, dtype=tf.float32) return tf.Variable(initial, name=name)
def glorot(shape, name=None): 'Glorot & Bengio (AISTATS 2010) init.' init_range = np.sqrt((6.0 / (shape[0] + shape[1]))) initial = tf.random_uniform(shape, minval=(- init_range), maxval=init_range, dtype=tf.float32) return tf.Variable(initial, name=name)
def zeros(shape, name=None): 'All zeros.' initial = tf.zeros(shape, dtype=tf.float32) return tf.Variable(initial, name=name)
def ones(shape, name=None): 'All ones.' initial = tf.ones(shape, dtype=tf.float32) return tf.Variable(initial, name=name)
def get_layer_uid(layer_name=''): 'Helper function, assigns unique layer IDs.' if (layer_name not in _LAYER_UIDS): _LAYER_UIDS[layer_name] = 1 return 1 else: _LAYER_UIDS[layer_name] += 1 return _LAYER_UIDS[layer_name]
def sparse_dropout(x, keep_prob, noise_shape): 'Dropout for sparse tensors.' random_tensor = keep_prob random_tensor += tf.random_uniform(noise_shape) dropout_mask = tf.cast(tf.floor(random_tensor), dtype=tf.bool) pre_out = tf.sparse_retain(x, dropout_mask) return (pre_out * (1.0 / keep_prob))...
def dot(x, y, sparse=False): 'Wrapper for tf.matmul (sparse vs dense).' if sparse: res = tf.sparse_tensor_dense_matmul(x, y) else: res = tf.matmul(x, y) return res
class Layer(object): 'Base layer class. Defines basic API for all layer objects.\n Implementation inspired by keras (http://keras.io).\n\n # Properties\n name: String, defines the variable scope of the layer.\n logging: Boolean, switches Tensorflow histogram logging on/off\n\n # Methods\n ...
class GraphConvolution(Layer): 'Graph convolution layer.' def __init__(self, input_dim, output_dim, placeholders, index=0, dropout=0.0, sparse_inputs=False, act=tf.nn.relu, bias=False, featureless=False, norm=False, **kwargs): super(GraphConvolution, self).__init__(**kwargs) self.dropout = dr...
class AttentionLayer(Layer): ' AttentionLayer is a function f : hkey × Hval → hval which maps\n a feature vector hkey and the set of candidates’ feature vectors\n Hval to an weighted sum of elements in Hval.\n ' def attention(inputs, attention_size, v_type=None, return_weights=False, bias=True, join...
class ConcatenationAggregator(Layer): "This layer equals to the equation (3) in\n paper 'Spam Review Detection with Graph Convolutional Networks.'\n " def __init__(self, input_dim, output_dim, review_item_adj, review_user_adj, review_vecs, user_vecs, item_vecs, dropout=0.0, act=tf.nn.relu, name=None, c...
class AttentionAggregator(Layer): "This layer equals to equation (5) and equation (8) in\n paper 'Spam Review Detection with Graph Convolutional Networks.'\n " def __init__(self, input_dim1, input_dim2, output_dim, hid_dim, user_review_adj, user_item_adj, item_review_adj, item_user_adj, review_vecs, us...
class GASConcatenation(Layer): 'GCN-based Anti-Spam(GAS) layer for concatenation of comment embedding learned by GCN from the Comment Graph\n and other embeddings learned in previous operations.\n ' def __init__(self, review_item_adj, review_user_adj, review_vecs, item_vecs, user_vecs, homo_vecs, nam...
class GEMLayer(Layer): "This layer equals to the equation (8) in\n paper 'Heterogeneous Graph Neural Networks for Malicious Account Detection.'\n " def __init__(self, placeholders, nodes, device_num, embedding, encoding, name=None, **kwargs): super(GEMLayer, self).__init__(**kwargs) sel...
class GAT(Layer): "This layer is adapted from PetarV-/GAT.'\n " def __init__(self, dim, attn_drop, ffd_drop, bias_mat, n_heads, name=None, **kwargs): super(GAT, self).__init__(**kwargs) self.dim = dim self.attn_drop = attn_drop self.ffd_drop = ffd_drop self.bias_mat...