repo stringlengths 2 99 | file stringlengths 14 239 | code stringlengths 20 3.99M | file_length int64 20 3.99M | avg_line_length float64 9.73 128 | max_line_length int64 11 86.4k | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
TiKick | TiKick-main/setup.py |
import os
from setuptools import setup, find_packages
import setuptools
def get_version() -> str:
# https://packaging.python.org/guides/single-sourcing-package-version/
init = open(os.path.join("tmarl", "__init__.py"), "r").read().split()
return init[init.index("__version__") + 2][1:-1]
setup(
name=... | 1,788 | 35.510204 | 74 | py |
TiKick | TiKick-main/tmarl/networks/policy_network.py |
import torch
import torch.nn as nn
from tmarl.networks.utils.util import init, check
from tmarl.networks.utils.mlp import MLPBase, MLPLayer
from tmarl.networks.utils.rnn import RNNLayer
from tmarl.networks.utils.act import ACTLayer
from tmarl.networks.utils.popart import PopArt
from tmarl.utils.util import get_shape_... | 5,558 | 41.113636 | 181 | py |
TiKick | TiKick-main/tmarl/networks/utils/distributions.py | import torch
import torch.nn as nn
from .util import init
"""
Modify standard PyTorch distributions so they are compatible with this code.
"""
# Standardize distribution interfaces
# Categorical
class FixedCategorical(torch.distributions.Categorical):
def sample(self):
return super().sample().unsqueeze(... | 3,466 | 27.891667 | 86 | py |
TiKick | TiKick-main/tmarl/networks/utils/mlp.py |
import torch.nn as nn
from .util import init, get_clones
class MLPLayer(nn.Module):
def __init__(self, input_dim, hidden_size, layer_N, use_orthogonal, activation_id):
super(MLPLayer, self).__init__()
self._layer_N = layer_N
active_func = [nn.Tanh(), nn.ReLU(), nn.LeakyReLU(), nn.ELU()]... | 2,116 | 32.603175 | 98 | py |
TiKick | TiKick-main/tmarl/networks/utils/popart.py | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class PopArt(torch.nn.Module):
def __init__(self, input_shape, output_shape, norm_axes=1, beta=0.99999, epsilon=1e-5, device=torch.device("cpu")):
super(PopArt, self).__init__()
self.bet... | 3,796 | 38.968421 | 119 | py |
TiKick | TiKick-main/tmarl/networks/utils/util.py |
import copy
import numpy as np
import torch
import torch.nn as nn
def init(module, weight_init, bias_init, gain=1):
weight_init(module.weight.data, gain=gain)
bias_init(module.bias.data)
return module
def get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
def che... | 426 | 21.473684 | 76 | py |
TiKick | TiKick-main/tmarl/networks/utils/act.py |
from .distributions import Bernoulli, Categorical, DiagGaussian
import torch
import torch.nn as nn
class ACTLayer(nn.Module):
def __init__(self, action_space, inputs_dim, use_orthogonal, gain):
super(ACTLayer, self).__init__()
self.multidiscrete_action = False
self.continuous_action = Fal... | 7,195 | 46.342105 | 121 | py |
TiKick | TiKick-main/tmarl/networks/utils/rnn.py |
import torch
import torch.nn as nn
class RNNLayer(nn.Module):
def __init__(self, inputs_dim, outputs_dim, recurrent_N, use_orthogonal):
super(RNNLayer, self).__init__()
self._recurrent_N = recurrent_N
self._use_orthogonal = use_orthogonal
self.rnn = nn.GRU(inputs_dim, outputs_dim... | 2,816 | 34.2125 | 132 | py |
TiKick | TiKick-main/tmarl/drivers/shared_distributed/base_driver.py | import numpy as np
import torch
def _t2n(x):
return x.detach().cpu().numpy()
class Driver(object):
def __init__(self, config, client=None):
self.all_args = config['all_args']
self.envs = config['envs']
self.eval_envs = config['eval_envs']
self.device = config['device']
... | 4,244 | 39.04717 | 126 | py |
TiKick | TiKick-main/tmarl/drivers/shared_distributed/football_driver.py | from tqdm import tqdm
import numpy as np
from tmarl.drivers.shared_distributed.base_driver import Driver
def _t2n(x):
return x.detach().cpu().numpy()
class FootballDriver(Driver):
def __init__(self, config):
super(FootballDriver, self).__init__(config)
def run(self):
self.trainer.prep_... | 4,315 | 42.16 | 102 | py |
TiKick | TiKick-main/tmarl/algorithms/r_mappo_distributed/mappo_algorithm.py | import torch
from tmarl.utils.valuenorm import ValueNorm
# implement the loss of the MAPPO here
class MAPPOAlgorithm():
def __init__(self,
args,
init_module,
device=torch.device("cpu")):
self.device = device
self.tpdv = dict(dtype=torch.float32, ... | 2,234 | 38.210526 | 147 | py |
TiKick | TiKick-main/tmarl/algorithms/r_mappo_distributed/mappo_module.py | import torch
from tmarl.networks.policy_network import PolicyNetwork
class MAPPOModule:
def __init__(self, args, obs_space, share_obs_space, act_space, device=torch.device("cpu")):
self.device = device
self.lr = args.lr
self.critic_lr = args.critic_lr
self.opti_eps = args.... | 1,050 | 41.04 | 135 | py |
TiKick | TiKick-main/tmarl/loggers/utils.py |
import time
def timer(function):
"""
装饰器函数timer
:param function:想要计时的函数
:return:
"""
def wrapper(*args, **kwargs):
time_start = time.time()
res = function(*args, **kwargs)
cost_time = time.time() - time_start
print("{} running time: {}s".format(function.__name... | 1,011 | 27.914286 | 74 | py |
TiKick | TiKick-main/tmarl/runners/base_evaluator.py |
import random
import numpy as np
import torch
from tmarl.configs.config import get_config
from tmarl.runners.base_runner import Runner
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
class Evaluator(Runner):
def __init__(sel... | 3,402 | 28.08547 | 97 | py |
TiKick | TiKick-main/tmarl/runners/base_runner.py |
import os
import random
import socket
import setproctitle
import numpy as np
from pathlib import Path
import torch
from tmarl.configs.config import get_config
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
class Runner:
d... | 1,079 | 22.478261 | 74 | py |
TiKick | TiKick-main/tmarl/runners/football/football_evaluator.py |
import sys
import os
from pathlib import Path
from tmarl.runners.base_evaluator import Evaluator
from tmarl.envs.football.football import RllibGFootball
from tmarl.envs.env_wrappers import ShareSubprocVecEnv, ShareDummyVecEnv
class FootballEvaluator(Evaluator):
def __init__(self, argv):
super(FootballE... | 3,181 | 34.355556 | 97 | py |
TiKick | TiKick-main/tmarl/utils/multi_discrete.py | import gym
import numpy as np
# An old version of OpenAI Gym's multi_discrete.py. (Was getting affected by Gym updates)
class MultiDiscrete(gym.Space):
"""
- The multi-discrete action space consists of a series of discrete action spaces with different parameters
- It can be adapted to both a Discrete actio... | 2,346 | 50.021739 | 198 | py |
TiKick | TiKick-main/tmarl/utils/valuenorm.py |
import numpy as np
import torch
import torch.nn as nn
class ValueNorm(nn.Module):
""" Normalize a vector of observations - across the first norm_axes dimensions"""
def __init__(self, input_shape, norm_axes=1, beta=0.99999, per_element_update=False, epsilon=1e-5, device=torch.device("cpu")):
super(V... | 3,110 | 37.8875 | 131 | py |
TiKick | TiKick-main/tmarl/utils/util.py |
import copy
import numpy as np
import math
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
from torch.autograd import Variable
from gym.spaces import Box, Discrete, Tuple
def check(input):
if type(input) == np.ndarray:
return torch.from_numpy... | 13,893 | 31.846336 | 122 | py |
TiKick | TiKick-main/tmarl/utils/segment_tree.py | import numpy as np
def unique(sorted_array):
"""
More efficient implementation of np.unique for sorted arrays
:param sorted_array: (np.ndarray)
:return:(np.ndarray) sorted_array without duplicate elements
"""
if len(sorted_array) == 1:
return sorted_array
left = sorted_array[:-1]
... | 6,859 | 40.325301 | 119 | py |
TiKick | TiKick-main/tmarl/utils/gpu_mem_track.py |
import gc
import datetime
import inspect
import torch
import numpy as np
dtype_memory_size_dict = {
torch.float64: 64/8,
torch.double: 64/8,
torch.float32: 32/8,
torch.float: 32/8,
torch.float16: 16/8,
torch.half: 16/8,
torch.int64: 64/8,
torch.long: 64/8,
torch.int32: 32/8,
t... | 4,432 | 36.888889 | 129 | py |
TiKick | TiKick-main/tmarl/utils/modelsize_estimate.py |
import torch.nn as nn
import numpy as np
def modelsize(model, input, type_size=4):
para = sum([np.prod(list(p.size())) for p in model.parameters()])
# print('Model {} : Number of params: {}'.format(model._get_name(), para))
print('Model {} : params: {:4f}M'.format(model._get_name(), para * type_size / 10... | 1,428 | 34.725 | 116 | py |
TiKick | TiKick-main/scripts/football/replay2video.py |
"""Script allowing to replay a given trace file.
Example usage:
python replay.py --trace_file=/tmp/dumps/shutdown_20190521-165136974075.dump
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tmarl.envs.football.env import script_helpers
from... | 1,389 | 31.325581 | 102 | py |
criterion.rs | criterion.rs-master/benches/benchmarks/external_process.py | import time
import sys
def fibonacci(n):
if n == 0 or n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
MILLIS = 1000
MICROS = MILLIS * 1000
NANOS = MICROS * 1000
def benchmark():
depth = int(sys.argv[1])
for line in sys.stdin:
iters = int(line.strip())
# Setup
... | 603 | 15.324324 | 46 | py |
RobDanns | RobDanns-main/deep_learning/yaml_gen.py |
"""Generate yaml files for experiment configurations."""
import yaml
# import math
import os
import re
import argparse
import numpy as np
import shutil
def parse_args():
"""Parses the arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--task',
dest='task',
h... | 16,638 | 38.058685 | 138 | py |
RobDanns | RobDanns-main/deep_learning/tools/corruptions-inference-tinyimagenet.py |
"""Train a classification model."""
from __future__ import print_function
import argparse
import numpy as np
import os
import sys
import torch
import multiprocessing as mp
import math
import pdb
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from pycls.co... | 25,928 | 41.092532 | 139 | py |
RobDanns | RobDanns-main/deep_learning/tools/train_resnet18_on_tinyimagenet200.py |
"""Train a classification model."""
from __future__ import print_function
import argparse
import numpy as np
import os
import sys
import torch
import multiprocessing as mp
import math
import pdb
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from pycls.co... | 21,617 | 37.741935 | 129 | py |
RobDanns | RobDanns-main/deep_learning/tools/adversarial-inference-tinyimagenet200.py |
"""Train a classification model."""
from __future__ import print_function
import argparse
import numpy as np
import os
import sys
import torch
import multiprocessing as mp
import math
import pdb
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from pycls.co... | 23,184 | 38.768439 | 147 | py |
RobDanns | RobDanns-main/deep_learning/tools/adversarial-inference.py |
"""Train a classification model."""
import argparse
import pickle
import numpy as np
import os
import sys
import torch
import math
import torchvision
import torchattacks
from pycls.config import assert_cfg
from pycls.config import cfg
from pycls.config import dump_cfg
from pycls.datasets import loader
from pycls.m... | 23,798 | 41.72711 | 166 | py |
RobDanns | RobDanns-main/deep_learning/tools/corruptions-inference.py |
"""Train a classification model."""
import argparse
import pickle
import numpy as np
import os
import sys
import torch
import math
import torchvision
import torchattacks
from pycls.config import assert_cfg
from pycls.config import cfg
from pycls.config import dump_cfg
from pycls.datasets import loader
from pycls.m... | 23,864 | 42.708791 | 139 | py |
RobDanns | RobDanns-main/deep_learning/tools/train_net.py |
"""Train a classification model."""
import argparse
import pickle
import numpy as np
import os
import sys
import torch
import math
# import torchvision
# import time
from pycls.config import assert_cfg
from pycls.config import cfg
from pycls.config import dump_cfg
from pycls.datasets import loader
from pycls.model... | 18,692 | 39.113734 | 127 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/losses.py |
"""Loss functions."""
import torch.nn as nn
from pycls.config import cfg
# Supported losses
_LOSS_FUNS = {
'cross_entropy': nn.CrossEntropyLoss,
}
def get_loss_fun():
"""Retrieves the loss function."""
assert cfg.MODEL.LOSS_FUN in _LOSS_FUNS.keys(), \
'Loss function \'{}\' not supported'.for... | 730 | 26.074074 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/efficientnet.py |
"""EfficientNet models."""
import math
import torch
import torch.nn as nn
from pycls.config import cfg
import pycls.utils.net as nu
import pycls.utils.logging as logging
from .relation_graph import *
logger = logging.get_logger(__name__)
def get_conv(name):
"""Retrieves the transformation function by nam... | 15,385 | 33.809955 | 108 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/resnet.py |
"""ResNet or ResNeXt model."""
import torch.nn as nn
import torch
from pycls.config import cfg
import pycls.utils.logging as lu
import pycls.utils.net as nu
from .relation_graph import *
import time
import pdb
logger = lu.get_logger(__name__)
# Stage depths for an ImageNet model {model depth -> (d2, d3, d4, d5... | 20,015 | 37.198473 | 108 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/cnn.py |
"""CNN model."""
import torch.nn as nn
import torch
from pycls.config import cfg
import pycls.utils.logging as lu
import pycls.utils.net as nu
from .relation_graph import *
logger = lu.get_logger(__name__)
def get_trans_fun(name):
"""Retrieves the transformation function by name."""
trans_funs = {
... | 17,388 | 34.779835 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/vgg.py |
"""VGG example"""
import torch.nn as nn
import torch.nn.functional as F
from pycls.config import cfg
import pycls.utils.net as nu
from .relation_graph import *
class VGG(nn.Module):
def __init__(self, num_classes=1024):
super(VGG, self).__init__()
self.seed = cfg.RGRAPH.SEED_GRAPH
d... | 3,097 | 35.880952 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/mlp.py |
"""MLP model."""
import torch.nn as nn
import torch
from pycls.config import cfg
import pycls.utils.logging as lu
import pycls.utils.net as nu
from .relation_graph import *
import time
import pdb
logger = lu.get_logger(__name__)
def get_trans_fun(name):
"""Retrieves the transformation function by name."""... | 8,012 | 30.300781 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/model_builder.py |
"""Model construction functions."""
import torch
from pycls.config import cfg
from pycls.models.resnet import ResNet
from pycls.models.mlp import MLPNet
from pycls.models.cnn import CNN
from pycls.models.mobilenet import MobileNetV1
from pycls.models.efficientnet import EfficientNet
from pycls.models.vgg import VG... | 2,355 | 30 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/mobilenet.py |
"""MobileNet example"""
import torch.nn as nn
import torch.nn.functional as F
from pycls.config import cfg
import pycls.utils.net as nu
from .relation_graph import *
class MobileNetV1(nn.Module):
def __init__(self, num_classes=1024):
super(MobileNetV1, self).__init__()
if cfg.RGRAPH.KEEP_GRA... | 3,404 | 35.223404 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/optimizer.py |
"""Optimizer."""
import torch
from pycls.config import cfg
import pycls.utils.lr_policy as lr_policy
def construct_optimizer(model):
"""Constructs the optimizer.
Note that the momentum update in PyTorch differs from the one in Caffe2.
In particular,
Caffe2:
V := mu * V + lr * g... | 1,678 | 27.457627 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/models/relation_graph.py |
"""Relational graph modules"""
import math
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import torch.nn.functional as F
import torch.nn.init as init
import networkx as nx
import numpy as np
from torch.nn.modules.utils import _pair
from torch.nn.modules.conv import _ConvNd
from torch.... | 15,045 | 35.877451 | 114 | py |
RobDanns | RobDanns-main/deep_learning/pycls/datasets/cifar100.py |
"""CIFAR100 dataset."""
import numpy as np
import os
import pickle
import torch
import torch.utils.data
import pycls.datasets.transforms as transforms
from torchvision import datasets
import pycls.utils.logging as lu
logger = lu.get_logger(__name__)
# Per-channel mean and SD values in BGR order
_MEAN = [129.3, 1... | 3,163 | 34.155556 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/datasets/cifar10.py |
"""CIFAR10 dataset."""
import numpy as np
import os
import pickle
import torch
import torch.utils.data
import pycls.datasets.transforms as transforms
import pycls.utils.logging as lu
from pycls.config import cfg
logger = lu.get_logger(__name__)
# Per-channel mean and SD values in BGR order
_MEAN = [125.3, 123.0,... | 3,048 | 33.647727 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/datasets/paths.py |
"""Dataset paths."""
import os
# Default data directory (/path/pycls/pycls/datasets/data)
_DEF_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
# Data paths
_paths = {
'cifar10': _DEF_DATA_DIR + '/cifar10',
'cifar100': _DEF_DATA_DIR + '/cifar100',
'tinyimagenet200': _DEF_DATA_DIR + '/tinyima... | 1,084 | 26.820513 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/datasets/loader.py |
"""Data loader."""
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data.sampler import RandomSampler
import torch
from pycls.config import cfg
from pycls.datasets.cifar10 import Cifar10
from pycls.datasets.cifar100 import Cifar100
from pycls.datasets.tinyimagenet200 import TinyImageNe... | 3,131 | 30.009901 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/datasets/imagenet.py |
"""ImageNet dataset."""
import cv2
import numpy as np
import os
import torch
import torch.utils.data
import pycls.datasets.transforms as transforms
import pycls.utils.logging as lu
logger = lu.get_logger(__name__)
# Per-channel mean and SD values in BGR order
_MEAN = [0.406, 0.456, 0.485]
_SD = [0.225, 0.224, 0.... | 6,759 | 35.344086 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/datasets/transforms.py |
"""Image transformations."""
import cv2
import math
import numpy as np
def CHW2HWC(image):
return image.transpose([1, 2, 0])
def HWC2CHW(image):
return image.transpose([2, 0, 1])
def color_normalization(image, mean, std):
"""Expects image in CHW format."""
assert len(mean) == image.shape[0]
... | 5,563 | 32.119048 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/datasets/load_graph.py |
"""load bio neural networks"""
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from networkx.utils import py_random_state
from matplotlib.colors import ListedColormap
import pdb
def compute_stats(G):
G_cluster = sorted(list(nx.clustering(G).values()))
cluster = sum(G_cluster) / l... | 4,341 | 30.014286 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/checkpoint.py |
"""Functions that handle saving and loading of checkpoints."""
import os
import torch
from collections import OrderedDict
from pycls.config import cfg
import pycls.utils.distributed as du
# Common prefix for checkpoint file names
_NAME_PREFIX = 'model_epoch_'
# Checkpoints directory name
_DIR_NAME = 'checkpoi... | 4,392 | 31.540741 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/timer.py |
"""Timer."""
import time
class Timer(object):
"""A simple timer (adapted from Detectron)."""
def __init__(self):
self.reset()
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time... | 1,013 | 25 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/error_handler.py |
"""Multiprocessing error handler."""
import os
import signal
import threading
class ChildException(Exception):
"""Wraps an exception from a child process."""
def __init__(self, child_trace):
super(ChildException, self).__init__(child_trace)
class ErrorHandler(object):
"""Multiprocessing err... | 2,012 | 31.467742 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/plotting.py |
"""Plotting functions."""
import colorlover as cl
import matplotlib.pyplot as plt
import plotly.graph_objs as go
import plotly.offline as offline
import pycls.utils.logging as lu
def get_plot_colors(max_colors, color_format='pyplot'):
"""Generate colors for plotting."""
colors = cl.scales['11']['qual']['... | 4,288 | 39.847619 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/logging.py |
"""Logging."""
import builtins
import decimal
import logging
import os
import simplejson
import sys
from pycls.config import cfg
import pycls.utils.distributed as du
import pycls.utils.metrics as mu
import pdb
# Show filename and line number in logs
_FORMAT = '[%(filename)s: %(lineno)3d]: %(message)s'
# Log fi... | 4,325 | 33.608 | 119 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/net.py |
"""Functions for manipulating networks."""
import itertools
import math
import torch
import torch.nn as nn
from pycls.config import cfg
from ..models.relation_graph import *
def init_weights(m):
"""Performs ResNet style weight initialization."""
if isinstance(m, nn.Conv2d) or isinstance(m, SymConv2d):
... | 4,360 | 37.59292 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/distributed.py |
"""Distributed helpers."""
import torch
from pycls.config import cfg
def is_master_proc():
"""Determines if the current process is the master process.
Master process is responsible for logging, writing and loading checkpoints.
In the multi GPU setting, we assign the master role to the rank 0 process... | 2,323 | 31.277778 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/metrics.py |
"""Functions for computing metrics."""
import numpy as np
import torch
import torch.nn as nn
import pdb
from pycls.config import cfg
from functools import reduce
import operator
from ..models.relation_graph import *
# Number of bytes in a megabyte
_B_IN_MB = 1024 * 1024
def topks_correct(preds, labels, ks):
... | 8,557 | 33.095618 | 158 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/multiprocessing.py |
"""Multiprocessing helpers."""
import multiprocessing as mp
import traceback
import subprocess
import numpy as np
import os
from pycls.utils.error_handler import ErrorHandler
import pycls.utils.distributed as du
def run(proc_rank, world_size, error_queue, fun, fun_args, fun_kwargs):
os.environ['MASTER_ADDR'... | 2,888 | 29.09375 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/lr_policy.py |
"""Learning rate policies."""
import numpy as np
from pycls.config import cfg
def lr_fun_steps(cur_epoch):
"""Steps schedule (cfg.OPTIM.LR_POLICY = 'steps')."""
ind = [i for i, s in enumerate(cfg.OPTIM.STEPS) if cur_epoch >= s][-1]
return cfg.OPTIM.BASE_LR * (cfg.OPTIM.LR_MULT ** ind)
def lr_fun_ex... | 1,643 | 31.235294 | 107 | py |
RobDanns | RobDanns-main/deep_learning/pycls/utils/meters.py |
"""Meters."""
from collections import deque
import datetime
import numpy as np
from pycls.config import cfg
from pycls.utils.timer import Timer
import pycls.utils.logging as lu
import pycls.utils.metrics as metrics
def eta_str(eta_td):
"""Converts an eta timedelta to a fixed-width string format."""
day... | 8,313 | 32.934694 | 116 | py |
kge_ecotox_regression | kge_ecotox_regression-main/main.py |
"""
TODO:
- Train embedding model.
- Apply embeddings to data.
- Encode data.
- Train,valid,test model
"""
from autoencoder import create_auto_encoder
from model import create_model, CorrelelatedFeatures, ApproxKerasSVM, coeff_determination
import numpy as np
import pandas as pd
from sklearn.model... | 32,681 | 35.394209 | 169 | py |
kge_ecotox_regression | kge_ecotox_regression-main/train_rdf2vec.py |
from pyrdf2vec.graphs import KG
from pyrdf2vec.samplers import UniformSampler
from pyrdf2vec.walkers import RandomWalker
from pyrdf2vec import RDF2VecTransformer
import pandas as pd
from rdflib import Graph, URIRef
import numpy as np
from main import load_data
import rdflib
d = './data/embeddings/'
pdf = [pd... | 1,266 | 27.795455 | 93 | py |
kge_ecotox_regression | kge_ecotox_regression-main/embedding_model.py | from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import Input, Embedding, Dense, Dropout, Conv2D, Flatten, Concatenate, Multiply
import tensorflow as tf
def min_distance_loss(w,epsilon=1.0):
r = tf.reduce_sum(w*w, 1)
r = tf.reshape(r, [-1, 1])
D = r - 2*tf.matmul(w, tf.... | 4,177 | 31.897638 | 108 | py |
kge_ecotox_regression | kge_ecotox_regression-main/pretrained_embedding_models.py |
import sys
import os
from itertools import product
from KGEkeras import DistMult, HolE, TransE, HAKE, ConvE, ComplEx, ConvR, RotatE, pRotatE, ConvKB, CosinE
from kerastuner import RandomSearch, HyperParameters, Objective, Hyperband, BayesianOptimization
from random import choice
from collections import defaultdict
... | 8,625 | 30.140794 | 134 | py |
kge_ecotox_regression | kge_ecotox_regression-main/create_data.py |
"""
TODO:
- Load LC50 data from ECOTOX.
- Take median per chemical species pairs.
- Defined chemical groups.
- Export files per chemical groups and each species.
- Forall chemicals and species export relevant KGs.
"""
from tera.DataAggregation import Taxonomy, Effects, Traits
from tera.... | 10,807 | 30.510204 | 157 | py |
kge_ecotox_regression | kge_ecotox_regression-main/autoencoder.py |
from tensorflow.keras.layers import Dense, GaussianNoise, Input, LayerNormalization
from tensorflow.keras.models import Model
from tensorflow import keras
def create_auto_encoder(input_size, dense_layers = (10,), noise=0):
autoencoder = keras.Sequential()
if noise > 0:
autoencoder.add(GaussianNoise(no... | 613 | 33.111111 | 83 | py |
lepard | lepard-main/main.py | import os, torch, json, argparse, shutil
from easydict import EasyDict as edict
import yaml
from datasets.dataloader import get_dataloader, get_datasets
from models.pipeline import Pipeline
from lib.utils import setup_seed
from lib.tester import get_trainer
from models.loss import MatchMotionLoss
from lib.tictok import... | 3,723 | 32.54955 | 116 | py |
lepard | lepard-main/models/matching.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from models.position_encoding import VolumetricPositionEncoding as VolPE
def log_optimal_transport(scores, alpha, iters, src_mask, tgt_mask ):
b, m, n = scores.shape
if src_mask is None:
ms = m
ns = n
else :
ms = s... | 5,412 | 29.931429 | 118 | py |
lepard | lepard-main/models/loss.py | import torch
import torch.nn as nn
import numpy as np
import open3d as o3d
from lib.benchmark_utils import to_o3d_pcd
from lib.visualization import *
import nibabel.quaternions as nq
from sklearn.metrics import precision_recall_fscore_support
from datasets.utils import blend_scene_flow, multual_nn_correspondence, knn_p... | 18,271 | 38.042735 | 137 | py |
lepard | lepard-main/models/position_encoding.py | import math
import torch
from torch import nn
class VolumetricPositionEncoding(nn.Module):
def __init__(self, config):
super().__init__()
self.feature_dim = config.feature_dim
self.vol_bnds = config.vol_bnds
self.voxel_size = config.voxel_size
self.vol_origin = self.vol_b... | 2,989 | 33.367816 | 160 | py |
lepard | lepard-main/models/backbone.py | from models.blocks import *
import torch.nn.functional as F
import numpy as np
class KPFCN(nn.Module):
def __init__(self, config):
super(KPFCN, self).__init__()
# Parameters
layer = 0
r = config.first_subsampling_dl * config.conv_radius
in_dim = config.in_feats_dim
... | 6,033 | 36.018405 | 100 | py |
lepard | lepard-main/models/transformer.py | import copy
import math
import torch
from torch import nn
from torch.nn import Module, Dropout
from models.position_encoding import VolumetricPositionEncoding as VolPE
from models.matching import Matching
from models.procrustes import SoftProcrustesLayer
import numpy as np
import random
from scipy.spatial.transform imp... | 10,666 | 36.559859 | 142 | py |
lepard | lepard-main/models/procrustes.py | import torch
import torch.nn as nn
def topk(data, num_topk):
sort, idx = data.sort(descending=True)
return sort[:num_topk], idx[:num_topk]
class SoftProcrustesLayer(nn.Module):
def __init__(self, config):
super(SoftProcrustesLayer, self).__init__()
self.sample_rate = config.sample_rate
... | 3,591 | 37.623656 | 107 | py |
lepard | lepard-main/models/pipeline.py | from models.blocks import *
from models.backbone import KPFCN
from models.transformer import RepositioningTransformer
from models.matching import Matching
from models.procrustes import SoftProcrustesLayer
class Pipeline(nn.Module):
def __init__(self, config):
super(Pipeline, self).__init__()
self.... | 3,685 | 43.95122 | 154 | py |
lepard | lepard-main/models/blocks.py | import time
import math
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.nn.init import kaiming_uniform_
from kernels.kernel_points import load_kernels
# from lib.ply import write_ply
def gather(x, idx, method=2):
"""
implementation of a custom gather operation for faste... | 26,090 | 35.956091 | 122 | py |
lepard | lepard-main/cpp_wrappers/cpp_neighbors/setup.py | from distutils.core import setup, Extension
import numpy.distutils.misc_util
# Adding OpenCV to project
# ************************
# Adding sources of the project
# *****************************
SOURCES = ["../cpp_utils/cloud/cloud.cpp",
"neighbors/neighbors.cpp",
"wrapper.cpp"]
module = E... | 619 | 20.37931 | 92 | py |
lepard | lepard-main/cpp_wrappers/cpp_subsampling/setup.py | from distutils.core import setup, Extension
import numpy.distutils.misc_util
# Adding OpenCV to project
# ************************
# Adding sources of the project
# *****************************
SOURCES = ["../cpp_utils/cloud/cloud.cpp",
"grid_subsampling/grid_subsampling.cpp",
"wrapper.cpp... | 633 | 20.862069 | 92 | py |
lepard | lepard-main/datasets/_4dmatch.py | import os, sys, glob, torch
# sys.path.append("../")
[sys.path.append(i) for i in ['.', '..']]
import numpy as np
import torch
import random
from scipy.spatial.transform import Rotation
from torch.utils.data import Dataset
from lib.benchmark_utils import to_o3d_pcd, to_tsfm, KDTree_corr
from lib.utils import load_obj
H... | 5,939 | 32.75 | 123 | py |
lepard | lepard-main/datasets/dataloader.py | import numpy as np
from functools import partial
import torch
import cpp_wrappers.cpp_subsampling.grid_subsampling as cpp_subsampling
import cpp_wrappers.cpp_neighbors.radius_neighbors as cpp_neighbors
from datasets._3dmatch import _3DMatch
from datasets._4dmatch import _4DMatch
from datasets.utils import blend_scene_f... | 24,996 | 37.875583 | 171 | py |
lepard | lepard-main/datasets/utils.py | import numpy as np
# from lib.benchmark_utils import to_o3d_pcd, KDTree_corr
def partition_arg_topK(matrix, K, axis=0):
""" find index of K smallest entries along a axis
perform topK based on np.argpartition
:param matrix: to be sorted
:param K: select and sort the top K items
:param axis: 0 or 1.... | 2,983 | 36.3 | 104 | py |
lepard | lepard-main/datasets/_3dmatch.py | import os, sys, glob, torch
# sys.path.append("../")
[sys.path.append(i) for i in ['.', '..']]
import numpy as np
import torch
import random
from scipy.spatial.transform import Rotation
from torch.utils.data import Dataset
from lib.benchmark_utils import to_o3d_pcd, to_tsfm, KDTree_corr
from lib.utils import load_obj
... | 5,766 | 33.327381 | 116 | py |
lepard | lepard-main/lib/visualization.py |
c_red = (224. / 255., 0 / 255., 125 / 255.)
c_pink = (224. / 255., 75. / 255., 232. / 255.)
c_blue = (0. / 255., 0. / 255., 255. / 255.)
c_green = (0. / 255., 255. / 255., 0. / 255.)
c_gray1 = (100. / 255., 100. / 255., 100. / 255.)
c_gray2 = (175. / 255., 175. / 255., 175. / 255.)
def viz_flow_mayavi( s_pc,flow = No... | 2,352 | 36.951613 | 126 | py |
lepard | lepard-main/lib/timer.py | import time
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0.0
self.sq_sum = 0.0
self.count = 0
def update(self, val, n=1):
... | 1,335 | 22.438596 | 71 | py |
lepard | lepard-main/lib/benchmark_utils.py | import os,re,sys,json,yaml,random, glob, argparse, torch, pickle
from tqdm import tqdm
import numpy as np
from scipy.spatial.transform import Rotation
import open3d as o3d
_EPS = 1e-7 # To prevent division by zero
def viz_coarse_nn_correspondence_mayavi(s_pc, t_pc, good_c, bad_c, f_src_pcd=None, f_tgt_pcd=None, sca... | 11,442 | 31.882184 | 122 | py |
lepard | lepard-main/lib/utils.py | import os,re,sys,json,yaml,random, argparse, torch, pickle
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from scipy.spatial.transform import Rotation
from sklearn.neighbors import NearestNeighbors
from scipy.spatial.distance import minkowski
_EPS = 1e-7 # To prev... | 2,759 | 23.424779 | 82 | py |
lepard | lepard-main/lib/ply.py | # | PLY files reader/writer |
# function to read/write .ply files
# Hugues THOMAS - 10/02/2017
# Imports and global variables
# \**********************************/
# Basic libs
import numpy as np
import sys
# Define PLY types
ply_dtypes = dict([
(b'int8', 'i1'),
(b'char',... | 10,301 | 28.267045 | 120 | py |
lepard | lepard-main/lib/tictok.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import time
import numpy as np
from collections import defaultdict
class Timer(object):
def __init__(self):
self.reset()
def tic(self):
self.st... | 1,644 | 24.307692 | 130 | py |
lepard | lepard-main/lib/trainer.py | import gc
import os
import torch
import torch.nn as nn
import numpy as np
from tensorboardX import SummaryWriter
from tqdm import tqdm
from lib.timer import AverageMeter
from lib.utils import Logger, validate_gradient
from lib.tictok import Timers
class Trainer(object):
def __init__(self, args):
self.c... | 8,861 | 34.590361 | 117 | py |
lepard | lepard-main/kernels/kernel_points.py |
# | Kernel Point Convolutions |
# Functions handling the disposition of kernel points.
# Hugues THOMAS - 11/06/2018
import time
import numpy as np
from os import makedirs
from os.path import join, exists
from lib.ply import read_ply, write_ply
# Functions
# \***************/
de... | 17,189 | 35.496815 | 120 | py |
sngan.pytorch | sngan.pytorch-master/functions.py | # @Date : 2019-07-25
# @Link : None
# @Version : 0.0
import os
import numpy as np
import torch
import torch.nn as nn
from torchvision.utils import make_grid
from imageio import imsave
from tqdm import tqdm
from copy import deepcopy
import logging
from utils.inception_score import get_inception_score
from utils.... | 6,022 | 32.837079 | 123 | py |
sngan.pytorch | sngan.pytorch-master/cfg.py | # @Date : 2019-07-25
# @Link : None
# @Version : 0.0
import argparse
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
... | 4,330 | 27.30719 | 78 | py |
sngan.pytorch | sngan.pytorch-master/datasets.py | import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import Dataset
class ImageDataset(object):
def __init__(self, args):
if args.dataset.lower() == 'cifar10':
Dt = datasets.CIFAR10
transform = transforms.Compose([
... | 2,115 | 40.490196 | 101 | py |
sngan.pytorch | sngan.pytorch-master/train.py | # @Date : 2019-07-25
# @Link : None
# @Version : 0.0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cfg
import models
import datasets
from functions import train, validate, LinearLrDecay, load_params, copy_params
from utils.utils import set_lo... | 6,393 | 37.287425 | 116 | py |
sngan.pytorch | sngan.pytorch-master/models/sngan_64.py | import torch.nn as nn
class GenBlock(nn.Module):
def __init__(self, in_channels, out_channels, hidden_channels=None, ksize=3, pad=1,
activation=nn.ReLU(), upsample=False, n_classes=0):
super(GenBlock, self).__init__()
self.activation = activation
self.upsample = upsample
... | 6,296 | 34.778409 | 107 | py |
sngan.pytorch | sngan.pytorch-master/models/sngan_stl10.py | import torch.nn as nn
class GenBlock(nn.Module):
def __init__(self, in_channels, out_channels, hidden_channels=None, ksize=3, pad=1,
activation=nn.ReLU(), upsample=False, n_classes=0):
super(GenBlock, self).__init__()
self.activation = activation
self.upsample = upsample
... | 6,305 | 34.426966 | 99 | py |
sngan.pytorch | sngan.pytorch-master/models/sngan_cifar10.py | import torch.nn as nn
from .gen_resblock import GenBlock
class Generator(nn.Module):
def __init__(self, args, activation=nn.ReLU(), n_classes=0):
super(Generator, self).__init__()
self.bottom_width = args.bottom_width
self.activation = activation
self.n_classes = n_classes
... | 4,805 | 34.338235 | 107 | py |
sngan.pytorch | sngan.pytorch-master/models/gen_resblock.py | # @Date : 3/26/20
# @Link : None
# @Version : 0.0
import torch.nn as nn
class GenBlock(nn.Module):
def __init__(self, in_channels, out_channels, hidden_channels=None, ksize=3, pad=1,
activation=nn.ReLU(), upsample=False, n_classes=0):
super(GenBlock, self).__init__()
self.a... | 1,671 | 33.833333 | 90 | py |
sngan.pytorch | sngan.pytorch-master/utils/cal_fid_stat.py | # @Date : 2019-07-26
# @Link : None
# @Version : 0.0
import os
import glob
import argparse
import numpy as np
from imageio import imread
import tensorflow as tf
import utils.fid_score as fid
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--data_path',
type=... | 2,264 | 29.2 | 103 | py |
sngan.pytorch | sngan.pytorch-master/utils/utils.py | # @Date : 2019-07-25
# @Link : None
# @Version : 0.0
import os
import torch
import dateutil.tz
from datetime import datetime
import time
import logging
def create_logger(log_dir, phase='train'):
time_str = time.strftime('%Y-%m-%d-%H-%M')
log_file = '{}_{}.log'.format(time_str, phase)
final_log_file... | 1,772 | 26.703125 | 75 | py |
sngan.pytorch | sngan.pytorch-master/utils/inception_score.py | # Code derived from tensorflow/tensorflow/models/image/imagenet/classify_image.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tqdm import tqdm
import os.path
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
im... | 3,818 | 36.07767 | 96 | py |
sngan.pytorch | sngan.pytorch-master/utils/fid_score.py | """ Calculates the Frechet Inception Distance (FID) to evaluate GANs.
The FID metric calculates the distance between two distributions of images.
Typically, we have summary statistics (mean & covariance matrix) of one
of these distributions, while the 2nd distribution is given by a GAN.
When run as a stand-alone prog... | 13,063 | 39.196923 | 103 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.