repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
TIP-GNN | TIP-GNN-main/data_unify.py | import argparse
import logging
import os
import time
from datetime import datetime
import dgl
import numpy as np
import pandas as pd
from data_util import _iterate_datasets, _load_data
from utils import set_random_seed
def data_stats(project_dir="data/format_data/"):
# nodes, edges, d_avg, d_max, timespan(days)... | 9,048 | 41.886256 | 310 | py |
TIP-GNN | TIP-GNN-main/utils.py | import logging
import os
import random
import time
from datetime import datetime
import numpy as np
import torch
def set_random_seed(seed=42):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backend... | 10,490 | 37.01087 | 172 | py |
TIP-GNN | TIP-GNN-main/module.py | import logging
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class MergeLayer(torch.nn.Module):
def __init__(self, dim1, dim2, dim3, dim4):
super().__init__()
#self.layer_norm = torch.nn.LayerNorm(dim1 + dim2)
self.fc1 = torch.nn.Linear(dim1 + dim2... | 21,597 | 35.483108 | 108 | py |
TIP-GNN | TIP-GNN-main/graph.py | import argparse
import dgl
import logging
import math
from numba import jit
import numpy as np
import os
import torch
import time
from tqdm import trange
from preprocess import load_data_var, init_adj, interaction2subgraph, subgraph_np, subgraph_dgl
def make_label_data(src_l, dst_l, ts_l, val_flag, rand_sampler):
... | 18,336 | 35.310891 | 100 | py |
TIP-GNN | TIP-GNN-main/data_processing.py | import numpy as np
import random
import pandas as pd
class Data:
def __init__(self, sources, destinations, timestamps, edge_idxs, labels):
self.sources = sources
self.destinations = destinations
self.timestamps = timestamps
self.edge_idxs = edge_idxs
self.labels = labels
self.n_interactions ... | 8,578 | 45.372973 | 108 | py |
TIP-GNN | TIP-GNN-main/data_util.py | import numpy as np
import os
import pandas as pd
from random import shuffle
def _load_data(dataset="JODIE-reddit", mode="format_data", root_dir="data/"):
edges = pd.read_csv("{}/{}/{}.edges".format(root_dir, mode, dataset))
nodes = pd.read_csv("{}/{}/{}.nodes".format(root_dir, mode, dataset))
return edges... | 4,536 | 40.245455 | 90 | py |
TIP-GNN | TIP-GNN-main/sampling.py | import numpy as np
from numba import jit
@jit
def find_before_nb(src_idx, cut_time, node_idx_l, node_ts_l, edge_idx_l,
off_set_l):
"""
Params
------
src_idx: int
cut_time: float
"""
neighbors_idx = node_idx_l[off_set_l[src_idx]:off_set_l[src_idx + 1]]
neighbors_ts ... | 6,584 | 34.403226 | 100 | py |
TIP-GNN | TIP-GNN-main/inductive_util.py | import argparse
from collections import defaultdict
from joblib import Parallel, delayed
import multiprocessing
import networkx as nx
import numpy as np
import pandas as pd
import scipy
from data_util import load_data, _iterate_datasets
from utils import set_logger, set_random_seed
def load_indudctive_data(dataset):
... | 4,634 | 39.657895 | 123 | py |
TIP-GNN | TIP-GNN-main/subgnn_np.py | import logging
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from graph import batch_interaction2subgraph
from mlp import MLP
from module import TimeEncode, MapBasedMultiHeadAttention, MultiHeadAttention, TGAN, MergeLayer
class SimpleAttention(torch.nn.Module):
"""Varian... | 13,685 | 39.853731 | 107 | py |
TIP-GNN | TIP-GNN-main/preprocess.py | import argparse
import os
import pickle
import dgl
import numpy as np
import numba
import pandas as pd
import torch
from tqdm import trange
from data_util import _iterate_datasets, load_data, load_split_edges
from utils import timeit
def load_data_var(dataset, task="node"):
if task == "node":
# For node... | 9,510 | 37.506073 | 81 | py |
CP-Flow | CP-Flow-main/train_ot.py | # -*- coding: utf-8 -*-
"""
Learning the optimal transport map (between Gaussians) via CP-Flow (comparing to IAF)
"""
import gc
from scipy import linalg
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import torch
from lib.flows import SequentialFlow, DeepConvexFlow, LinearIAF
from lib.icnn import... | 6,547 | 28.102222 | 113 | py |
CP-Flow | CP-Flow-main/train_toy.py | # -*- coding: utf-8 -*-
"""
CP-Flow on toy distributions
"""
import gc
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import torch
from lib.flows import SequentialFlow, DeepConvexFlow, ActNorm, IAF, InvertibleLinear, NAFDSF
from lib.icnn import ICNN3
from lib import dis... | 12,771 | 29.628297 | 115 | py |
CP-Flow | CP-Flow-main/train_vae.py | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
taken from sylvester flows
https://github.com/riannevdberg/sylvester-flows/blob/master/main_experiment.py
"""
from __future__ import print_function
import argparse
import time
import torch
import torch.utils.data
import torch.optim as optim
import numpy as np
import m... | 15,968 | 44.23796 | 120 | py |
CP-Flow | CP-Flow-main/train_toy_cond.py | # -*- coding: utf-8 -*-
"""
CP-Flow on toy conditional distributions
"""
import gc
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import torch
from lib.flows import SequentialFlow, DeepConvexFlow, ActNorm
from lib.icnn import PICNN as PICNN
from data.toy_data import OneDMixtureOfGaussians as ... | 2,984 | 23.467213 | 101 | py |
CP-Flow | CP-Flow-main/train_img.py | import argparse
from functools import partial
import datetime
import time
import math
import sys
import os
import os.path
import numpy as np
from tqdm import tqdm
import gc
import torch
import torch.nn as nn
import torch.distributed as dist
import torch.multiprocessing as mp
# noinspection PyPep8Naming
from torch.nn.p... | 19,024 | 32.973214 | 120 | py |
CP-Flow | CP-Flow-main/train_tabular.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from contextlib import contextmanager
import gc
import math
import random
import os
import time
import warnings
import numpy
import torch
from tqdm import tqdm
import lib.datasets as datasets
import lib.utils as utils
import lib.flows as flows
from lib.fl... | 15,538 | 37.558313 | 114 | py |
CP-Flow | CP-Flow-main/data/toy_data.py | from sklearn.datasets import make_swiss_roll
import torch
import numpy as np
from torch.utils.data import Dataset as Dataset
from lib.distributions import log_normal
from scipy.stats import wishart
from sklearn.utils import shuffle as util_shuffle
class ToyDataset(Dataset):
data = dict()
data_names = []
... | 5,921 | 32.269663 | 112 | py |
CP-Flow | CP-Flow-main/lib/distributions.py | import torch
import numpy as np
Log2PI = float(np.log(2 * np.pi))
def log_normal(x, mean, log_var, eps=0.00001):
z = - 0.5 * Log2PI
return - (x - mean) ** 2 / (2. * torch.exp(log_var) + eps) - log_var / 2. + z
def log_standard_normal(x):
z = - 0.5 * Log2PI
return - x ** 2 / 2 + z
| 302 | 19.2 | 81 | py |
CP-Flow | CP-Flow-main/lib/test_made.py | import numpy as np
import torch
from lib.made import MADE
# run a quick and dirty test for the autoregressive property
D = 10
rng = np.random.RandomState(14)
x = (rng.rand(1, D) > 0.5).astype(np.float32)
configs = [
(D, [], D, False), # test various hidden sizes
(D, [200], D, False),
(D, [200, 220], D, F... | 1,427 | 30.733333 | 93 | py |
CP-Flow | CP-Flow-main/lib/made.py | """
Copy from https://github.com/karpathy/pytorch-made/blob/master/made.py
Implements Masked AutoEncoder for Density Estimation, by Germain et al. 2015
Re-implementation by Andrej Karpathy based on https://arxiv.org/abs/1502.03509
"""
import numpy as np
import torch
import torch.nn as nn
# noinspection PyPep8Naming
i... | 5,760 | 36.901316 | 113 | py |
CP-Flow | CP-Flow-main/lib/functional.py | import torch
import torch.nn as nn
import numpy as np
DELTA = 1e-7
def softplus(x):
return nn.functional.softplus(x) + DELTA
def sigmoid(x):
return torch.sigmoid(x) * (1-DELTA) + 0.5 * DELTA
def logsigmoid(x):
return -softplus(-x)
def log(x):
return torch.log(x*1e2)-np.log(1e2)
def logit(x):
... | 1,054 | 16.583333 | 57 | py |
CP-Flow | CP-Flow-main/lib/utils.py | import os
import logging
import torch
def makedirs(dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)
# noinspection PyDefaultArgument
def get_logger(logpath, package_files=[], displaying=True, saving=True, debug=False):
logger = logging.getLogger()
if debug:
level = logging.... | 4,079 | 28.142857 | 105 | py |
CP-Flow | CP-Flow-main/lib/icnn.py | import torch
# noinspection PyPep8Naming
from torch import nn, Tensor
import torch.nn.init as init
# noinspection PyPep8Naming
import torch.nn.functional as F
import numpy as np
from lib.flows.flows import ActNormNoLogdet
from lib.functional import log_sum_exp
def symm_softplus(x, softplus_=torch.nn.functional.softpl... | 39,700 | 35.658356 | 110 | py |
CP-Flow | CP-Flow-main/lib/naf.py | # noinspection PyPep8Naming
from torch.nn import functional as F
from lib.functional import *
def sigmoid_flow(x, logdet=0, ndim=4, params=None, delta=DELTA, logit_end=True):
"""
element-wise sigmoidal flow described in `Neural Autoregressive Flows` (https://arxiv.org/pdf/1804.00779.pdf)
:param x: input
... | 1,668 | 38.738095 | 113 | py |
CP-Flow | CP-Flow-main/lib/logdet_estimators.py | import numpy as np
import torch
# noinspection PyPep8Naming
import torch.nn.functional as F
EPS = 1e-7
CG_ITERS_TRACER = list()
# noinspection PyPep8Naming
def gram_schmidt_ortho(Q, v, tol=1e-5):
"""
Orthogonalizes v wrt the rows vectors in Q.
Assumes row vectors in Q are orthogonal and have unit Euclid... | 7,254 | 30.004274 | 115 | py |
CP-Flow | CP-Flow-main/lib/multiscale_flow.py | import numpy as np
import torch
import torch.nn as nn
from lib.flows import SequentialFlow, ActNorm, SqueezeLayer, Invertible1x1Conv
class MultiscaleFlow(nn.Module):
""" Creates a stack of flow blocks with squeeze / factor out.
Main arg:
block_fn: Function that takes a 3D input shape (c, h, w) and a ... | 7,015 | 33.22439 | 113 | py |
CP-Flow | CP-Flow-main/lib/flows/cpflows.py | import torch
# noinspection PyPep8Naming
import torch.nn.functional as nnF
from functools import partial
import numpy as np
from lib.logdet_estimators import stochastic_lanczos_quadrature, \
unbiased_logdet, stochastic_logdet_gradient_estimator, CG_ITERS_TRACER
import gc
import warnings
HESS_NORM_TRACER = list()
... | 7,625 | 38.512953 | 119 | py |
CP-Flow | CP-Flow-main/lib/flows/elemwise.py | import math
import torch
import torch.nn as nn
# noinspection PyUnusedLocal
class LogitTransform(nn.Module):
"""
The proprocessing step used in Real NVP:
y = sigmoid(x) - a / (1 - 2a)
x = logit(a + (1 - 2a)*y)
"""
def __init__(self, alpha):
nn.Module.__init__(self)
self.alpha ... | 1,120 | 28.5 | 86 | py |
CP-Flow | CP-Flow-main/lib/flows/__init__.py | from lib.flows.flows import *
from lib.flows.cpflows import *
from lib.flows.elemwise import LogitTransform
from lib.flows.coupling import MaskedCouplingBlock
| 159 | 31 | 50 | py |
CP-Flow | CP-Flow-main/lib/flows/coupling.py | import torch
import torch.nn as nn
__all__ = ['MaskedCouplingBlock']
# noinspection PyUnusedLocal, PyMethodMayBeStatic
class MaskedCouplingBlock(nn.Module):
"""Coupling layer for images implemented using masks.
"""
def __init__(self, dim, nnet, mask_type='checkerboard0'):
nn.Module.__init__(self... | 2,787 | 26.067961 | 80 | py |
CP-Flow | CP-Flow-main/lib/flows/flows.py | import numpy as np
# noinspection PyPep8Naming
import torch.nn.functional as F
import torch.nn as nn
import torch
from lib.distributions import log_standard_normal
from lib.flows import cpflows
from lib.made import MADE, CMADE
from lib.naf import sigmoid_flow
_scaling_min = 0.001
# noinspection PyUnusedLocal
class ... | 14,030 | 32.091981 | 119 | py |
CP-Flow | CP-Flow-main/lib/datasets/power.py | """
Copyright (c) 2017, George Papamakarios
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the f... | 3,488 | 32.873786 | 108 | py |
CP-Flow | CP-Flow-main/lib/datasets/hepmass.py | """
Copyright (c) 2017, George Papamakarios
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the f... | 4,235 | 34.596639 | 112 | py |
CP-Flow | CP-Flow-main/lib/datasets/gas.py | """
Copyright (c) 2017, George Papamakarios
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the f... | 3,196 | 30.653465 | 79 | py |
CP-Flow | CP-Flow-main/lib/datasets/bsds300.py | """
Copyright (c) 2017, George Papamakarios
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the f... | 2,187 | 33.730159 | 79 | py |
CP-Flow | CP-Flow-main/lib/datasets/miniboone.py | """
Copyright (c) 2017, George Papamakarios
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the f... | 3,479 | 34.510204 | 96 | py |
CP-Flow | CP-Flow-main/lib/datasets/__init__.py | import torch
import torchvision.datasets as vdsets
from .power import POWER
from .gas import GAS
from .hepmass import HEPMASS
from .miniboone import MINIBOONE
from .bsds300 import BSDS300
root = 'data/'
class Dataset(object):
def __init__(self, loc, transform=None, in_mem=True):
self.in_mem = in_mem
... | 2,997 | 25.069565 | 116 | py |
CP-Flow | CP-Flow-main/lib/sylvester/__init__.py | 0 | 0 | 0 | py | |
CP-Flow | CP-Flow-main/lib/sylvester/models/VAE.py | from __future__ import print_function
import torch
import torch.nn as nn
from torch.autograd import Variable
from lib.sylvester.models import flows
from lib.sylvester.models.layers import GatedConv2d, GatedConvTranspose2d
from lib.flows import DeepConvexFlow, SequentialFlow, LayerActnorm
from lib.icnn import PICNNAbst... | 28,518 | 33.113636 | 124 | py |
CP-Flow | CP-Flow-main/lib/sylvester/models/layers.py | import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import numpy as np
import torch.nn.functional as F
class Identity(nn.Module):
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x
class GatedConv2d(nn.Module):
def __init__(self, ... | 7,149 | 34.04902 | 115 | py |
CP-Flow | CP-Flow-main/lib/sylvester/models/__init__.py | 0 | 0 | 0 | py | |
CP-Flow | CP-Flow-main/lib/sylvester/models/flows.py | """
Collection of flow strategies
"""
from __future__ import print_function
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from lib.sylvester.models.layers import MaskedConv2d, MaskedLinear
class Planar(nn.Module):
"""
PyTorch implementation of planar... | 9,953 | 32.18 | 118 | py |
CP-Flow | CP-Flow-main/lib/sylvester/optimization/loss.py | from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from lib.sylvester.utils.distributions import log_normal_diag, log_normal_standard, log_bernoulli
import torch.nn.functional as F
def binary_loss_function(recon_x, x, z_mu, z_var, z_0, z_k,... | 10,517 | 37.669118 | 114 | py |
CP-Flow | CP-Flow-main/lib/sylvester/optimization/training.py | from __future__ import print_function
import torch
import gc
from torch.autograd import Variable
from lib.sylvester.optimization.loss import calculate_loss
from lib.sylvester.utils.visual_evaluation import plot_reconstructions
from lib.sylvester.utils.log_likelihood import calculate_likelihood
import numpy as np
de... | 6,267 | 32.340426 | 120 | py |
CP-Flow | CP-Flow-main/lib/sylvester/optimization/__init__.py | 0 | 0 | 0 | py | |
CP-Flow | CP-Flow-main/lib/sylvester/utils/distributions.py | from __future__ import print_function
import torch
import torch.utils.data
from torch.autograd import Variable
import math
MIN_EPSILON = 1e-5
MAX_EPSILON = 1.-1e-5
PI = Variable(torch.FloatTensor([math.pi]))
PI.requires_grad = False
if torch.cuda.is_available():
PI = PI.cuda()
# N(x | mu, var) = 1/sqrt{2pi var}... | 1,837 | 25.257143 | 86 | py |
CP-Flow | CP-Flow-main/lib/sylvester/utils/plotting.py | from __future__ import division
from __future__ import print_function
import numpy as np
import matplotlib
# noninteractive background
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def plot_training_curve(train_loss, validation_loss, fname='training_curve.pdf', labels=None):
"""
Plots train_loss and ... | 4,019 | 37.285714 | 106 | py |
CP-Flow | CP-Flow-main/lib/sylvester/utils/log_likelihood.py | from __future__ import print_function
import numpy as np
from scipy.special import logsumexp
from lib.sylvester.optimization.loss import calculate_loss_array
def calculate_likelihood(X, model, args, S=5000, MB=500):
# set auxiliary variables for number of training and test sets
N_test = X.size(0)
X = X.... | 1,492 | 25.192982 | 83 | py |
CP-Flow | CP-Flow-main/lib/sylvester/utils/load_data.py | from __future__ import print_function
import torch
import torch.utils.data as data_utils
import pickle
from scipy.io import loadmat
import numpy as np
import os
def load_static_mnist(args, **kwargs):
"""
Dataloading function for static mnist. Outputs image data in vectorized form: each image is a vector of... | 7,640 | 35.913043 | 120 | py |
CP-Flow | CP-Flow-main/lib/sylvester/utils/__init__.py | 0 | 0 | 0 | py | |
CP-Flow | CP-Flow-main/lib/sylvester/utils/visual_evaluation.py | from __future__ import print_function
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def plot_reconstructions(data, recon_mean, loss, loss_type, epoch, args):
if args.input_type == 'multinomial':
# data is already between 0 and 1
... | 2,100 | 35.859649 | 109 | py |
DIMES | DIMES-main/TSP/TSP-Full/train.py | from tqdm import tqdm
import numpy as np
import pandas as pd
import torch
from torch import optim
from torch import nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
import matplotlib.collections as mc
import seaborn as sns
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def row... | 10,498 | 40.828685 | 192 | py |
DIMES | DIMES-main/TSP/TSP-KNN/test_AS_MCTS.py | from inc.tsp_args import *
from inc.tsp_core import *
args = args_init()
save_name = args.save_name
print(save_name)
mcts_dir = 'MCTS_500_1000' if args.n_nodes <= 1000 else 'MCTS_10000'
# load net
net = Net(args).to(args.device)
net.load_state_dict(torch.load(f'{save_name}~net{args.te_net}.pt', map_location = args.d... | 2,366 | 39.118644 | 118 | py |
DIMES | DIMES-main/TSP/TSP-KNN/test_AS_G.py | from inc.tsp_args import *
from inc.tsp_core import *
args = args_init()
save_name = args.save_name
print(save_name)
# load net
net = Net(args).to(args.device)
net.load_state_dict(torch.load(f'{save_name}~net{args.te_net}.pt', map_location = args.device))
# load data
x_list = torch.tensor(np.load(f'../data/test-{arg... | 817 | 33.083333 | 118 | py |
DIMES | DIMES-main/TSP/TSP-KNN/test_AS_S.py | from inc.tsp_args import *
from inc.tsp_core import *
args = args_init()
save_name = args.save_name
print(save_name)
# load net
net = Net(args).to(args.device)
net.load_state_dict(torch.load(f'{save_name}~net{args.te_net}.pt', map_location = args.device))
# load data
x_list = torch.tensor(np.load(f'../data/test-{arg... | 819 | 33.166667 | 118 | py |
DIMES | DIMES-main/TSP/TSP-KNN/train.py | from inc.tsp_args import *
from inc.tsp_core import *
args = args_init()
save_name = args.save_name
print(save_name)
net = Net(args).to(args.device)
net = net_train(args, net, verbose = True, save_name = save_name) | 216 | 23.111111 | 65 | py |
DIMES | DIMES-main/TSP/TSP-KNN/inc/header.py | import gc
import os
import os.path as osp
from copy import copy, deepcopy
import time
import random
from tqdm import tqdm, trange
import numpy as np
import pandas as pd
import torch
from torch import nn, optim
import torch.nn.functional as F
import torch_geometric as pyg
import torch_geometric.nn as gnn
import mat... | 420 | 15.84 | 32 | py |
DIMES | DIMES-main/TSP/TSP-KNN/inc/tsp_utils.py | from inc.header import *
from inc.utils import *
__TSP_VERSION__ = 1.1
# generate save_name
def tsp_save_name(args, save_name = None):
if not save_name:
timestamp = int(time.time() * 100)
save_name = f'dimes-tsp{num_abbr(args.n_nodes)}-knn{args.knn_k}@{timestamp}'
return osp.join(args.output_d... | 3,008 | 41.985714 | 130 | py |
DIMES | DIMES-main/TSP/TSP-KNN/inc/tsp_args.py | import argparse
from inc.utils import *
from inc.tsp_utils import *
def args_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type = int, help = 'random seed')
parser.add_argument('--device', type = str, help = 'device for torch')
parser.add_argument('--n_nodes', type = int, ... | 4,098 | 54.391892 | 131 | py |
DIMES | DIMES-main/TSP/TSP-KNN/inc/utils.py | from inc.header import *
# assert with custom exception class
def assert_(cond, cls, *args, **kwargs):
if not cond:
raise cls(*args, **kwargs)
class Dict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__dict__ = self
# preprocess instance graphs
cla... | 3,639 | 35.767677 | 116 | py |
DIMES | DIMES-main/TSP/TSP-KNN/inc/tsp_nets.py | from inc.header import *
from inc.tsp_utils import *
# GNN for edge embeddings
class EmbNet(nn.Module):
@classmethod
def make(cls, args):
return cls(args.emb_depth, 2, args.net_units, args.net_act_fn, args.emb_agg_fn).to(args.device)
def __init__(self, depth, feats, units, act_fn, agg_fn):
... | 4,551 | 38.929825 | 123 | py |
DIMES | DIMES-main/TSP/TSP-KNN/inc/__init__.py | #
| 2 | 0.5 | 1 | py |
DIMES | DIMES-main/TSP/TSP-KNN/inc/tsp_core.py | from inc.tsp_nets import *
# REINFORCE
def tsp_tune(emb0, phi_net, graph, opt_fn, steps, sample_size, greedy_size, verbose = True, plot = True, save_name = None):
emb = emb0.detach().clone().requires_grad_()
psi_net = phi_net.clone()
psi_net.train()
opt = opt_fn([emb, *psi_net.trainables()])
tbar =... | 6,791 | 43.684211 | 214 | py |
DIMES | DIMES-main/TSP/torch_sampling/setup.py | import os, sysconfig, shutil
from setuptools import setup
import torch
from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension, BuildExtension
WITH_CUDA = torch.cuda.is_available() and CUDA_HOME is not None
LIB_PATH = os.getenv('LD_LIBRARY_PATH').split(':')[-1]
PYTHON_SITE = sysconfig.get_paths()[... | 1,168 | 30.594595 | 92 | py |
DIMES | DIMES-main/MIS/main.py | #!/usr/bin/env python3
import argparse
import pathlib
import logzero
from logzero import logger
from filelock import FileLock
# globals for release in the end
cuda_devices = []
got_devices_from_folder = False
def _set_loglevel(loglevel):
if loglevel == "DEBUG":
logzero.loglevel(logzero.DEBUG)
elif lo... | 23,027 | 56 | 262 | py |
DIMES | DIMES-main/MIS/data_generation/realworld.py | from re import split
from data_generation.generator import DataGenerator
from pathlib import Path
from pysat.formula import CNF
import networkx as nx
import numpy as np
import subprocess
import tempfile
import shutil
from pathlib import Path
import networkx as nx
import pandas as pd
import scipy.io
import sys
from log... | 20,118 | 58.523669 | 199 | py |
DIMES | DIMES-main/MIS/data_generation/random_graph.py | from data_generation.generator import DataGenerator
import networkx as nx
import random
import pickle
from abc import ABC, abstractmethod
from pathlib import Path
import subprocess
import os
import functools
from logzero import logger
from utils import run_command_with_live_output
class GraphSampler(ABC):
@abstra... | 5,796 | 32.316092 | 204 | py |
DIMES | DIMES-main/MIS/data_generation/generator.py | from abc import ABC, abstractmethod, abstractstaticmethod
from pathlib import Path
import os
import shutil
import pickle
from solvers.gurobi import Gurobi
import json
import numpy as np
from logzero import logger
import multiprocessing
class DataGenerator(ABC):
def _call_gurobi_solver(self, G, timeout=30, weighte... | 2,447 | 29.987342 | 94 | py |
DIMES | DIMES-main/MIS/data_generation/sat.py | from data_generation.generator import DataGenerator
from pathlib import Path
from pysat.formula import CNF
import networkx as nx
import numpy as np
import pickle
class SATGraphDataGenerator(DataGenerator):
def __init__(self, input_path, output_path):
self.input_path = Path(input_path)
self.output... | 2,769 | 33.197531 | 146 | py |
DIMES | DIMES-main/MIS/helper_scripts/fetch_optima.py | #!/usr/bin/env python3
"""
Evaluating the results of different solvers requires us to (sometimes) compute
an approximation factor. For this we need the optimal MIS sizes we have computed
for most of the graphs with the help of Gurobi beforehand. This script collects
these optima, which are included in the files stori... | 2,168 | 33.983871 | 145 | py |
DIMES | DIMES-main/MIS/helper_scripts/aggregator.py | #!/usr/bin/env python3
"""
If you run experiments with different solvers on different graphs, you probably want to
have a single csv file containing all data. This script takes the experiment output folder
as input, and outputs such an aggregated csv.
"""
import argparse
import pathlib
import re
import pandas as pd
i... | 4,850 | 40.110169 | 317 | py |
DIMES | DIMES-main/MIS/solvers/abstractsolver.py | from abc import ABC, abstractmethod, abstractstaticmethod
import pathlib
class MWISSolver(ABC):
@abstractmethod
def load_weights(self, model_state_path):
pass
@abstractmethod
def __str__(self):
pass
@abstractmethod
def directory(self):
pass
@abstractstaticmethod
... | 1,545 | 28.169811 | 122 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch.py | import subprocess
import os.path
import pathlib
import shutil
import sys
import scipy.io
import numpy as np
import networkx as nx
import random as rd
from logzero import logger
from utils import launch_python_script_in_conda_env
from solvers.abstractsolver import MWISSolver
class IntelTreesearch(MWISSolver):
de... | 9,300 | 41.47032 | 143 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/demo_parallel_dimes.py | from __future__ import division
from __future__ import print_function
### Begin argument parsing
import argparse
parser = argparse.ArgumentParser(description="Intel-based tree search.")
parser.add_argument("input", type=str, action="store", help="Directory containing input graphs to be solved")
parser.add_argument("o... | 16,248 | 36.526559 | 148 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/train_dimes_batched.py | from __future__ import division
from __future__ import print_function
import sys
import os
import random
sys.path.append('%s/gcn' % os.path.dirname(os.path.realpath(__file__)))
import time
import scipy.io as sio
import numpy as np
import scipy.sparse as sp
from copy import deepcopy
import tensorflow.compat.v1 as tf... | 14,007 | 41.707317 | 134 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/demo_dimes.py | from __future__ import division
from __future__ import print_function
### Begin argument parsing
import argparse
parser = argparse.ArgumentParser(description="Intel-based tree search.")
parser.add_argument("input", type=str, action="store", help="Directory containing input graphs to be solved")
parser.add_argument("o... | 17,897 | 38.597345 | 148 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/demo.py | from __future__ import division
from __future__ import print_function
### Begin argument parsing
import argparse
parser = argparse.ArgumentParser(description="Intel-based tree search.")
parser.add_argument("input", type=str, action="store", help="Directory containing input graphs to be solved")
parser.add_argument("o... | 13,233 | 35.86351 | 148 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/statistics.py | import json
import time
import numpy as np
import os
class GraphResultCollector():
def __init__(self, graph_name):
self.best_mis = None
self.best_mis_time = None
self.best_mis_size = 0
self.total_solutions = 0
self.results = {}
self.graph_name = graph_name.replace(".... | 3,708 | 31.535088 | 108 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/demo_parallel.py | from __future__ import division
from __future__ import print_function
### Begin argument parsing
import argparse
parser = argparse.ArgumentParser(description="Intel-based tree search.")
parser.add_argument("input", type=str, action="store", help="Directory containing input graphs to be solved")
parser.add_argument("o... | 16,042 | 36.222738 | 148 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/train.py | from __future__ import division
from __future__ import print_function
import sys
import os
import random
sys.path.append( '%s/gcn' % os.path.dirname(os.path.realpath(__file__)) )
import time
import scipy.io as sio
import numpy as np
import scipy.sparse as sp
from copy import deepcopy
import tensorflow.compat.v1 as t... | 8,012 | 39.065 | 182 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/kernel/reduce_lib.py | import ctypes
import networkx as nx
import numpy as np
import os
import sys
import scipy.sparse as sp
class reducelib(object):
def __init__(self):
dir_path = os.path.dirname(os.path.realpath(__file__))
self.lib = ctypes.CDLL('%s/libreduce.so' % dir_path)
def __CtypeNetworkX(self, g):
... | 3,254 | 39.6875 | 127 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/gcn/inits.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
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):
"""Glor... | 1,077 | 28.135135 | 95 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/gcn/reinforce.py | import functools
import jax
import jax.numpy as jnp
import jax.scipy
import numpy as np
import sys
import time
def sample(carry):
(jax_flag, jax_solution, graph_indices, par, par_grad, rng_key) = carry
prob = jax.nn.softmax(par, axis=-1)
p_next_node = jax.random.categorical(rng_key, par)
flag = (par[... | 20,613 | 42.673729 | 137 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/gcn/utils.py | import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh, eigs
import sys
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return inde... | 6,292 | 34.553672 | 113 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/gcn/layers.py | from inits import *
import tensorflow.compat.v1 as tf
import functools
tf.disable_v2_behavior()
flags = tf.flags
FLAGS = flags.FLAGS
# global unique layer ID dictionary for layer name assignment
_LAYER_UIDS = {}
def get_layer_uid(layer_name=''):
"""Helper function, assigns unique layer IDs."""
if layer_name... | 11,776 | 38.922034 | 115 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/gcn/models.py | from layers import *
from metrics import *
import reinforce
from layers import _LAYER_UIDS
import tensorflow_addons as tfa
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
flags = tf.flags
FLAGS = flags.FLAGS
def lrelu(x):
return tf.maximum(x * 0.2, x)
class Model(object):
def __init__(self, **kwarg... | 23,040 | 40.969035 | 118 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/NPHard/gcn/metrics.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
def my_softmax_cross_entropy(preds, labels):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
return tf.reduce_mean(loss)
def my_accuracy(preds, labels):
"""Accuracy w... | 1,179 | 32.714286 | 79 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/KaMIS/reduce_lib.py | import ctypes
import networkx as nx
import numpy as np
import os
import sys
import scipy.sparse as sp
class reducelib(object):
def __init__(self):
dir_path = os.path.dirname(os.path.realpath(__file__))
self.lib = ctypes.CDLL('%s/libreduce.so' % dir_path)
def __CtypeNetworkX(self, g):
... | 3,254 | 39.6875 | 127 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/KaMIS/misc/conversion/dimacs_to_metis.py | # Converts a DIMACS-graph into the METIS format
import sys, os, re
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
return [ atoi(c) for c in re.split('(\d+)', text) ]
filename = sys.argv[1]
if not os.path.isfile(filename):
print "File not found."
sys.exit(0)
num... | 1,929 | 26.571429 | 87 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/KaMIS/misc/conversion/sort_metis.py | # Converts a DIMACS-graph into the METIS format
import sys, os, re
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
return [ atoi(c) for c in re.split('(\d+)', text) ]
filename = sys.argv[1]
if not os.path.isfile(filename):
print "File not found."
sys.exit(0)
numb... | 1,481 | 24.118644 | 97 | py |
DIMES | DIMES-main/MIS/solvers/intel_treesearch/KaMIS/misc/conversion/metis_to_dimacs.py | # Converts a METIS-graph into the DIMACS format
import sys, os, re
filename = sys.argv[1]
if not os.path.isfile(filename):
print "File not found."
sys.exit(0)
number_nodes = 0
number_edges = 0
edges_counted = 0
adjacency = []
print "Reading the file."
with open(filename) as f:
node = 0
for line in f... | 1,447 | 26.320755 | 97 | py |
visual-semantic-embedding | visual-semantic-embedding-master/optim.py | """
Optimizers for multimodal ranking
"""
import theano
import theano.tensor as tensor
import numpy
# name(hyperp, tparams, grads, inputs (list), cost) = f_grad_shared, f_update
def adam(lr, tparams, grads, inp, cost):
gshared = [theano.shared(p.get_value() * 0., name='%s_grad'%k) for k, p in tparams.iteritems()]
... | 1,239 | 27.837209 | 99 | py |
visual-semantic-embedding | visual-semantic-embedding-master/utils.py | """
Helper functions for multimodal-ranking
"""
import theano
import theano.tensor as tensor
import numpy
from collections import OrderedDict
def zipp(params, tparams):
"""
Push parameters to Theano shared variables
"""
for kk, vv in params.iteritems():
tparams[kk].set_value(vv)
def unzip(zip... | 3,294 | 22.705036 | 74 | py |
visual-semantic-embedding | visual-semantic-embedding-master/model.py | """
Model specification
"""
import theano
import theano.tensor as tensor
from theano.tensor.extra_ops import fill_diagonal
import numpy
from collections import OrderedDict
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from utils import _p, ortho_weight, norm_weight, xavier_weight, tanh, l2norm... | 4,146 | 29.270073 | 125 | py |
visual-semantic-embedding | visual-semantic-embedding-master/tools.py | """
A selection of functions for encoding images and sentences
"""
import theano
import theano.tensor as tensor
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
import cPickle as pkl
import numpy
from collections import OrderedDict, defaultdict
from scipy.linalg import norm
from utils import loa... | 3,834 | 30.434426 | 137 | py |
visual-semantic-embedding | visual-semantic-embedding-master/vocab.py | """
Constructing and loading dictionaries
"""
import cPickle as pkl
import numpy
from collections import OrderedDict
def build_dictionary(text):
"""
Build a dictionary
text: list of sentences (pre-tokenized)
"""
wordcount = OrderedDict()
for cc in text:
words = cc.split()
for w ... | 1,107 | 22.574468 | 81 | py |
visual-semantic-embedding | visual-semantic-embedding-master/layers.py | """
Layers for multimodal-ranking
"""
import theano
import theano.tensor as tensor
import numpy
from utils import _p, ortho_weight, norm_weight, xavier_weight, tanh, linear
# layers: 'name': ('parameter initializer', 'feedforward')
layers = {'ff': ('param_init_fflayer', 'fflayer'),
'gru': ('param_init_gru'... | 4,103 | 29.857143 | 108 | py |
visual-semantic-embedding | visual-semantic-embedding-master/datasets.py | """
Dataset loading
"""
import numpy
#-----------------------------------------------------------------------------#
# Specify dataset(s) location here
#-----------------------------------------------------------------------------#
path_to_data = '/ais/gobi3/u/rkiros/uvsdata/'
#----------------------------------------... | 1,354 | 29.795455 | 79 | py |
visual-semantic-embedding | visual-semantic-embedding-master/demo.py | """
Embedding and captioning new images
"""
import os
import cPickle as pkl
import numpy
import skimage.transform
import lasagne
from lasagne.layers import InputLayer, DenseLayer, NonlinearityLayer
from lasagne.layers.corrmm import Conv2DMMLayer as ConvLayer
from lasagne.layers import MaxPool2DLayer as PoolLayer
from ... | 7,443 | 32.836364 | 95 | py |
visual-semantic-embedding | visual-semantic-embedding-master/homogeneous_data.py | import numpy
import copy
import sys
class HomogeneousData():
def __init__(self, data, batch_size=128, maxlen=None):
self.batch_size = 128
self.data = data
self.batch_size = batch_size
self.maxlen = maxlen
self.prepare()
self.reset()
def prepare(self):
... | 3,829 | 31.457627 | 109 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.