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 |
|---|---|---|---|---|---|---|
GATS | GATS-main/src/data/data_utils.py | import os
import re
import numpy as np
import torch
from pathlib import Path
from tqdm import tqdm
from torch import Tensor
from torch_geometric.data import Dataset
from torch_geometric.datasets import Planetoid, Amazon, Coauthor, CoraFull
from torch_geometric.io.planetoid import index_to_mask
from torch_geometric.tran... | 8,583 | 46.688889 | 119 | py |
GATS | GATS-main/src/model/model.py | import torch
import torch.nn.functional as F
from torch.nn import Linear, Dropout
from torch_geometric.nn import GCNConv, GATConv
def create_model(dataset, args):
"""
Create model with hyperparameters
"""
num_layers = 2
if args.model == 'GAT':
num_hidden = 8
attention_head = [8, ... | 2,831 | 40.647059 | 121 | py |
gutenberg-dialog | gutenberg-dialog-master/gpt2_trainings_scripts/utils.py | # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved. This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from datetime import datetime
import json
import logging
import os
import tarfile
import tempfile
import socket
import to... | 2,711 | 37.742857 | 124 | py |
gutenberg-dialog | gutenberg-dialog-master/gpt2_trainings_scripts/interact.py | # # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import logging
import random
import re
from argparse import ArgumentParser
from itertools import chain
from pprint im... | 9,284 | 43.214286 | 178 | py |
gutenberg-dialog | gutenberg-dialog-master/gpt2_trainings_scripts/train.py | # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
import os
import math
import logging
from pprint import pformat
from argparse import ArgumentParser
from collections import ... | 20,157 | 49.395 | 185 | py |
GIL | GIL-master/train.py | from __future__ import division
from __future__ import print_function
import datetime
import json
import logging
import os
import pickle
import time
import numpy as np
import optimizers
import torch
from config import parser
from models.base_models import NCModel, LPModel
from utils.data_utils import load_data
from u... | 6,668 | 38.696429 | 111 | py |
GIL | GIL-master/models/decoders.py | """Graph decoders."""
import manifolds
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers.hyp_layers import HGATConv
from layers.layers import Linear, GCNConv, GATConv, SAGEConv
import geoopt.manifolds.poincare.math as pmath
import geoopt
class Decoder(nn.Module):
"""
Decoder abstr... | 6,121 | 32.637363 | 119 | py |
GIL | GIL-master/models/base_models.py | import manifolds
import models.encoders as encoders
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from models.decoders import model2decoder
from layers.layers import FermiDiracDecoder
from sklearn.metrics import roc_auc_score, average_precision_score
from utils.eval_utils import ... | 6,007 | 33.728324 | 112 | py |
GIL | GIL-master/models/encoders.py | """Graph encoders."""
import manifolds
import layers.hyp_layers as hyp_layers
import numpy as np
import torch
import torch.nn as nn
from layers.layers import Linear, get_dim_act, GCNConv, GATConv, SGConv, SAGEConv
class Encoder(nn.Module):
"""
Encoder abstract class.
"""
def __init__(self, c):
... | 10,987 | 31.128655 | 113 | py |
GIL | GIL-master/layers/hyp_layers.py | """Hyperbolic layers."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
import geoopt.manifolds.poincare.math as pmath
from layers.layers import GCNConv, GATConv, HFusion, EF... | 10,615 | 31.464832 | 118 | py |
GIL | GIL-master/layers/layers.py | """Euclidean layers."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.module import Module
from torch.nn import Parameter
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.utils import remove_self_loops, softmax
from torch_scatter import scatter_add
impo... | 14,071 | 32.188679 | 117 | py |
GIL | GIL-master/optimizers/radam.py | """Riemannian adam optimizer geoopt implementation (https://github.com/geoopt/)."""
import torch.optim
from manifolds import Euclidean, ManifoldParameter
# in order not to create it at each iteration
_default_manifold = Euclidean()
class OptimMixin(object):
def __init__(self, *args, stabilize=None, **kwargs):
... | 6,970 | 38.834286 | 103 | py |
GIL | GIL-master/optimizers/__init__.py | from torch.optim import Adam
from .radam import RiemannianAdam
| 63 | 20.333333 | 33 | py |
GIL | GIL-master/utils/data_utils.py | """Data utils functions for pre-processing and data loading."""
import os
import pickle as pkl
import sys
import networkx as nx
import numpy as np
import scipy.sparse as sp
import torch
def load_data(args, datapath):
if args.task == 'nc':
data = load_data_nc(args.dataset, args.use_feats, datapath, args.s... | 10,792 | 38.105072 | 125 | py |
GIL | GIL-master/utils/train_utils.py | import os
import numpy as np
import math
import torch
import torch.nn.modules.loss
def format_metrics(metrics, split):
"""Format metric in metric dict for logging."""
return " ".join(
["{}_{}: {:.4f}".format(split, metric_name, metric_val) for metric_name, metric_val in metrics.items()])
def get_di... | 3,699 | 30.092437 | 112 | py |
GIL | GIL-master/utils/math_utils.py | import torch
def cosh(x, clamp=15):
return x.clamp(-clamp, clamp).cosh()
def sinh(x, clamp=15):
return x.clamp(-clamp, clamp).sinh()
def tanh(x, clamp=15):
return x.clamp(-clamp, clamp).tanh()
def arcosh(x):
return Arcosh.apply(x)
def arsinh(x):
return Arsinh.apply(x)
def artanh(x):
... | 1,512 | 21.25 | 83 | py |
GIL | GIL-master/manifolds/base.py | from torch.nn import Parameter
class Manifold(object):
"""
Abstract class to define operations on a manifold.
"""
def __init__(self):
super().__init__()
self.eps = 10e-8
def sqdist(self, p1, p2, c):
"""Squared distance between pairs of points."""
raise NotImplement... | 2,413 | 28.439024 | 106 | py |
GIL | GIL-master/manifolds/poincare.py | import torch
from manifolds.base import Manifold
from torch.autograd import Function
from utils.math_utils import artanh, tanh
class PoincareBall(Manifold):
"""
PoicareBall Manifold class.
We use the following convention: x0^2 + x1^2 + ... + xd^2 < 1 / c
Note that 1/sqrt(c) is the Poincare ball radi... | 4,639 | 34.968992 | 120 | py |
cbp | cbp-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# cbp documentation build configuration file, created by
# sphinx-quickstart on Thu May 14 12:44:04 2020.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... | 5,553 | 30.027933 | 79 | py |
papilledema | papilledema-main/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io, os, sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package metadata
NAME = "ppma"
DESCRIPTION = "Papilledema Identification in Fundus Images"
URL = "https://github.com/klean2050/papilledema"
EMAIL = "k.avramidis@windowslive... | 3,380 | 26.713115 | 86 | py |
papilledema | papilledema-main/src/training.py | from __future__ import print_function
from __future__ import division
import torch, torch.nn as nn
import os, copy, numpy as np
import matplotlib.pyplot as plt, cv2 as cv
import torch.optim as optim
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split, StratifiedShuffleSplit
from... | 8,395 | 34.576271 | 86 | py |
papilledema | papilledema-main/src/dataset.py | import numpy as np, pandas as pd, os
import matplotlib.pyplot as plt
from torchvision import transforms
from torch.utils.data import Dataset
from PIL import Image, ImageEnhance
from random import uniform
from .utils import *
class PapDataset(Dataset):
def __init__(self, root, subjects, train):
self.root_... | 4,174 | 32.4 | 87 | py |
papilledema | papilledema-main/src/models.py | import torch.nn as nn, torch
from torchvision import models
from torch.autograd import Function
class GradReverse(Function):
@staticmethod
def forward(_, x):
return x.view_as(x)
@staticmethod
def backward(_, grad_output):
return grad_output.neg()
class Sub_Adaptor(nn.Module):
de... | 3,036 | 31.308511 | 70 | py |
papilledema | papilledema-main/src/utils/helper.py | import torch, clip, os, numpy as np
import matplotlib.pyplot as plt, cv2
import pandas as pd, pickle
from PIL import Image
from tqdm import tqdm
from sklearn.metrics import roc_auc_score, roc_curve
def get_embeddings(path="data/cropped/"):
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preproc... | 3,083 | 33.651685 | 84 | py |
PatchUp | PatchUp-master/main.py | #!/usr/bin/env python
from __future__ import division
import os, sys
from modules.cutmix import CutMix
from modules.cutout import Cutout
from modules.patchup import PatchUpMode
from utility.adversarial_attack import run_test_adversarial
from torchvision import transforms
sys.path.append(os.path.dirname(os.path.dirname... | 25,535 | 43.179931 | 130 | py |
PatchUp | PatchUp-master/data_loader.py | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import torch
from torchvision import datasets, transforms
import numpy as np
import torchvision
import matplotlib.pyplot as plt
import argparse
def per_image_standardization(x):
y = x.view(-1, x.shape[1] * x.shape[2] * x.... | 18,396 | 47.413158 | 120 | py |
PatchUp | PatchUp-master/modules/cutmix.py | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import numpy as np
import torch
from utility.utils import device
class CutMix(object):
"""
The following code was implemented by the authors of CutMix paper.
https://arxiv.org/abs/1905.04899
following is the ... | 1,589 | 32.125 | 91 | py |
PatchUp | PatchUp-master/modules/drop_block.py | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import torch
import torch.nn as nn
import torch.nn.functional as F
if torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("cpu")
class DropBlock(nn.Module):
"""
this implement... | 2,597 | 43.033898 | 117 | py |
PatchUp | PatchUp-master/modules/cutout.py | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import numpy as np
import torch
from utility.utils import device
class Cutout(object):
"""Randomly mask out one or more patches from an image.
The following code was implemented by the authors of cutout paper.
ht... | 1,782 | 28.229508 | 82 | py |
PatchUp | PatchUp-master/modules/patchup.py | import os, sys
from enum import Enum
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class PatchUpMode(Enum):
SOFT = 'soft'
HARD = 'hard'
class PatchUp(nn.Module):
"""
PatchUp Module.... | 6,797 | 47.212766 | 121 | py |
PatchUp | PatchUp-master/utility/utils.py | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import matplotlib
import shutil
matplotlib.use('agg')
import matplotlib.pyplot as plt
import... | 8,194 | 33.004149 | 120 | py |
PatchUp | PatchUp-master/utility/adversarial_attack.py | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import torch
from torch.autograd import Variable, grad
from utility.utils import to_var, device
def fgsm(classifier, x, loss_func, epsilon, initial_perturb=None):
"""
This function is responsible to creat adversarial ... | 3,266 | 34.901099 | 118 | py |
PatchUp | PatchUp-master/utility/activation_study.py | from __future__ import division
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import matplotlib as mpl
mpl.use('Agg')
from utility.utils import *
import models
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import _pickle as pickle
from data_loader im... | 7,362 | 40.134078 | 130 | py |
PatchUp | PatchUp-master/models/preresnet.py | ### dropout has been removed in this code. original code had dropout#####
## https://github.com/kuangliu/pytorch-cifar/blob/master/models/resnet.py
'''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Ima... | 11,064 | 42.90873 | 120 | py |
PatchUp | PatchUp-master/models/wide_resnet.py | ### dropout has been removed in this code. original code had dropout#####
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
im... | 9,439 | 40.585903 | 128 | py |
FewX | FewX-master/fsod_train_net.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
TridentNet Training Script.
This script is a simplified version of the training script in detectron2/tools.
"""
import os
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
fr... | 3,400 | 27.341667 | 92 | py |
FewX | FewX-master/fewx/solver/build.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from enum import Enum
from typing import Any, Callable, Dict, Iterable, List, Set, Type, Union
import torch
from detectron2.config import CfgNode
from detectron2.solver.lr_scheduler import WarmupCosineLR, WarmupMultiStepLR
_GradientClipperInput =... | 5,975 | 34.571429 | 94 | py |
FewX | FewX-master/fewx/evaluation/coco_evaluation.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import contextlib
import copy
import io
import itertools
import json
import logging
import numpy as np
import os
import pickle
from collections import OrderedDict
import pycocotools.mask as mask_util
import torch
from fvcore.common.file_io import Pa... | 25,830 | 41.766556 | 259 | py |
FewX | FewX-master/fewx/layers/conv_with_kaiming_uniform.py | from torch import nn
from detectron2.layers import Conv2d
from .deform_conv import DFConv2d
from detectron2.layers.batch_norm import get_norm
def conv_with_kaiming_uniform(
norm=None, activation=None,
use_deformable=False, use_sep=False):
def make_conv(
in_channels, out_channels, kernel_s... | 1,652 | 30.188679 | 68 | py |
FewX | FewX-master/fewx/layers/deform_conv.py | import torch
from torch import nn
from detectron2.layers import Conv2d
class _NewEmptyTensorOp(torch.autograd.Function):
@staticmethod
def forward(ctx, x, new_shape):
ctx.shape = x.shape
return x.new_empty(new_shape)
@staticmethod
def backward(ctx, grad):
shape = ctx.shape
... | 3,992 | 32 | 104 | py |
FewX | FewX-master/fewx/layers/iou_loss.py | import torch
from torch import nn
class IOULoss(nn.Module):
"""
Intersetion Over Union (IoU) loss which supports three
different IoU computations:
* IoU
* Linear IoU
* gIoU
"""
def __init__(self, loc_loss_type='iou'):
super(IOULoss, self).__init__()
self.loc_loss_type =... | 2,203 | 31.411765 | 65 | py |
FewX | FewX-master/fewx/layers/misc.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
helper class that supports empty tensors on some nn functions.
Ideally, add support directly in PyTorch to empty tensors in
those functions.
This can be removed once https://github.com/pytorch/pytorch/issues/12013
is implemented
"""
import mat... | 2,077 | 31.984127 | 86 | py |
FewX | FewX-master/fewx/layers/naive_group_norm.py | import torch
from torch.nn import Module, Parameter
from torch.nn import init
class NaiveGroupNorm(Module):
r"""NaiveGroupNorm implements Group Normalization with the high-level matrix operations in PyTorch.
It is a temporary solution to export GN by ONNX before the official GN can be exported by ONNX.
Th... | 2,977 | 40.943662 | 103 | py |
FewX | FewX-master/fewx/utils/comm.py | import torch
import torch.nn.functional as F
import torch.distributed as dist
from detectron2.utils.comm import get_world_size
def reduce_sum(tensor):
world_size = get_world_size()
if world_size < 2:
return tensor
tensor = tensor.clone()
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
retur... | 1,394 | 23.910714 | 68 | py |
FewX | FewX-master/fewx/data/dataset_mapper.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import logging
import numpy as np
import torch
from fvcore.common.file_io import PathManager
from PIL import Image
from detectron2.data import detection_utils as utils
from detectron2.data import transforms as T
import pandas as pd
fro... | 12,313 | 46 | 238 | py |
FewX | FewX-master/fewx/data/build.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import bisect
import copy
import itertools
import logging
import numpy as np
import operator
import pickle
import torch.utils.data
from fvcore.common.file_io import PathManager
from tabulate import tabulate
from termcolor import colored
from detect... | 8,964 | 42.946078 | 249 | py |
FewX | FewX-master/fewx/modeling/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .fsod import FsodRCNN, FsodRes5ROIHeads, FsodFastRCNNOutputLayers, FsodRPN
_EXCLUDE = {"torch", "ShapeSpec"}
__all__ = [k for k in globals().keys() if k not in _EXCLUDE and not k.startswith("_")]
| 273 | 44.666667 | 86 | py |
FewX | FewX-master/fewx/modeling/fsod/fsod_roi_heads.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import inspect
import logging
import numpy as np
from typing import Dict, List, Optional, Tuple, Union
import torch
from torch import nn
from detectron2.config import configurable
from detectron2.layers import ShapeSpec, nonzero_tuple
from detectro... | 8,035 | 37.085308 | 110 | py |
FewX | FewX-master/fewx/modeling/fsod/fsod_rpn.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn.functional as F
from fvcore.nn import smooth_l1_loss
from torch import nn
from detectron2.config import configurable
from detectron2.layers import ShapeSpec, cat
from detec... | 21,575 | 43.856549 | 112 | py |
FewX | FewX-master/fewx/modeling/fsod/fsod_fast_rcnn.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import torch
from fvcore.nn import smooth_l1_loss
from torch import nn
from torch.nn import functional as F
from detectron2.config import configurable
from detectron2.layers import Linear, ShapeSpec, batched_nms, cat, nonzero_tuple
f... | 26,668 | 42.648118 | 128 | py |
FewX | FewX-master/fewx/modeling/fsod/fsod_rcnn.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import numpy as np
import torch
from torch import nn
from detectron2.data.detection_utils import convert_image_to_rgb
from detectron2.structures import ImageList, Boxes, Instances
from detectron2.utils.events import get_event_storage... | 19,251 | 45.956098 | 209 | py |
phitnet | phitnet-master/inference.py | import cv2
import argparse
import torch.utils.data
from train_test_functions import prepare_train, custom_transforms
from imageio import imsave
import os
from train_test_functions.utils import tensor2array
import torch
from train_test_functions.sequence_folders_list import SequenceFolderPlane
import numpy as np
parser... | 3,924 | 34.36036 | 116 | py |
phitnet | phitnet-master/test_patchmatching.py | import torch.backends.cudnn as cudnn
import torch.utils.data
from train_test_functions import prepare_train
import os
from train_test_functions.train_test_run_inference_ import run_pm_images_rep as run_inf
from train_test_functions.run_patch_matching import run_patch_matching_3 as run_pm
import arguments
import argpars... | 3,725 | 35.891089 | 121 | py |
phitnet | phitnet-master/test_registration.py | from train_test_functions.test_tasks_utils import get_psnr_rmse
from train_test_functions.test_tasks_utils import affine_transform as aftf
import torch.utils.data
from train_test_functions.utils import tensor2array
import torch
import numpy as np
import torchvision.transforms.functional as TVF
import cv2
import torch.... | 9,299 | 41.272727 | 138 | py |
phitnet | phitnet-master/train.py | import numpy as np
import torch.backends.cudnn as cudnn
import torch.utils.data
from train_test_functions import prepare_train
from train_test_functions import run_epoch
from train_test_functions import utils
import os
from train_test_functions.train_test_run_inference_ import run_pm_images_rep as run_inf
from train_te... | 3,729 | 46.820513 | 130 | py |
phitnet | phitnet-master/train_test_functions/custom_transforms.py | from __future__ import division
import numpy as np
import random
from PIL import Image
import torchvision.transforms.functional as TVF
'''Set of tranform random routines that takes list of inputs as arguments,
in order to have random but coherent transformations.'''
class Compose(object):
def __init__(self, trans... | 2,566 | 31.493671 | 163 | py |
phitnet | phitnet-master/train_test_functions/loss_functions.py | from __future__ import division
import torch
import torch.nn.functional as F
import torch.nn as NN
from train_test_functions.utils import square_center_crop
def corr_dist_batch(x1, x2):
return 1 - ((x1 * x2).sum(-1).sum(-1) * torch.rsqrt((x1 ** 2).sum(-1).sum(-1) * (x2 ** 2).sum(-1).sum(-1)))
def get_dfunc(args):... | 4,805 | 47.545455 | 150 | py |
phitnet | phitnet-master/train_test_functions/sequence_folders_list.py | import os
import torch.utils.data as data
import numpy as np
import PIL
from path import Path
import random
from PIL import Image
class SequenceFolder(data.Dataset):
def __init__(self, root, transform=None, seed=None, train=True, grayscale=False, hsv=False):
np.random.seed(seed)
random.seed(seed)
... | 6,945 | 38.691429 | 130 | py |
phitnet | phitnet-master/train_test_functions/train_test_run_inference_.py | import argparse
import torch.utils.data
from train_test_functions import prepare_train, custom_transforms
from imageio import imsave
import os
from train_test_functions.utils import tensor2array
import torch
from train_test_functions.sequence_folders_list import SequenceFolder_Inference
import numpy as np
parser = arg... | 7,295 | 36.608247 | 116 | py |
phitnet | phitnet-master/train_test_functions/utils.py | from __future__ import division
import torch
from path import Path
import datetime
def save_path_formatter(args, parser):
def is_default(key, value):
return value == parser.get_default(key)
args_dict = vars(args)
data_folder_name = str(Path(args_dict['data']).normpath().name)
folder_string = [d... | 2,093 | 32.238095 | 85 | py |
phitnet | phitnet-master/train_test_functions/run_epoch.py | import time
import torch.utils.data
from train_test_functions.utils import tensor2array
from train_test_functions import loss_functions
from train_test_functions.logger import AverageMeter
import numpy as np
import torch
import torch.nn.functional as F
from train_test_functions.utils import square_center_crop
import ra... | 15,375 | 62.27572 | 149 | py |
phitnet | phitnet-master/train_test_functions/prepare_train.py | import sys
import os
from train_test_functions import custom_transforms
import torch
import models
from tensorboardX import SummaryWriter
from train_test_functions.sequence_folders_list import SequenceFolder, SequenceFolder_Validation_Full
from train_test_functions.utils import save_path_formatter
from path import Pat... | 8,501 | 34.573222 | 113 | py |
phitnet | phitnet-master/models/InvRepNet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
def inception_branch(in_planes,inception_params):
k_size=inception_params[2]
batch_norm=inception_params[3]
reflection_pad=inception_params[4]
if batch_norm == True:
return nn.Sequential(
nn... | 11,270 | 35.241158 | 126 | py |
denspi | denspi-master/bert.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | 21,102 | 43.056367 | 118 | py |
denspi | denspi-master/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | 6,754 | 39.692771 | 116 | py |
denspi | denspi-master/phrase.py | import torch
from torch import nn
from torch.nn.functional import binary_cross_entropy_with_logits, embedding
from bert import BertModel, BERTLayerNorm, SparseAttention
class BertWrapper(nn.Module):
"""
Abides phrase model's encoder spec:
1. (input_ids, mask) -> input_vectors
2. input_ids[0] is a spe... | 10,848 | 43.281633 | 111 | py |
denspi | denspi-master/run_piqa.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import collections
import logging
import json
import os
import random
from time import time
import h5py
from torch.optim import Adam
from tqdm import tqdm as tqdm_
import numpy as np
import to... | 43,992 | 49.566667 | 120 | py |
denspi | denspi-master/post.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, The HugginFace Inc. team and University of Washington.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.... | 25,035 | 42.240069 | 119 | py |
denspi | denspi-master/pre.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, The HugginFace Inc. team and University of Washington.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.... | 27,677 | 39.943787 | 118 | py |
denspi | denspi-master/open/mips.py | import argparse
import json
import os
import random
from collections import namedtuple, Counter
from time import time
import h5py
import numpy as np
import faiss
import torch
from tqdm import tqdm
def int8_to_float(num, offset, factor):
return num.astype(np.float32) / factor + offset
def adjust(each):
last... | 11,183 | 44.096774 | 120 | py |
seld-net | seld-net-master/keras_model.py | #
# The SELDnet architecture
#
from keras.layers import Bidirectional, Conv2D, MaxPooling2D, Input, MaxPooling3D, Conv3D, merge
from keras.layers.core import Dense, Activation, Dropout, Reshape, Permute
from keras.layers.recurrent import GRU
from keras.layers.normalization import BatchNormalization
from keras.models i... | 2,213 | 36.525424 | 101 | py |
seld-net | seld-net-master/seld.py | #
# A wrapper script that trains the SELDnet. The training stops when the SELD error (check paper) stops improving.
#
import os
import sys
import numpy as np
import matplotlib.pyplot as plot
import cls_data_generator
import evaluation_metrics
import keras_model
import parameter
import utils
import time
from IPython im... | 9,904 | 42.634361 | 122 | py |
DGNN_analysis | DGNN_analysis-main/ASTGNN/utils2.py | #includes predict_and_save_results function from model/ASTGNN.py with additional codes for profiling
import os
#import numpy as np
import torch
import torch.utils.data
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from lib.metrics import masked_mape_np
from lib.utils imp... | 6,058 | 39.939189 | 232 | py |
DGNN_analysis | DGNN_analysis-main/ASTGNN/train_ASTGNN.py | #!/usr/bin/env python
# coding: utf-8
import sys
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import os
from time import time
import shutil
import argparse
import configparser
from model.ASTGNN import make_model
from lib.utils import get_adjacency_matrix, get_adjacency_matrix_2direc... | 11,352 | 35.504823 | 306 | py |
DGNN_analysis | DGNN_analysis-main/ASTGNN/model/ASTGNN.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
import math
import numpy as np
from lib.utils import norm_Adj
def clones(module, N):
'''
Produce N identical layers.
:param module: nn.Module
:param N: int
:return: torch.nn.ModuleList
'''
return nn.ModuleList([c... | 40,679 | 46.247387 | 399 | py |
DGNN_analysis | DGNN_analysis-main/ASTGNN/lib/utils.py | import os
import numpy as np
import torch
import torch.utils.data
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from .metrics import masked_mape_np
from time import time
from scipy.sparse.linalg import eigs
def re_normalization(x, mean, std):
x = x * std + mean
... | 76,263 | 41.605587 | 207 | py |
DGNN_analysis | DGNN_analysis-main/LDG_DyRep/main.py | import numpy as np
import sys
import os
import time
import copy
import datetime
import pickle
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
import argparse
import platform
import subprocess
from sklearn.metrics import roc_auc_sc... | 25,965 | 44.236934 | 161 | py |
DGNN_analysis | DGNN_analysis-main/LDG_DyRep/data_loader.py | import numpy as np
import datetime
import torch
import torch.utils
from datetime import datetime, timezone
class EventsDataset(torch.utils.data.Dataset):
'''
Base class for event datasets
'''
def __init__(self, TZ=None):
self.TZ = TZ # timezone.utc
# Implement here these fields (see... | 3,001 | 37.987013 | 104 | py |
DGNN_analysis | DGNN_analysis-main/LDG_DyRep/encoder.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class LinearEncoder(nn.Module):
def __init__(self, n_in, n_out, sym=True):
super(LinearEncoder, self).__init__()
self.fc = nn.Linear(n_in * 2, n_out)
self.sym = sym
self.init_weights()
def i... | 8,021 | 35.298643 | 118 | py |
DGNN_analysis | DGNN_analysis-main/LDG_DyRep/dyrep.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from encoder import *
from utils import *
from torch.profiler import profile, record_function, ProfilerActivity
class DyRep(nn.Module):
def __init__(self,
node_embeddings,
# n_event_types,
... | 38,846 | 45.246429 | 167 | py |
DGNN_analysis | DGNN_analysis-main/TGAT_NVIDIA/module.py | import logging
import numpy as np
import torch
import argparse
import torch.nn as nn
import torch.nn.functional as F
from torch.profiler import profile, record_function, ProfilerActivity
#parser = argparse.ArgumentParser('Interface for TGAT experiments on link predictions')
#args = parser.parse_args()
class MergeLay... | 25,196 | 41.70678 | 151 | py |
DGNN_analysis | DGNN_analysis-main/TGAT_NVIDIA/graph.py | import numpy as np
import torch
class NeighborFinder:
def __init__(self, adj_list, uniform=False):
"""
Params
------
node_idx_l: List[int]
node_ts_l: List[int]
off_set_l: List[int], such that node_idx_l[off_set_l[i]:off_set_l[i + 1]] = adjacent_list[i]
"""
... | 6,042 | 37.246835 | 136 | py |
DGNN_analysis | DGNN_analysis-main/TGAT_NVIDIA/learn_edge.py | """Unified interface to all dynamic graph model experiments"""
import math
import logging
import time
import random
import sys
import argparse
import torch
import pandas as pd
import numpy as np
#import numba
from sklearn.metrics import average_precision_score
from sklearn.metrics import f1_score
from sklearn.metrics... | 14,152 | 40.749263 | 169 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/egcn_o.py | import utils as u
import torch
from torch.nn.parameter import Parameter
import torch.nn as nn
import math
from torch.profiler import profile, record_function, ProfilerActivity
class EGCN(torch.nn.Module):
def __init__(self, args, activation, device='cpu', skipfeats=False):
super().__init__()
GRCU_... | 6,107 | 32.56044 | 105 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/link_pred_tasker.py | import torch
import taskers_utils as tu
import utils as u
class Link_Pred_Tasker():
'''
Creates a tasker object which computes the required inputs for training on a link prediction
task. It receives a dataset object which should have two attributes: nodes_feats and edges, this
makes the tasker independent of the ... | 6,029 | 34.05814 | 105 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/run_exp.py | import utils as u
import torch
import torch.distributed as dist
import numpy as np
import time
import random
#datasets
import bitcoin_dl as bc
#import elliptic_temporal_dl as ell_temp
#import uc_irv_mess_dl as ucim
#import auto_syst_dl as aus
#import sbm_dl as sbm
#import reddit_dl as rdt
#taskers
import link_pred_t... | 10,376 | 37.576208 | 195 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/node_cls_tasker.py | import taskers_utils as tu
import torch
import utils as u
class Node_Cls_Tasker():
def __init__(self,args,dataset):
self.data = dataset
self.max_time = dataset.max_time
self.args = args
self.num_classes = 2
self.feats_per_node = dataset.feats_per_node
self.nodes_labels_times = dataset.nodes_labels_ti... | 5,086 | 28.068571 | 144 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/self-attention.py | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 11 00:30:52 2022
@author: chenhanqiou
"""
import torch
from torch.nn.functional import softmax
x = [
[1, 0, 1, 0], # Input 1
[0, 2, 0, 2], # Input 2
[1, 1, 1, 1] # Input 3
]
x = torch.tensor(x, dtype=torch.float32)
print(" the input shape of x is:",x.shape)
w_... | 3,080 | 26.026316 | 113 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/egcn_h.py | import utils as u
import torch
from torch.nn.parameter import Parameter
import torch.nn as nn
import math
from torch.profiler import profile, record_function, ProfilerActivity
class EGCN(torch.nn.Module):
def __init__(self, args, activation, device='cpu', skipfeats=False):
super().__init__()
GRCU_a... | 6,201 | 32.89071 | 105 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/utils.py | import argparse
import yaml
import torch
import numpy as np
import time
import random
import math
def pad_with_last_col(matrix,cols):
out = [matrix]
pad = [matrix[:,[-1]]] * (cols - matrix.size(1))
out.extend(pad)
return torch.cat(out,dim=1)
def pad_with_last_val(vect,k):
device = 'cuda' if vect.i... | 6,820 | 41.63125 | 216 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/logger.py | import logging
import pprint
import sys
import datetime
import torch
import utils
import matplotlib.pyplot as plt
import time
from sklearn.metrics import average_precision_score
from scipy.sparse import coo_matrix
import numpy as np
class Logger():
def __init__(self, args, num_classes, minibatch_log_interval=10... | 15,098 | 41.894886 | 231 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/splitter.py | from torch.utils.data import Dataset, DataLoader
import torch
import numpy as np
import utils as u
class splitter():
'''
creates 3 splits
train
dev
test
'''
def __init__(self,args,tasker):
if tasker.is_static: #### For static datsets
assert args.train_p... | 5,002 | 36.901515 | 147 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/Cross_Entropy.py | import torch
import utils as u
class Cross_Entropy(torch.nn.Module):
"""docstring for Cross_Entropy"""
def __init__(self, args, dataset):
super().__init__()
weights = torch.tensor(args.class_weights).to(args.device)
self.weights = self.dyn_scale(args.task, dataset, weights)
... | 2,651 | 33.894737 | 106 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/taskers_utils.py | import torch
import utils as u
import numpy as np
import time
ECOLS = u.Namespace({'source': 0,
'target': 1,
'time': 2,
'label':3}) #--> added for edge_cls
# def get_2_hot_deg_feats(adj,max_deg_out,max_deg_in,num_nodes):
# #For now it'll just return a... | 8,690 | 32.298851 | 106 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/models.py | import torch
import utils as u
from argparse import Namespace
from torch.nn.parameter import Parameter
from torch.nn import functional as F
import torch.nn as nn
import math
class Sp_GCN(torch.nn.Module):
def __init__(self,args,activation):
super().__init__()
self.activation = activation
se... | 7,005 | 35.113402 | 111 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/edge_cls_tasker.py | import torch
import taskers_utils as tu
import utils as u
class Edge_Cls_Tasker():
def __init__(self,args,dataset):
self.data = dataset
#max_time for link pred should be one before
self.max_time = dataset.max_time
self.args = args
self.num_classes = dataset.num_classes
if not args.use_1_hot_node_feats:
... | 2,442 | 27.741176 | 77 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/trainer.py | import torch
import utils as u
import logger
import time
import pandas as pd
import numpy as np
from torch.profiler import profile, record_function, ProfilerActivity
class Trainer():
def __init__(self,args, splitter, gcn, classifier, comp_loss, dataset, num_classes):
self.args = args
self.splitter = splitter
se... | 8,834 | 34.625 | 229 | py |
DGNN_analysis | DGNN_analysis-main/EvolveGCN/bitcoin_dl.py | import torch
import utils as u
import os
class bitcoin_dataset():
def __init__(self,args):
assert args.task in ['link_pred', 'edge_cls'], 'bitcoin only implements link_pred or edge_cls'
self.ecols = u.Namespace({'FromNodeId': 0,
'ToNodeId': 1,
... | 4,968 | 37.51938 | 109 | py |
DGNN_analysis | DGNN_analysis-main/TGN/modules/message_function.py | from torch import nn
class MessageFunction(nn.Module):
"""
Module which computes the message for a given interaction.
"""
def compute_message(self, raw_messages):
return None
class MLPMessageFunction(MessageFunction):
def __init__(self, raw_message_dimension, message_dimension):
super(MLPMessageF... | 1,021 | 23.926829 | 80 | py |
DGNN_analysis | DGNN_analysis-main/TGN/modules/memory.py | import torch
from torch import nn
from collections import defaultdict
from copy import deepcopy
class Memory(nn.Module):
def __init__(self, n_nodes, memory_dimension, input_dimension, message_dimension=None,
device="cpu", combination_method='sum'):
super(Memory, self).__init__()
self.n_node... | 2,412 | 30.75 | 98 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.