repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
pFedGate | pFedGate-main/models/gating_layers.py | from copy import copy, deepcopy
import torch
from torch import nn as nn
from models import switchable_norm
from models.adapted_op import AdaptedLinear, deepgetattr
from utils.constants import IN_PLANES_TYPE, SHAKESPEARE_CONFIG
from models.adapted_op import map_module_name
class Reshape(nn.Module):
def __init__(... | 8,233 | 52.122581 | 126 | py |
pFedGate | pFedGate-main/utils/optim.py | import torch
import torch.optim as optim
from torch.optim.optimizer import Optimizer, required
import numpy as np
class ProxSGD(Optimizer):
r"""Adaptation of torch.optim.SGD to proximal stochastic gradient descent (optionally with momentum),
presented in `Federated optimization in heterogeneous networks`__.... | 8,202 | 36.801843 | 106 | py |
pFedGate | pFedGate-main/utils/utils.py | import shutil
from typing import Callable, Optional
from wandb.sdk.lib import filenames
from wandb.sdk.lib.filenames import WANDB_DIRS
from models.adapted_op import AdaptedLeafCNN1, AdaptedLeNet, AdaptedLeafCNN3
from pFedGate.gate_aggregator import pFedGateAggregator
from pFedGate.gated_learner import GatedLearner
fr... | 31,826 | 35.540758 | 120 | py |
pFedGate | pFedGate-main/utils/sparse_factor_schedule.py | from torch._six import inf
class SparsityLinearScheduler(object):
def __init__(self, prune_begin_round, total_rounds, s_target, s_begin):
self.prune_begin_round = prune_begin_round
self.total_decay_rounds = total_rounds
self.s_target = s_target
self.s_begin = s_begin
# line... | 4,669 | 33.592593 | 121 | py |
pFedGate | pFedGate-main/utils/torch_utils.py | import collections.abc
import copy
import pickle
import warnings
from collections import OrderedDict
import torch
import torch.nn as nn
def average_model_of_learners(
learners,
target_learner,
weights=None,
average_params=True,
average_gradients=False):
"""
Compute the... | 8,889 | 31.210145 | 121 | py |
pFedGate | pFedGate-main/utils/metrics.py | import torch
import torch.nn.functional as F
def mse(y_pred, y):
return F.mse_loss(y_pred, y)
def binary_accuracy(y_pred, y):
y_pred = torch.round(torch.sigmoid(y_pred)) # round predictions to the closest integer
correct = (y_pred == y).float()
acc = correct.sum()
return acc
def accuracy(y_pr... | 446 | 20.285714 | 91 | py |
pFedGate | pFedGate-main/data/cifar10/generate_data.py | """
Download CIFAR-10 dataset, and splits it among clients
"""
import os
import argparse
import pickle
from torchvision.datasets import CIFAR10
from torchvision.transforms import Compose, ToTensor, Normalize
from torch.utils.data import ConcatDataset
from sklearn.model_selection import train_test_split
from utils im... | 5,122 | 28.442529 | 115 | py |
pFedGate | pFedGate-main/data/cifar10/generate_data_pFedHN.py | # split CIFAR 100 & CIFAR10 according to the paper, Personalized Federated Learning using Hypernetworks
# the split code is from [author](https://github.com/AvivSham/pFedHN/blob/e50b64a5694030a3594534e7fb7bdafde01554f2/experiments/dataset.py)
#
import random
from collections import defaultdict
import numpy as np
impo... | 8,695 | 36.645022 | 138 | py |
pFedGate | pFedGate-main/data/cifar10/utils.py | import random
import time
import numpy as np
def iid_divide(l, g):
"""
https://github.com/TalwalkarLab/leaf/blob/master/data/utils/sample.py
divide list `l` among `g` groups
each group has either `int(len(l)/g)` or `int(len(l)/g)+1` elements
returns a list of groups
"""
num_elems = len(l)... | 5,579 | 34.541401 | 119 | py |
pFedGate | pFedGate-main/data/cifar10/generate_toy_data.py | """
Download CIFAR-10 dataset, and splits it among clients
"""
import os
import argparse
import pickle
from torchvision.datasets import CIFAR10
from torchvision.transforms import Compose, ToTensor, Normalize
from torch.utils.data import ConcatDataset
from sklearn.model_selection import train_test_split
from utils im... | 5,129 | 28.482759 | 115 | py |
pFedGate | pFedGate-main/data/cifar100/generate_data.py | """
Download CIFAR-10 dataset, and splits it among clients
"""
import os
import argparse
import pickle
import numpy as np
from torchvision.datasets import CIFAR100
from torchvision.transforms import Compose, ToTensor, Normalize
from torch.utils.data import ConcatDataset
from sklearn.model_selection import train_test_... | 6,913 | 30.144144 | 115 | py |
pFedGate | pFedGate-main/data/cifar100/generate_data_pFedHN.py | # split CIFAR 100 & CIFAR10 according to the paper, Personalized Federated Learning using Hypernetworks
# the split code is from [author](https://github.com/AvivSham/pFedHN/blob/e50b64a5694030a3594534e7fb7bdafde01554f2/experiments/dataset.py)
#
import random
from collections import defaultdict
import numpy as np
impo... | 8,696 | 36.649351 | 138 | py |
pFedGate | pFedGate-main/data/cifar100/utils.py | import random
import time
import numpy as np
def renormalize(weights, index):
"""
:param weights: vector of non negative weights summing to 1.
:type weights: numpy.array
:param index: index of the weight to remove
:type index: int
"""
renormalized_weights = np.delete(weights, index)
r... | 10,505 | 34.493243 | 119 | py |
pFedGate | pFedGate-main/data/emnist/generate_data.py | """
Download EMNIST dataset, and splits it among clients
"""
import os
import argparse
import pickle
from torchvision.datasets import EMNIST
from torchvision.transforms import Compose, ToTensor, Normalize
from torch.utils.data import ConcatDataset
from sklearn.model_selection import train_test_split
from utils impor... | 5,588 | 28.728723 | 115 | py |
pFedGate | pFedGate-main/data/emnist/utils.py | import random
import time
import numpy as np
def iid_divide(l, g):
"""
https://github.com/TalwalkarLab/leaf/blob/master/data/utils/sample.py
divide list `l` among `g` groups
each group has either `int(len(l)/g)` or `int(len(l)/g)+1` elements
returns a list of groups
"""
num_elems = len(l)... | 5,579 | 34.541401 | 119 | py |
pFedGate | pFedGate-main/data/femnist/generate_data.py | """
Process Femnist dataset, and splits it among clients
"""
import os
import time
import random
import argparse
import torch
from tqdm import tqdm
from sklearn.model_selection import train_test_split
RAW_DATA_PATH = os.path.join("intermediate", "data_as_tensor_by_writer")
# TARGET_PATH = "all_data/"
TARGET_PATH = "... | 3,884 | 26.553191 | 109 | py |
pFedGate | pFedGate-main/data/femnist/data_to_tensor.py | """
Converts a list of (writer, [list of (file,class)]) into torch.tensor,
For each writer, creates a `.pt` file containing `data` and `targets`,
The resulting file is saved in `intermediate/data_as_tensor_by_writer'
"""
import os
import pickle
import torch
import numpy as np
from tqdm import tqdm
from PIL import Ima... | 1,884 | 27.560606 | 92 | py |
pFedGate | pFedGate-main/learners/learner.py | import torch
class Learner:
"""
Responsible of training and evaluating a (deep-)learning model
Attributes
----------
model (nn.Module): the model trained by the learner
criterion (torch.nn.modules.loss): loss function used to train the `model`, should have reduction="none"
metric (fn): ... | 12,622 | 26.441304 | 108 | py |
pFedGate | pFedGate-main/learners/learners_ensemble.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class LearnersEnsemble(object):
"""
Iterable Ensemble of Learners.
Attributes
----------
learners
learners_weights
model_dim
is_binary_classification
device
metric
Methods
----------
__init__
_... | 8,586 | 29.777778 | 114 | py |
ALS4GAN | ALS4GAN-main/tools/train_AL.py | import argparse
import numpy as np
import math
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.models as models
from torch.utils import data
from skorch import NeuralNetClassifier
import modAL
from modAL.models import ActiveLearner
from scipy.special import softmax
from ... | 9,782 | 37.364706 | 173 | py |
ALS4GAN | ALS4GAN-main/tools/auto_evaluate.py | import argparse
import cv2
import numpy as np
import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils import data
from model import *
from data.ucm import UCMDataSet
from data.deepglobe import DeepGlobeDataSet
from utils.crf imp... | 7,314 | 35.212871 | 112 | py |
ALS4GAN | ALS4GAN-main/tools/train_s4gan.py | import argparse
import os
import numpy as np
import timeit
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.utils import data
from torch.autograd import Variable
from model import *
from model.discriminator import s4GAN_disc... | 20,059 | 37.725869 | 152 | py |
ALS4GAN | ALS4GAN-main/utils/lr_scheduler.py | from torch.optim.lr_scheduler import _LRScheduler
class PolynomialLR(_LRScheduler):
def __init__(self, optimizer, step_size, iter_max, power, last_epoch=-1):
self.step_size = step_size
self.iter_max = iter_max
self.power = power
super(PolynomialLR, self).__init__(optimizer, last_ep... | 767 | 35.571429 | 78 | py |
ALS4GAN | ALS4GAN-main/utils/loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
class CrossEntropy2d(nn.Module):
def __init__(self, ignore_label=255):
super(CrossEntropy2d, self).__init__()
self.ignore_label = ignore_label
def forward(self, predict, t... | 1,230 | 37.46875 | 92 | py |
ALS4GAN | ALS4GAN-main/utils/metric.py | # Originally written by wkentaro
# https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py
import numpy as np
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
hist = np.bincount(
n_class * label_true[mask].astype(int) + label_pred[mask],... | 1,206 | 31.621622 | 78 | py |
ALS4GAN | ALS4GAN-main/data/deepglobe.py | import cv2
import numpy as np
import json
import random
import os.path as osp
from torch.utils import data
class DeepGlobeDataSet(data.Dataset):
def __init__(self, root, list_path, module, crop_size=(320, 320), mean=(128, 128, 128), scale=False, mirror=False, ignore_label=255):
self.module = module
... | 5,522 | 36.571429 | 137 | py |
ALS4GAN | ALS4GAN-main/data/ucm.py | import cv2
import numpy as np
import random
import os.path as osp
from torch.utils import data
from PIL import Image
import re
class UCMDataSet(data.Dataset):
def __init__(self, root, list_path, module, crop_size=(320, 320), mean=(128, 128, 128), scale=False, mirror=False, ignore_label=255):
self.module =... | 4,327 | 37.300885 | 137 | py |
ALS4GAN | ALS4GAN-main/model/msc.py | #!/usr/bin/env python
# coding: utf-8
#
# Author: Kazuto Nakashima
# URL: http://kazuto1011.github.io
# Created: 2018-03-26
import torch
import torch.nn as nn
import torch.nn.functional as F
class MSC(nn.Module):
"""
Multi-scale inputs
"""
def __init__(self, base, scales=None):
super... | 1,300 | 23.54717 | 86 | py |
ALS4GAN | ALS4GAN-main/model/discriminator.py | from torch.autograd import Variable
import torch.nn as nn
class s4GAN_discriminator(nn.Module):
def __init__(self, num_classes, dataset, ndf = 64):
super(s4GAN_discriminator, self).__init__()
#print(dataset, 'in discriminator')
self.conv1 = nn.Conv2d(num_classes+3, ndf, kernel_size=4, stri... | 1,672 | 33.854167 | 98 | py |
ALS4GAN | ALS4GAN-main/model/resnet.py | #!/usr/bin/env python
# coding: utf-8
#
# Author: Kazuto Nakashima
# URL: http://kazuto1011.github.io
# Created: 2017-11-19
from __future__ import absolute_import, print_function
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
try:
from encoding.nn ... | 4,061 | 28.014286 | 84 | py |
ALS4GAN | ALS4GAN-main/model/deeplabv2.py | #!/usr/bin/env python
# coding: utf-8
#
# Author: Kazuto Nakashima
# URL: http://kazuto1011.github.io
# Created: 2017-11-19
from __future__ import absolute_import, print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from .resnet import _ConvBnReLU, _ResLayer, _Stem
class _ASPP... | 2,019 | 27.857143 | 87 | py |
M2U-Net | M2U-Net-master/m2unet.py | # M2U-Net PyTorch model
#
# MIT License
# Copyright (c) September 2018 Tim Laibacher
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | 7,420 | 37.651042 | 110 | py |
M2U-Net | M2U-Net-master/driu.py | # PyTorch implementation of DRIU:
# http://www.vision.ee.ethz.ch/~cvlsegmentation/driu/data/paper/DRIU_MICCAI2016.pdf
# MIT License
# Copyright (c) September 2018 Tim Laibacher
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ... | 4,102 | 34.678261 | 94 | py |
M2U-Net | M2U-Net-master/benchmark_pytorch.py | from pathlib import Path
import torch
from torch.utils.data import DataLoader
import torchvision.transforms.functional as VF
import torch.backends.cudnn as cudnn
import time
import numpy as np
from PIL import Image
from argparse import ArgumentParser
from dataset import get_file_lists, RetinaDataset
# Networks
from m2... | 5,503 | 37.48951 | 220 | py |
M2U-Net | M2U-Net-master/dataset.py | from pathlib import Path
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
import torchvision.transforms.functional as VF
def get_file_lists(image_file_path):
"""
Args:
image_file_path
returns:
list of file names in path
"""
file_paths = np.array(sorted(l... | 1,239 | 28.52381 | 67 | py |
M2U-Net | M2U-Net-master/unet.py | # MIT License
# Copyright (c) 2018 Joris
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish,... | 5,808 | 39.062069 | 98 | py |
M2U-Net | M2U-Net-master/erfnet.py | # ERFNet full model definition for Pytorch
# Sept 2017
# Eduardo Romera
# Attribution-NonCommercial 4.0 International
# https://github.com/Eromera/erfnet_pytorch
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
class DownsamplerBlock (nn.Module):
def __init__(self, n... | 4,800 | 29.775641 | 124 | py |
M2U-Net | M2U-Net-master/benchmark_tvm_arm.py | import tvm
import nnvm.compiler
import nnvm.testing
import nnvm
import onnx
from tvm import rpc
from tvm.contrib import util, graph_runtime as runtime
from pathlib import Path
import torchvision.transforms.functional as VF
import torch
from PIL import Image
import numpy as np
from argparse import ArgumentParser
def l... | 4,764 | 33.781022 | 221 | py |
MetaPrompting | MetaPrompting-main/dataloader.py | import os
import json
import random
from collections import defaultdict
from tqdm import tqdm, trange
import datetime
import numpy as np
import torch
# from utils import tprint
from transformers import BertForMaskedLM, RobertaForMaskedLM, \
BertConfig, BertTokenizer, RobertaConfig, RobertaTokenizer, \
AlbertF... | 17,411 | 38.482993 | 146 | py |
MetaPrompting | MetaPrompting-main/utils.py | import json
import os
import torch
import datetime
from collections import defaultdict
import numpy as np
from tqdm import tqdm, trange
def tprint(s):
'''
print datetime and s
@params:
s (str): the string to be printed
'''
print('{}: {}'.format(
datetime.datetime.now()... | 1,147 | 23.956522 | 88 | py |
MetaPrompting | MetaPrompting-main/model.py | import json
import jsonpickle
import os
from typing import List, Dict, Optional
import copy
import torch
import torch.nn as nn
import numpy as np
from tensorboardX import SummaryWriter
from torch.utils.data import RandomSampler, DataLoader, SequentialSampler, Dataset
from tqdm import trange, tqdm
from transformers imp... | 36,020 | 45.003831 | 118 | py |
MetaPrompting | MetaPrompting-main/MetaPrompting.py | import os
import argparse
import random
import torch
import numpy as np
# import datetime
import dataloader as loader
from model import MetaTransformerModelWrapper
from utils import tprint
def parse_args():
parser = argparse.ArgumentParser(
description="MetaPrompting")
# data configuration
parse... | 8,112 | 49.080247 | 114 | py |
MetaPrompting | MetaPrompting-main/meta/example.py | import argparse
import random
import torch
from torch import nn, optim
from torch.nn import functional as F
from tqdm import tqdm
from meta.algrithm import MAML
def compute_loss(model):
pass
model = MyModel()
maml = MAML(model, lr=0.1)
opt = torch.optim.SGD(maml.parameters(), lr=0.001) # change it
for itera... | 707 | 25.222222 | 107 | py |
MetaPrompting | MetaPrompting-main/meta/algrithm.py | #!/usr/bin/env python3
import traceback
import torch
from torch.autograd import grad
from torch import nn
from time import sleep
from meta.utils import clone_module, update_module, detach_module
class BaseLearner(nn.Module):
def __init__(self, module=None):
super(BaseLearner, self).__init__()
... | 10,091 | 39.047619 | 104 | py |
MetaPrompting | MetaPrompting-main/meta/utils.py | #!/usr/bin/env python3
import copy
import torch
import argparse
import dataclasses
def magic_box(x):
"""
[[Source]](https://github.com/learnables/learn2learn/blob/master/learn2learn/utils.py)
**Description**
The magic box operator, which evaluates to 1 but whose gradient is \\(dx\\):
$$\\boxdot (... | 11,595 | 35.012422 | 119 | py |
MetaPrompting | MetaPrompting-main/meta/gpu_profile.py | import torch
from pytorch_memlab import LineProfiler
def inner():
torch.nn.Linear(100, 100).cuda()
@profile
def outer():
linear = torch.nn.Linear(100, 100).cuda()
linear2 = torch.nn.Linear(100, 100).cuda()
inner()
# # with LineProfiler(outer, inner) as prof:
# # outer()
# prof.display()
outer()
| 320 | 16.833333 | 46 | py |
ClusterEA | ClusterEA-master/src/utils_largeea.py | import io
import json
from typing import *
import pickle
import torch
import torch.nn.utils.rnn as rnn
import torch_sparse
import numpy as np
from torch import Tensor
from torch_scatter import scatter, scatter_max, scatter_min
from torch_geometric.utils import softmax
import torch
from torch import Tensor
from functoo... | 13,522 | 27.231733 | 106 | py |
ClusterEA | ClusterEA-master/src/main.py | import argparse
def get_arguments():
parser = argparse.ArgumentParser()
# My arguments
parser.add_argument('--scale', type=str, default='small', help='dataset scale, '
'small -> IDS15K'
... | 18,752 | 41.913043 | 119 | py |
ClusterEA | ClusterEA-master/src/sparse_eval.py | # from text_utils import *
from utils import *
import torch.nn.functional as F
from tqdm import trange
from math import floor, ceil
def get_hit_k(match_id: Tensor, link: Tensor, src=0, k_list=(1, 3, 5, 10), ignore=None, start=""):
trg = 1 - src
total = link.size(1)
if ignore is not None:
match_id[... | 8,516 | 37.538462 | 111 | py |
ClusterEA | ClusterEA-master/src/utils.py | import numpy as np
import scipy.sparse as sp
import torch
from tqdm import tqdm
global_dict = {}
def add_log(key, value):
global_dict[key] = value
def func(triples):
head = {}
cnt = {}
for tri in triples:
if tri[1] not in cnt: # relation
cnt[tri[1]] = 1
head[tri[1]... | 7,194 | 28.487705 | 114 | py |
ClusterEA | ClusterEA-master/src/align_batch.py | import utils
from utils import *
from dataset import *
def get_bi_mapping(src2trg, trg2src, lens) -> Tensor:
srclen, trglen = lens
with torch.no_grad():
i = torch.arange(srclen, device=src2trg.device).to(torch.long)
return trg2src[src2trg[i]] == i
def filter_mapping(src2trg: Tensor, trg2src:... | 6,817 | 33.609137 | 105 | py |
ClusterEA | ClusterEA-master/src/dataset.py | from utils import *
import os
import os.path as osp
from random import shuffle
import codecs
from dto import *
class EAData:
def __init__(self, triple1_path, triple2_path, ent_links_path,
shuffle_pairs=False, train_ratio=0.3, unsup=False, filter_link=True, **kwargs):
rel1, ent1, triple1 =... | 7,621 | 36.920398 | 117 | py |
ClusterEA | ClusterEA-master/src/metis.py | import networkx as nx
import nxmetis
from utils import *
from dataset import EAData, LargeScaleEAData
from random import sample
import numpy as np
from dto import *
from collections import defaultdict
from tqdm import tqdm, trange
from typing import *
import argparse, logging, random, time
def stat(array, name, prin... | 11,362 | 39.010563 | 105 | py |
ClusterEA | ClusterEA-master/src/framework.py | from dataset import *
import torch.nn as nn
from evaluation import get_hits
from metis import Partition
from common.sinkhorn import *
from partition_models.trainer import PartitionTrainer
from sparse_eval import sparse_top_k
from align_batch import SelectedCandidates
from utils import get_batch_sim, get_batch_csls_si... | 12,352 | 42.192308 | 120 | py |
ClusterEA | ClusterEA-master/src/evaluation.py | from dataset import *
import faiss
import scipy.spatial
def get_hits_slow(em1, em2, test_pair, top_k=(1, 10)):
em1 = em1.detach().numpy()
em2 = em2.detach().numpy()
Lvec = np.array([em1[e1] for e1, e2 in test_pair])
Rvec = np.array([em2[e2] for e1, e2 in test_pair])
sim = scipy.spatial.distance.c... | 3,225 | 34.844444 | 118 | py |
ClusterEA | ClusterEA-master/src/common/sinkhorn.py | # from fml.functional import sinkhorn
from utils import *
from utils_largeea import *
import numpy as np
from scipy.optimize import linear_sum_assignment
from scipy.sparse import coo_matrix
import torch
def sinkhorn_norm(alpha: torch.Tensor, n_iter: int = 20) -> (torch.Tensor,):
for _ in range(n_iter):
... | 6,280 | 38.25625 | 120 | py |
ClusterEA | ClusterEA-master/src/prev_models/wrapper.py | from utils import *
from utils_largeea import *
from tqdm import tqdm
from sparse_eval import evaluate_sim_matrix
import torch.nn as nn
import torch.optim as optim
def default(*args, **kwargs):
pass
class ModelWrapper:
def __init__(self, name, **kwargs):
self.tf = True
print('Model name is'... | 1,663 | 32.28 | 68 | py |
ClusterEA | ClusterEA-master/src/prev_models/duala/loss.py | import torch
import torch.nn.functional as F
def align_loss(align_input, embedding, gamma, node_size, device):
def squared_dist(x):
A, B = x
row_norms_A = torch.sum(torch.square(A), dim=1)
row_norms_A = torch.reshape(row_norms_A, [-1, 1]) # Column vector.
row_norms_B = torch.sum(t... | 2,129 | 43.375 | 119 | py |
ClusterEA | ClusterEA-master/src/prev_models/duala/duala_wrapper.py | from .duala import *
import dgl
import numpy as np
import torch
import time
from utils_largeea import *
from .loss import align_loss
from .data_util import *
from tqdm import *
def get_embedding(index_a, index_b, vec):
vec = vec.detach().numpy()
Lvec = np.array([vec[e] for e in index_a])
Rvec = np.array([... | 9,525 | 35.498084 | 113 | py |
ClusterEA | ClusterEA-master/src/prev_models/duala/duala.py | import dgl
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl.utils import expand_as_pair
import dgl.function as fn
class overAll(nn.Module):
def __init__(self, node_size, node_hidden,
rel_size,
rel_matrix,
ent_matrix,
... | 5,358 | 41.19685 | 105 | py |
ClusterEA | ClusterEA-master/src/prev_models/rrea/layer.py | from __future__ import absolute_import
from keras import activations, constraints, initializers, regularizers
from keras import backend as K
from keras.layers import Layer, Dropout, LeakyReLU
import tensorflow as tf
import numpy as np
class NR_GraphAttention(Layer):
def __init__(self,
node_size... | 6,583 | 42.315789 | 119 | py |
ClusterEA | ClusterEA-master/src/prev_models/rrea/rrea.py | # %%
import warnings
warnings.filterwarnings('ignore')
import keras
from tqdm import *
from .utils import *
from .CSLS import *
import tensorflow as tf
import keras.backend as K
from keras.layers import *
from .layer import NR_GraphAttention
from .mraea.model import get_mraea_model
from utils import *
from tensorflo... | 14,621 | 39.280992 | 115 | py |
ClusterEA | ClusterEA-master/src/prev_models/rrea/CSLS.py | import multiprocessing
import gc
import os
import numpy as np
import time
from scipy.spatial.distance import cdist
g = 1000000000
def div_list(ls, n):
ls_len = len(ls)
if n <= 0 or 0 == ls_len:
return [ls]
if n > ls_len:
return [ls]
elif n == ls_len:
return [[i] for i in ls... | 11,106 | 31.287791 | 120 | py |
ClusterEA | ClusterEA-master/src/prev_models/rrea/mraea/layer.py | from __future__ import absolute_import
from keras import activations, constraints, initializers, regularizers
from keras import backend as K
from keras.layers import Layer, Dropout, LeakyReLU
import tensorflow as tf
import numpy as np
class TR_GraphAttention(Layer):
def __init__(self,
node_size... | 7,662 | 47.808917 | 148 | py |
ClusterEA | ClusterEA-master/src/prev_models/rrea/mraea/model.py | from __future__ import absolute_import
import keras
from keras.layers import *
from .layer import TR_GraphAttention
from keras import activations, constraints, initializers, regularizers
from keras import backend as K
from keras.layers import Layer, Dropout, LeakyReLU
import tensorflow as tf
import numpy as np
class... | 2,801 | 39.608696 | 106 | py |
ClusterEA | ClusterEA-master/src/prev_models/rrea/dual_amn/layer.py | from __future__ import absolute_import
from keras import activations, constraints, initializers, regularizers
from keras import backend as K
from keras.layers import Layer, Dropout, LeakyReLU
import tensorflow.compat.v1 as tf
import numpy as np
class NR_GraphAttention(Layer):
def __init__(self,
... | 7,631 | 42.611429 | 117 | py |
ClusterEA | ClusterEA-master/src/prev_models/rrea/dual_amn/evaluate.py | import keras
import numpy as np
from utils import *
from tqdm import *
import tensorflow as tf
import keras.backend as K
from keras.layers import *
class evaluate:
def __init__(self, dev_pair):
self.dev_pair = dev_pair
Matrix_A = Input(shape=(None, None))
Matrix_B = Input(shape=(None, Non... | 4,977 | 41.547009 | 118 | py |
ClusterEA | ClusterEA-master/src/prev_models/rrea/dual_amn/duala.py | # %%
import warnings
warnings.filterwarnings('ignore')
import os
import keras
import numpy as np
from .utils import *
from tqdm import *
from .evaluate import evaluate
import tensorflow.compat.v1 as tf
import keras.backend as K
from keras.layers import *
from .layer import NR_GraphAttention
class TokenEmbedding(ke... | 8,076 | 35.547511 | 110 | py |
ClusterEA | ClusterEA-master/src/prev_models/gcn_align/layers.py | from .inits import *
import tensorflow.compat.v1 as tf
flags = tf.app.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 not in _LAYER_UIDS:
_LAYER_U... | 6,236 | 31.149485 | 99 | py |
ClusterEA | ClusterEA-master/src/prev_models/gcn_align/gcn_align.py | from __future__ import division
from __future__ import print_function
import time
import tensorflow.compat.v1 as tf
from .utils import *
from .metrics import *
from .models import GCN_Align
import tensorflow
physical_devices = tensorflow.config.list_physical_devices('GPU')
tensorflow.config.experimental.set_memory_... | 7,968 | 39.451777 | 119 | py |
ClusterEA | ClusterEA-master/src/prev_models/duala_sample/dgl_rrea.py | import dgl
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl.dataloading import MultiLayerFullNeighborSampler
from dgl.utils import expand_as_pair
import dgl.function as fn
class overAllRREA(nn.Module):
def __init__(self, node_size, node_hidden,
rel_si... | 5,607 | 38.216783 | 118 | py |
ClusterEA | ClusterEA-master/src/prev_models/duala_sample/dgl_sample_gcn.py | import dgl
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl.dataloading import MultiLayerFullNeighborSampler
from dgl.utils import expand_as_pair
import dgl.function as fn
class overAll(nn.Module):
def __init__(self, node_size, node_hidden,
rel_size,
... | 7,200 | 41.358824 | 118 | py |
ClusterEA | ClusterEA-master/src/prev_models/duala_sample/wrapper.py | from .dgl_sample_gcn import *
from .dgl_rrea import overAllRREA
import dgl
import numpy as np
import torch
import time
from ..duala.data_util import *
from tqdm import *
from dgl.dataloading import *
import torch.nn.functional as F
from dto import saveobj, readobj
gamma = 1
def batch_align_loss(batch_size, neg_size,... | 12,613 | 34.937322 | 119 | py |
ClusterEA | ClusterEA-master/src/prev_models/gcn_sample/loss.py | import torch
import torch.nn.functional as F
from utils_largeea import norm_process
def marginLossGCN(pos_1, pos_2, neg_1, neg_2, margin=3):
A = torch.norm(pos_1 - pos_2, p=1, dim=1, keepdim=False)
B = torch.norm(neg_1 - neg_2, p=1, dim=1, keepdim=False)
C = torch.norm(pos_1 - neg_2, p=1, dim=1, keepdim=... | 1,761 | 37.304348 | 100 | py |
ClusterEA | ClusterEA-master/src/prev_models/gcn_sample/models.py | import torch.nn as nn
import torch.nn.functional as F
import dgl.nn
from dataset import *
# import time
class GCN(nn.Module):
def __init__(self, in_feats, out_feats, middle=200, device='cuda', first_layer_weight=False):
super(GCN, self).__init__()
self.in_dim = in_feats
self.conv1 = dgl.nn.... | 6,000 | 40.673611 | 131 | py |
ClusterEA | ClusterEA-master/src/prev_models/gcn_sample/train.py | from utils import set_seed
set_seed(0)
from .models import *
from evaluation import get_hits
from .partition import RandomUniquePartition
from dataset import *
# ds = 'srp'
# scale = 'large'
# lang = 'fr'
# fanout = -1
dim = 200
train_epoch = 10
batch_size = 2000
learning_rate = 0.001
fanouts = [8, 8]
neg_k = 2
marg... | 3,861 | 35.780952 | 109 | py |
ClusterEA | ClusterEA-master/src/partition_models/tmodel.py | from torch import Tensor, tensor, randn, zeros
import torch
import torch.nn as nn
a = torch.tensor(zeros(5), requires_grad=False)
b = nn.Linear(5, 5)
c = b(a)
loss = c.sum()
loss.backward()
if __name__ == '__main__':
print()
pass
| 244 | 12.611111 | 47 | py |
ClusterEA | ClusterEA-master/src/partition_models/gnns.py | import dgl
import torch
import torch.nn as nn
import torch.nn.functional as F
from dataset import EAData
import dgl.data
from utils import ConstructGraph
import dgl.nn
class GCN(nn.Module):
def __init__(self, in_feats, h_feats, num_classes):
super(GCN, self).__init__()
self.conv1 = dgl.nn.GraphCon... | 5,825 | 32.872093 | 110 | py |
ClusterEA | ClusterEA-master/src/partition_models/kmeans.py | import math
import torch
from time import time
import numpy as np
class KMeans:
'''
Kmeans clustering algorithm implemented with PyTorch
Parameters:
n_clusters: int,
Number of clusters
max_iter: int, default: 100
Maximum number of iterations
tol: float, default: 0.0001
... | 9,353 | 37.652893 | 140 | py |
ClusterEA | ClusterEA-master/src/partition_models/sklearn_models.py | from xgboost import XGBClassifier
from utils_largeea import *
from sklearn.neural_network import MLPClassifier
class SKLearnPartition:
def __init__(self, classifier, **kwargs):
if classifier == 'xgb':
self.model = XGBClassifier(tree_method='gpu_hist', gpu_id=0, predictor='gpu_predictor',
... | 1,011 | 30.625 | 99 | py |
ClusterEA | ClusterEA-master/src/partition_models/trainer.py | import torch
import torch.nn as nn
from nxmetis import metis
from .kmeans import KMeans
from metis import Partition
from sklearn.neural_network import MLPClassifier
from dataset import *
from torch import Tensor
import numpy as np
import nxmetis
from .gnns import NodeClassification
from .sklearn_models import SKLearnP... | 15,978 | 42.421196 | 116 | py |
partial_identification | partial_identification-main/experiments/ate_experiment.py | import os
import sys
import fire
import torch
from geomloss import SamplesLoss
from pytorch_lightning import seed_everything, Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(dir_path, '../model'))
sys.path.append(os.pa... | 3,211 | 40.714286 | 124 | py |
partial_identification | partial_identification-main/experiments/utils.py | from abc import ABC
import numpy as np
import pandas as pd
from pytorch_lightning import LightningDataModule
from pytorch_lightning.loggers import WandbLogger
from typing import Optional
from pathlib import Path
import torch
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader... | 3,161 | 33 | 97 | py |
partial_identification | partial_identification-main/experiments/atd_experiment.py | import os
import sys
import fire
import torch
from geomloss import SamplesLoss
from pytorch_lightning import seed_everything, Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(dir_path, '../model'))
sys.path.append(os.pa... | 2,797 | 40.147059 | 120 | py |
partial_identification | partial_identification-main/experiments/acic_experiment.py | import os
import sys
import fire
import numpy as np
import torch
from geomloss import SamplesLoss
from pytorch_lightning import seed_everything, Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(dir_path, '../model'))
sy... | 3,360 | 42.649351 | 117 | py |
partial_identification | partial_identification-main/data/load_scm.py | import itertools
from typing import Optional, Callable, Dict
import numpy as np
import torch
import os
from load_dag import DAG, gen_dags
import torch.nn.functional as F
dirname = os.path.dirname(__file__)
####################
# Collection of synthetic datasets used in the paper.
####################
class SCM:
... | 12,962 | 37.014663 | 116 | py |
partial_identification | partial_identification-main/model/sinkhorn_gn.py | import warnings
from abc import ABC
from argparse import ArgumentParser
from typing import Optional, Union, Callable, Dict
from pytorch_lightning import LightningModule
from torch.optim import Adam, Optimizer
import numpy as np
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import ReduceLROnPlateau
f... | 11,210 | 43.844 | 120 | py |
partial_identification | partial_identification-main/model/common.py | import copy
from typing import Dict, Optional
import numpy as np
import torch
import torch.nn as nn
from pytorch_lightning.callbacks import Callback, EarlyStopping
import pytorch_lightning as pl
from pytorch_lightning.callbacks.progress import TQDMProgressBar
import torch.nn.functional as F
from load_dag import DAG
... | 8,671 | 40.692308 | 120 | py |
partial_identification | partial_identification-main/model/estimands.py | from typing import Callable
import torch
import numpy as np
from common import Generator
from load_dag import DAG
####################
# Collection of causal estimands. We will assume dim(do_var) = 1.
####################
class Estimand:
r"""Describes the estimand of interest (interventional quantity) and calcul... | 6,704 | 37.757225 | 117 | py |
dpcca | dpcca-master/linalg.py | """=============================================================================
Functions for linear algebra operations.
============================================================================="""
import cuda
import torch
# ------------------------------------------------------------------------------
diag = t... | 2,481 | 33 | 80 | py |
dpcca | dpcca-master/cuda.py | """=============================================================================
CUDA-related utility functions.
============================================================================="""
import torch
# ------------------------------------------------------------------------------
def device():
"""Return c... | 497 | 30.125 | 80 | py |
dpcca | dpcca-master/traindpcca.py | """=============================================================================
Train deep probabilistic CCA (DPCCA).
============================================================================="""
import argparse
import time
import torch
import torch.utils.data
from torch.nn.utils import clip_grad_norm_
from t... | 7,446 | 30.289916 | 80 | py |
dpcca | dpcca-master/pprint.py | """=============================================================================
Utility functions for easy and pretty file logging.
============================================================================="""
import logging
import numpy as np
import types
import torch
# ------------------------------------------... | 3,234 | 29.518868 | 80 | py |
dpcca | dpcca-master/models/aelinear.py | """=============================================================================
Linear autoencoder.
============================================================================="""
from torch import nn
# ------------------------------------------------------------------------------
class AELinear(nn.Module):
... | 1,086 | 30.057143 | 80 | py |
dpcca | dpcca-master/models/aetanh.py | """=============================================================================
Autoencoder with tanh nonlinearities.
============================================================================="""
import numpy as np
from torch import nn
# --------------------------------------------------------------------------... | 1,537 | 27.481481 | 80 | py |
dpcca | dpcca-master/models/pccasimple.py | """=============================================================================
Probabilistic canonical correlation analysis. For references in comments:
A Probabilistic Interpretation of Canonical Correlation Analysis.
Bach, Jordan (2006).
The EM algorithm for mixtures of factor analyzers.
Ghahraman... | 8,873 | 32.360902 | 80 | py |
dpcca | dpcca-master/models/dpcca.py | """=============================================================================
Deep probabilistic CCA (DPCCA) for histology images and gene expression levels.
============================================================================="""
import torch
from torch import nn
from models import PCCA
import cuda
#... | 5,103 | 32.801325 | 80 | py |
dpcca | dpcca-master/models/dcganae128.py | """=============================================================================
DCGAN-based autoencoder with a 128x128 input. See:
https://github.com/pytorch/examples/issues/70
============================================================================="""
from torch import nn
# -------------------------------... | 3,479 | 36.419355 | 81 | py |
dpcca | dpcca-master/models/aesigmoid.py | """=============================================================================
Autoencoder with sigmoid nonlinearities.
============================================================================="""
import torch
from torch import nn
from torch.nn import functional as F
# --------------------------------------... | 1,661 | 29.777778 | 80 | py |
dpcca | dpcca-master/models/pccavec.py | """=============================================================================
Probabilistic canonical correlation analysis. For references in comments:
A Probabilistic Interpretation of Canonical Correlation Analysis.
Bach, Jordan (2006).
The EM algorithm for mixtures of factor analyzers.
Ghahraman... | 8,576 | 32.244186 | 80 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.