code stringlengths 17 6.64M |
|---|
class GeniePathLayer(Layer):
"This layer equals to the Adaptive Path Layer in\n paper 'GeniePath: Graph Neural Networks with Adaptive Receptive Paths.'\n The code is adapted from shawnwang-tech/GeniePath-pytorch\n "
def __init__(self, placeholders, nodes, in_dim, dim, heads=1, name=None, **kwargs):
... |
class Model(object):
'Adapted from tkipf/gcn.'
def __init__(self, **kwargs):
allowed_kwargs = {'name', 'logging'}
for kwarg in kwargs.keys():
assert (kwarg in allowed_kwargs), ('Invalid keyword argument: ' + kwarg)
name = kwargs.get('name')
if (not name):
... |
class GCN(Model):
def __init__(self, placeholders, dim1, input_dim, output_dim, index=0, **kwargs):
super(GCN, self).__init__(**kwargs)
self.inputs = placeholders['x']
self.placeholders = placeholders
self.input_dim = input_dim
self.output_dim = output_dim
self.dim... |
def arg_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default='GAS', help="['Player2Vec', 'FdGars','GEM','SemiGNN','GAS','GeniePath']")
parser.add_argument('--seed', type=int, default=123, help='Random seed.')
parser.add_argument('--dataset_str', type=str, defau... |
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('dataset/DBLP4057_GAT_with_idx_tra200_val_800.mat')
node_size = features.shape[0]
node_embedding = features.shape[1]
class_size = train_label.... |
def train(args, adj_list, features, train_data, train_label, test_data, test_label, paras):
with tf.Session() as sess:
if (args.model == 'Player2Vec'):
adj_data = [normalize_adj(adj) for adj in adj_list]
meta_size = len(adj_list)
net = Player2Vec(session=sess, class_siz... |
class Baseline(torch.nn.Module):
def __init__(self, params, num_notes, num_lengths):
super(Baseline, self).__init__()
self.params = params
self.width_reduction = 1
self.height_reduction = 1
for i in range(4):
self.width_reduction = (self.width_reduction * param... |
class RNNDecoder(torch.nn.Module):
def __init__(self, params, num_notes, num_lengths, max_chord_stack):
super(RNNDecoder, self).__init__()
self.params = params
self.width_reduction = 1
self.height_reduction = 1
self.max_chord_stack = max_chord_stack
for i in range(... |
class FlagDecoder(torch.nn.Module):
def __init__(self, params, num_notes, num_durs, num_accs):
super(FlagDecoder, self).__init__()
self.params = params
self.width_reduction = 1
self.height_reduction = 1
self.num_notes = num_notes
self.num_durs = num_durs
se... |
def default_model_params():
params = dict()
params['img_height'] = 128
params['img_width'] = None
params['batch_size'] = 12
params['img_channels'] = 1
params['conv_blocks'] = 4
params['conv_filter_n'] = [32, 64, 128, 256]
params['conv_filter_size'] = [[3, 3], [3, 3], [3, 3], [3, 3]]
... |
def init_weights(m):
if (isinstance(m, torch.nn.Conv2d) or isinstance(m, torch.nn.Linear)):
torch.nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(0)
|
def save_model():
root_model_path = (('models/latest_model' + str(model_num)) + '.pt')
model_dict = nn_model.state_dict()
state_dict = {'model': model_dict, 'optimizer': optimizer.state_dict()}
torch.save(state_dict, root_model_path)
print('Saved model')
|
class Measure():
def __init__(self, measure, num_staves, beats, beat_type):
self.measure = measure
self.num_staves = num_staves
self.beats = beats
self.beat_type = beat_type
def parse_attributes(self, attributes):
'\n Reads through all attributes of a measure \... |
class MusicXML():
def __init__(self, input_file=None, output_file=None):
'\n Stores MusicXML file passed in \n '
self.input_file = input_file
self.output_file = output_file
self.key = ''
self.clef = ''
self.time = ''
self.beat = 4
self... |
def main():
'\n Main method\n '
num_files = 0
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input', type=str, required=('-c' not in sys.argv), help='Path to the input directory with MusicXMLs.')
args = parser.parse_args()
for file_name in os.listdir(args.input):
... |
def main():
'\n Main method\n '
parser = argparse.ArgumentParser()
parser.add_argument('-imgs', dest='imgs', type=str, required=True, help='Path to the directory with imgs.')
parser.add_argument('-labels', dest='labels', type=str, required=True, help='Path to the directory with labels.')
arg... |
def main():
'\n Main method\n '
parser = argparse.ArgumentParser()
parser.add_argument('-poly', dest='poly', type=str, required=True, help='File with list of polyphonic files')
parser.add_argument('-dir', dest='dir', type=str, required=True, help='Path to the directory with labels or images.')
... |
def main():
'\n Main method\n '
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input', type=str, required=('-c' not in sys.argv), help='Path to the directory with images and labels')
args = parser.parse_args()
sparse_count = 0
for file_name in os.listdir(args.inpu... |
def main():
'\n Main method\n '
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input', type=str, required=('-c' not in sys.argv), help='Path to the directory with images.')
args = parser.parse_args()
for file_name in os.listdir(args.input):
if (file_name.endsw... |
class FdGars(keras.Model):
'\n The FdGars model\n '
def __init__(self, input_dim: int, nhid: int, output_dim: int, args: argparse.ArgumentParser().parse_args()) -> None:
'\n :param input_dim: the input feature dimension\n :param nhid: the output embedding dimension of the first GC... |
def FdGars_main(support: list, features: tf.SparseTensor, label: tf.Tensor, masks: list, args: argparse.ArgumentParser().parse_args()) -> None:
'\n Main function to train, val and test the model\n\n :param support: a list of the sparse adjacency matrices\n :param features: node feature tuple for all node... |
class GAS(keras.Model):
'\n The GAS model\n '
def __init__(self, args: argparse.ArgumentParser().parse_args()) -> None:
'\n :param args: argument used by the GAS model\n '
super().__init__()
self.class_size = args.class_size
self.reviews_num = args.reviews_... |
def GAS_main(adj_list: list, r_support: list, features: tf.Tensor, r_feature: tf.SparseTensor, label: tf.Tensor, masks: list, args: argparse.ArgumentParser().parse_args()) -> None:
'\n Main function to train and test the model\n\n :param adj_list:\n a list of Homogeneous graphs and a sparse... |
class GEM(keras.Model):
def __init__(self, input_dim, output_dim, args):
super().__init__()
self.nodes_num = args.nodes_num
self.class_size = args.class_size
self.input_dim = input_dim
self.output_dim = output_dim
self.device_num = args.device_num
self.hop ... |
def GEM_main(supports: list, features: tf.SparseTensor, label: tf.Tensor, masks: list, args) -> None:
'\n :param supports: a list of the sparse adjacency matrix\n :param features: the feature of the sparse tensor for all nodes\n :param label: the label tensor for all nodes\n :param masks: a list of ma... |
class GraphConsis(keras.Model):
'\n The GraphConsis model\n '
def __init__(self, features_dim: int, internal_dim: int, num_layers: int, num_classes: int, num_relations: int) -> None:
'\n :param int features_dim: input dimension\n :param int internal_dim: hidden layer dimension\n ... |
class GraphSage(tf.keras.Model):
'\n GraphSage model\n '
def __init__(self, features_dim, internal_dim, num_layers, num_classes):
'\n :param int features_dim: input dimension\n :param int internal_dim: hidden layer dimension\n :param int num_layers: number of sample layer\n... |
class Player2Vec(keras.Model):
'\n The Player2Vec model\n '
def __init__(self, input_dim: int, nhid: int, output_dim: int, args: argparse.ArgumentParser().parse_args()) -> None:
'\n :param input_dim: the input feature dimension\n :param nhid: the output embedding dimension of the ... |
def Player2Vec_main(support: list, features: tf.SparseTensor, label: tf.Tensor, masks: list, args: argparse.ArgumentParser().parse_args()) -> None:
'\n Main function to train, val and test the model\n\n :param support: a list of the sparse adjacency matrices\n :param features: node feature tuple for all ... |
class SemiGNN(keras.Model):
'\n The SemiGNN model\n '
def __init__(self, nodes: int, class_size: int, semi_encoding1: int, semi_encoding2: int, semi_encoding3: int, init_emb_size: int, view_num: int, alpha: float) -> None:
'\n :param nodes: total nodes number\n :param semi_encodin... |
def SemiGNN_main(adj_list: list, label: tf.Tensor, masks: list, args: argparse.ArgumentParser().parse_args()) -> None:
'\n Main function to train and test the model\n\n :param adj_list: a list of the sparse adjacency matrices\n :param label: the label tensor for all nodes\n :param masks: a list of mas... |
def sparse_dropout(x: tf.SparseTensor, rate: float, noise_shape: int) -> tf.SparseTensor:
'\n Dropout for sparse tensors.\n\n :param x: the input sparse tensor\n :param rate: the dropout rate\n :param noise_shape: the feature dimension\n '
random_tensor = (1 - rate)
random_tensor += tf.rand... |
def dot(x: tf.Tensor, y: tf.Tensor, sparse: bool=False) -> tf.Tensor:
'\n Wrapper for tf.matmul (sparse vs dense).\n\n :param x: first tensor\n :param y: second tensor\n :param sparse: whether the first tensor is of type tf.SparseTensor\n '
if sparse:
res = tf.sparse.sparse_dense_matmul... |
class GraphConvolution(layers.Layer):
'\n Graph convolution layer.\n Source:https://github.com/dragen1860/GCN-TF2/blob/master/layers.py\n\n :param input_dim: the input feature dimension\n :param output_dim: the output dimension (number of classes)\n :param num_features_nonzero: the node feature dim... |
class AttentionLayer(layers.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\n :param input_dim: the input dimension\n :param attention_size: the number of meta_p... |
class NodeAttention(layers.Layer):
' Node level attention for SemiGNN.\n\n :param input_dim: the input dimension\n :param view_num: the number of views\n '
def __init__(self, input_dim: int, **kwargs: Optional) -> None:
super().__init__(**kwargs)
self.H_v = tf.Variable(tf.random.norm... |
class ViewAttention(layers.Layer):
' View level attention implementation for SemiGNN\n\n :param encoding: a list of MLP encoding sizes for each view\n :param layer_size: the number of view attention layer\n :param view_num: the number of views\n '
def __init__(self, encoding: list, la... |
def scaled_dot_product_attention(q: tf.Tensor, k: tf.Tensor, v: tf.Tensor) -> Tuple[(tf.Tensor, tf.Tensor)]:
'\n Obtain attention value in one embedding\n\n :param q: original embedding\n :param k: original embedding\n :param v:embedding after aggregate neighbour feature\n :param mask: whether use ... |
class ConcatenationAggregator(layers.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, dropout=0.0, act=tf.nn.relu, concat=False, **kwargs):
'\n :param input_dim: the dimensio... |
class SageMeanAggregator(layers.Layer):
' GraphSAGE Mean Aggregation Layer\n Parts of this code file were originally forked from\n https://github.com/subbyte/graphsage-tf2\n '
def __init__(self, src_dim, dst_dim, activ=True, **kwargs):
'\n :param int src_dim: input dimension\n ... |
class ConsisMeanAggregator(SageMeanAggregator):
' GraphConsis Mean Aggregation Layer Inherited SageMeanAggregator\n Parts of this code file were originally forked from\n https://github.com/subbyte/graphsage-tf2\n '
def __init__(self, src_dim, dst_dim, **kwargs):
'\n :param int src_dim... |
class AttentionAggregator(layers.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, input_dim3, input_dim4, output_dim, dropout=0.0, bias=False, act=tf.nn.relu, concat=False, **... |
class GASConcatenation(layers.Layer):
'GCN-based Anti-Spam(GAS) layer for concatenation of comment embedding\n learned by GCN from the Comment Graph and other embeddings learned in\n previous operations.\n '
def __init__(self, **kwargs):
super(GASConcatenation, self).__init__(**kwargs)
... |
class GEMLayer(layers.Layer):
"\n This layer equals to the equation (8) in\n paper 'Heterogeneous Graph Neural Networks\n for Malicious Account Detection.'\n "
def __init__(self, nodes_num, input_dim, output_dim, device_num, **kwargs):
super(GEMLayer, self).__init__(**kwargs)
self... |
def load_example_data(meta: bool=False, data: str='dblp') -> Tuple[(list, np.array, list, np.array)]:
"\n Loading the a small handcrafted data for testing\n\n :param meta: if True: it loads a HIN with two meta-graphs,\n if False: it loads a homogeneous graph\n :param data: the example dat... |
def load_data_dblp(path: str='dataset/DBLP4057_GAT_with_idx_tra200_val_800.mat', train_size: int=0.8, meta: bool=True) -> Tuple[(list, np.array, list, np.array)]:
'\n The data loader to load the DBLP heterogeneous information network data\n source: https://github.com/Jhy1993/HAN\n\n :param path: the loca... |
def load_data_yelp(path: str='dataset/YelpChi.mat', train_size: int=0.8, meta: bool=True) -> Tuple[(list, np.array, list, np.array)]:
'\n The data loader to load the Yelp heterogeneous information network data\n source: http://odds.cs.stonybrook.edu/yelpchi-dataset\n\n :param path: the local path of the ... |
def load_example_semi():
'\n The data loader to load the example data for SemiGNN\n '
features = np.array([[1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 1], [1, 0, 1, 1, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1]])
rownetwo... |
def load_data_gas():
'\n The data loader to load the example data for GAS\n\n '
user_review_adj = [[0, 1], [2], [3], [5], [4, 6]]
user_review_adj = pad_adjlist(user_review_adj)
user_item_adj = [[0, 1], [0], [0], [2], [1, 2]]
user_item_adj = pad_adjlist(user_item_adj)
item_review_adj = [[... |
def masked_softmax_cross_entropy(preds: tf.Tensor, labels: tf.Tensor, mask: tf.Tensor) -> tf.Tensor:
'\n Softmax cross-entropy loss with masking.\n\n :param preds: the last layer logits of the input data\n :param labels: the labels of the input data\n :param mask: the mask for train/val/test data\n ... |
def masked_accuracy(preds: tf.Tensor, labels: tf.Tensor, mask: tf.Tensor) -> tf.Tensor:
'\n Accuracy with masking.\n\n :param preds: the class prediction probabilities of the input data\n :param labels: the labels of the input data\n :param mask: the mask for train/val/test data\n '
correct_pre... |
def accuracy(preds: tf.Tensor, labels: tf.Tensor) -> tf.Tensor:
'\n Accuracy.\n\n :param preds: the class prediction probabilities of the input data\n :param labels: the labels of the input data\n '
correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1))
accuracy_all = tf.cast... |
def eval_other_methods(x, y, names=None):
gmm = mixture.GaussianMixture(covariance_type='full', n_components=args.n_clusters, random_state=0)
gmm.fit(x)
y_pred_prob = gmm.predict_proba(x)
y_pred = y_pred_prob.argmax(1)
acc = np.round(cluster_acc(y, y_pred), 5)
nmi = np.round(metrics.normalized... |
def cluster_manifold_in_embedding(hl, y, label_names=None):
if (args.manifold_learner == 'UMAP'):
md = float(args.umap_min_dist)
hle = umap.UMAP(random_state=0, metric=args.umap_metric, n_components=args.umap_dim, n_neighbors=args.umap_neighbors, min_dist=md).fit_transform(hl)
elif (args.manif... |
def best_cluster_fit(y_true, y_pred):
y_true = y_true.astype(np.int64)
D = (max(y_pred.max(), y_true.max()) + 1)
w = np.zeros((D, D), dtype=np.int64)
for i in range(y_pred.size):
w[(y_pred[i], y_true[i])] += 1
ind = linear_assignment((w.max() - w))
best_fit = []
for i in range(y_pr... |
def cluster_acc(y_true, y_pred):
(_, ind, w) = best_cluster_fit(y_true, y_pred)
return ((sum([w[(i, j)] for (i, j) in ind]) * 1.0) / y_pred.size)
|
def plot(x, y, plot_id, names=None):
viz_df = pd.DataFrame(data=x[:5000])
viz_df['Label'] = y[:5000]
if (names is not None):
viz_df['Label'] = viz_df['Label'].map(names)
viz_df.to_csv((((args.save_dir + '/') + args.dataset) + '.csv'))
plt.subplots(figsize=(8, 5))
sns.scatterplot(x=0, y... |
def autoencoder(dims, act='relu'):
n_stacks = (len(dims) - 1)
x = Input(shape=(dims[0],), name='input')
h = x
for i in range((n_stacks - 1)):
h = Dense(dims[(i + 1)], activation=act, name=('encoder_%d' % i))(h)
h = Dense(dims[(- 1)], name=('encoder_%d' % (n_stacks - 1)))(h)
for i in ra... |
def visualize_graph(graph, path, og_set=None):
g = ig.Graph(len(graph), list(zip(*list(zip(*nx.to_edgelist(graph)))[:2])), directed=True)
layout = g.layout('kk')
visual_style = {'vertex_size': 10, 'vertex_color': '#AAAAFF', 'edge_width': 1, 'arrow_size': 0.01, 'vertex_label': range(g.vcount()), 'layout': ... |
def remap_graph(graph):
node_index = 0
node_mapping = {}
remapped_graph = nx.DiGraph()
for node in graph.nodes():
node_mapping[node] = node_index
node_index += 1
for (n1, n2) in graph.edges():
n1 = node_mapping[n1]
n2 = node_mapping[n2]
remapped_graph.add_ed... |
def create_fcg_graph(dex_path):
save_path = dex_path.replace('apk_files', 'graph_files').replace('.apk', '.edgelist')
if (not os.path.exists(save_path)):
os.makedirs(os.path.dirname(save_path), exist_ok=True)
try:
(a, d, dx) = AnalyzeAPK(dex_path)
cg = dx.get_call_graph... |
def main():
print('Constructing FCG Dataset')
apk_files = glob(os.path.join(os.getcwd(), 'apk_files/*.apk'))
Parallel(n_jobs=1)((delayed(create_fcg_graph)(apk_path) for apk_path in tqdm(apk_files)))
|
def run_method(idx, args, file, method):
if (method == 'sf'):
graph = process_file_karate(file)
result = sf(graph, args['n_eigen'])
elif (method == 'ldp'):
subgraphs = process_file_karate(file)
result = ldp(subgraphs)
elif (method == 'fgsd'):
graph = process_file_ka... |
def get_kernel_embedding(args, train_files, val_files, test_files):
print('\n******Running WL Kernel on train set******')
gk = GraphKernel(kernel=[{'name': 'weisfeiler_lehman', 'n_iter': args['n_iter']}, 'subtree_wl'], normalize=True, n_jobs=args['n_cores'])
graphs = Parallel(n_jobs=args['n_cores'])((dela... |
def get_embedding(args, files, run_type):
print('\n******Running {} on {} set******'.format(args['method'], run_type))
embedding = Parallel(n_jobs=args['n_cores'])((delayed(run_method)(idx, args, file, args['method']) for (idx, file) in enumerate(tqdm(files))))
embedding = np.asarray(embedding)
if (le... |
def warn(*args, **kwargs):
pass
|
def run_experiment(args_og, files_train, files_val, files_test, y_train, y_val, y_test, train_ratios, wl_train_ratios):
args = copy.deepcopy(args_og)
result = []
if (args['method'] != 'wl'):
start = time.time()
(x_train, x_val, x_test) = (get_embedding(args, files_train, run_type='train'),... |
def run_param_search():
from config import args as args
args.update({'metric': 'macro-F1', 'train_ratio': 1.0, 'val_ratio': 0.1, 'test_ratio': 0.2, 'malnet_tiny': False})
groups = ['type', 'family']
results = []
for group in groups:
args['group'] = group
(files_train, files_val, fi... |
def run_best_params():
from config import args as args
args.update({'metric': 'macro-F1', 'group': 'type', 'train_ratio': 1.0, 'val_ratio': 0.1, 'test_ratio': 0.2, 'malnet_tiny': False})
(files_train, files_val, files_test, y_train, y_val, y_test, label_dict) = get_split_info(args)
args['class_labels'... |
def ldp(graph):
model = LDP()
model._check_graphs([graph])
embedding = model._calculate_ldp(graph)
return embedding
|
def feather(graph, order=5):
model = FeatherGraph(order=order)
model._set_seed()
model._check_graphs([graph])
embedding = model._calculate_feather(graph)
return embedding
|
def ige(graph, max_deg):
model = IGE()
model._set_seed()
model._check_graphs([graph])
model.max_deg = max_deg
embedding = model._calculate_invariant_embedding(graph)
return embedding
|
def fgsd(graph):
model = FGSD()
model._set_seed()
model._check_graphs([graph])
embedding = model._calculate_fgsd(graph)
return embedding
|
def lsd(graph):
model = NetLSD()
model._set_seed()
model._check_graphs([graph])
embedding = model._calculate_netlsd(graph)
return embedding
|
def sf(graph, n_eigenvalues=128):
model = SF(dimensions=n_eigenvalues)
model._set_seed()
model._check_graphs([graph])
embedding = model._calculate_sf(graph)
return embedding
|
def geo_scattering(graph, order=4):
model = GeoScattering(order=order)
model._set_seed()
model._check_graphs([graph])
embedding = model._calculate_geoscattering(graph)
return embedding
|
def g2v_document(idx, graph):
model = Graph2Vec()
model._set_seed()
model._check_graphs([graph])
document = WeisfeilerLehmanHashing(graph, model.wl_iterations, model.attributed, model.erase_base_features)
document = TaggedDocument(words=document.get_graph_features(), tags=str(idx))
return docu... |
def g2v(documents):
from tqdm import tqdm
model = Doc2Vec(documents)
embedding = [model.docvecs[str(i)] for (i, _) in enumerate(tqdm(documents))]
return np.array(embedding)
|
def warn(*args, **kwargs):
pass
|
def process_file_karate(file):
g = nx.read_edgelist(file)
gcc = sorted(nx.connected_components(g), key=len, reverse=True)
g = g.subgraph(gcc[0])
g = nx.convert_node_labels_to_integers(g)
return g
|
def process_file_nog(file):
return nx.read_edgelist(file)
|
def process_file_slaq(file):
g = nx.read_edgelist(file)
g = nx.convert_node_labels_to_integers(g)
adj = nx.to_scipy_sparse_matrix(g, dtype=np.float32, format='csr')
adj.data = np.ones(adj.data.shape, dtype=np.float32)
return adj
|
def process_file_grakel(file):
g = nx.read_edgelist(file)
gcc = sorted(nx.connected_components(g), key=len, reverse=True)
g = g.subgraph(gcc[0])
g = nx.convert_node_labels_to_integers(g)
nx.set_node_attributes(g, 'a', 'label')
return list(graph_from_networkx([g], node_labels_tag='label', as_Gr... |
def chunker(seq, size):
return (seq[pos:(pos + size)] for pos in range(0, len(seq), size))
|
def kernel_transform(args, files, gk):
chunk_size = 1000
pbar = tqdm(total=len(files))
for (idx, files) in enumerate(chunker(files, chunk_size)):
graphs = Parallel(n_jobs=args['n_cores'])((delayed(process_file_grakel)(file) for file in files))
data = gk.transform(graphs)
if (idx ==... |
class MalnetDataset(Dataset):
def __init__(self, args, root, files, labels, transform=None, pre_transform=None):
self.args = args
self.files = files
self.labels = labels
self.num_classes = len(np.unique(labels))
super(MalnetDataset, self).__init__(root, transform, pre_tran... |
def model_search(gpu, malnet_tiny, group, metric, epochs, model, K, num_layers, hidden_dim, lr, dropout, train_ratio):
from config import args
args.update({'gpu': gpu, 'batch_size': 64, 'node_feature': 'ldp', 'directed_graph': True, 'remove_isolates': False, 'lcc_only': False, 'add_self_loops': True, 'model':... |
def preprocess_search(gpu, epochs, node_feature, directed_graph, remove_isolates, lcc_only, add_self_loops, model='gcn', K=0, hidden_dim=32, num_layers=3, lr=0.0001, dropout=0):
from config import args
args.update({'gpu': gpu, 'batch_size': 128, 'node_feature': node_feature, 'directed_graph': directed_graph, ... |
def search_all_preprocess():
epochs = 1000
gpus = [0, 1, 2, 3, 4, 5, 6, 7]
Parallel(n_jobs=len(gpus))((delayed(preprocess_search)(gpus[idx], epochs, node_feature=feature, directed_graph=True, remove_isolates=True, lcc_only=False, add_self_loops=False) for (idx, feature) in enumerate(tqdm(['ldp', 'constant... |
def search_all_models():
gpus = [2]
models = ['gin']
layers = [5]
hidden_dims = [64]
learning_rates = [0.0001]
dropouts = [0]
epochs = 500
metric = 'macro-F1'
groups = ['family']
malnet_tiny = False
train_ratios = [1.0]
combinations = list(itertools.product(*[groups, mo... |
def run_best_models():
epochs = 500
gpus = [2, 3, 4, 5]
metric = 'macro-F1'
group = 'family'
malnet_tiny = True
combinations = [['gin', 0, 3, 64, 0.001, 0.5]]
results = Parallel(n_jobs=len(combinations))((delayed(model_search)(gpus[(idx % len(gpus))], malnet_tiny, group, metric, epochs, mo... |
class GIN(torch.nn.Module):
def __init__(self, args):
super(GIN, self).__init__()
self.args = args
self.layers = torch.nn.ModuleList([])
for i in range((args['num_layers'] + 1)):
dim_input = (args['num_features'] if (i == 0) else args['hidden_dim'])
nn = Se... |
class MLP(torch.nn.Module):
def __init__(self, args):
super(MLP, self).__init__()
self.args = args
self.layers = torch.nn.ModuleList([])
for i in range((args['num_layers'] + 1)):
dim_input = (args['num_features'] if (i == 0) else args['hidden_dim'])
dim_out... |
class GraphSAGE(torch.nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
self.layers = torch.nn.ModuleList([])
for i in range((args['num_layers'] + 1)):
dim_input = (args['num_features'] if (i == 0) else args['hidden_dim'])
conv = SAG... |
class GCN(torch.nn.Module):
def __init__(self, args):
super(GCN, self).__init__()
self.args = args
self.layers = torch.nn.ModuleList([])
for i in range((args['num_layers'] + 1)):
dim_input = (args['num_features'] if (i == 0) else args['hidden_dim'])
conv = ... |
class SGC(torch.nn.Module):
def __init__(self, args):
super(SGC, self).__init__()
self.args = args
self.layers = torch.nn.ModuleList([])
for i in range((args['num_layers'] + 1)):
dim_input = (args['num_features'] if (i == 0) else args['hidden_dim'])
conv = ... |
def process_file(args, idx, file, processed_dir, pre_transform):
if args['directed_graph']:
graph = nx.read_edgelist(file, create_using=nx.DiGraph)
else:
graph = nx.read_edgelist(file)
if args['lcc_only']:
graph = graph.subgraph(sorted(nx.connected_components(graph), key=len, rever... |
def convert_files_pytorch(args, files, processed_dir, pre_transform):
if (len(glob((processed_dir + '*.pt'))) != len(files)):
os.makedirs(processed_dir, exist_ok=True)
Parallel(n_jobs=args['n_cores'])((delayed(process_file)(args, idx, file, processed_dir, pre_transform) for (idx, file) in enumerat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.