repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
FBNETGEN
FBNETGEN-main/main.py
from pathlib import Path import argparse import yaml import torch from model import FBNETGEN, GNNPredictor, SeqenceModel, BrainNetCNN from train import BasicTrain, BiLevelTrain, SeqTrain, GNNTrain, BrainCNNTrain from datetime import datetime from dataloader import init_dataloader def main(args): with open(args....
3,687
35.514851
109
py
FBNETGEN
FBNETGEN-main/dataloader.py
import numpy as np import torch import torch.utils.data as utils from sklearn import preprocessing import pandas as pd from scipy.io import loadmat import pathlib class StandardScaler: """ Standard the input """ def __init__(self, mean, std): self.mean = mean self.std = std def t...
6,468
30.556098
104
py
FBNETGEN
FBNETGEN-main/train.py
from typing import overload import torch from numpy.lib import save from util import Logger, accuracy, TotalMeter import numpy as np from pathlib import Path import torch.nn.functional as F from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_fscore_support from util.prepossess import ...
16,952
34.690526
98
py
FBNETGEN
FBNETGEN-main/util/prepossess.py
import torch import numpy as np import random def mixup_data(x, nodes, y, alpha=1.0, device='cuda'): '''Returns mixed inputs, pairs of targets, and lambda''' if alpha > 0: lam = np.random.beta(alpha, alpha) else: lam = 1 batch_size = x.size()[0] index = torch.randperm(batch_size)....
2,388
27.783133
90
py
FBNETGEN
FBNETGEN-main/util/loss.py
import torch def inner_loss(label, matrixs): loss = 0 if torch.sum(label == 0) > 1: loss += torch.mean(torch.var(matrixs[label == 0], dim=0)) if torch.sum(label == 1) > 1: loss += torch.mean(torch.var(matrixs[label == 1], dim=0)) return loss def intra_loss(label, matrixs): a,...
1,451
24.928571
70
py
FBNETGEN
FBNETGEN-main/util/logger.py
import logging class Logger: def __init__(self): self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) for handler in self.logger.handlers: handler.close() self.logger.handlers.clear() formatter = logging.Formatter( '[%(asctime)s][%(f...
579
28
82
py
FBNETGEN
FBNETGEN-main/util/__init__.py
from .logger import Logger from .meter import AverageMeter, TotalMeter, accuracy
81
26.333333
53
py
FBNETGEN
FBNETGEN-main/util/meter.py
from typing import List import torch def accuracy(output: torch.Tensor, target: torch.Tensor, top_k=(1,)) -> List[float]: max_k = max(top_k) batch_size = target.size(0) _, predict = output.topk(max_k, 1, True, True) predict = predict.t() correct = predict.eq(target.view(1, -1).expand_as(predict))...
1,699
22.943662
84
py
FBNETGEN
FBNETGEN-main/util/FCNet/fc_net_label_generation.py
from sklearn.cluster import AffinityPropagation import numpy as np import argparse import random import pathlib def main(args): final_fc = np.load(args.data_path, allow_pickle=True) if args.dataset == 'PNC': final_fc = final_fc.item() final_fc = final_fc['data'] column_idxs = [] lab...
1,893
29.548387
116
py
FBNETGEN
FBNETGEN-main/util/FCNet/infer.py
import torch import argparse import yaml from model import SeqenceModel, FCNet from dataloader import infer_dataloader from pathlib import Path import numpy as np from sklearn.linear_model import ElasticNet from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import roc_...
2,775
22.726496
119
py
FBNETGEN
FBNETGEN-main/util/analysis/extract_info_from_log.py
import argparse import re def main(args): table = [] with open(args.path, 'r') as f: lines = f.readlines() for l in lines: value = re.findall(r'.*Epoch\[(\d+)/500\].*Train Loss: (\d+\.\d+).*Test Loss: (\d+\.\d+)', l) table.append(value[0]) s = f'|Epoch|' fo...
853
25.6875
124
py
FBNETGEN
FBNETGEN-main/util/abide/03-generate_abide_dataset.py
import deepdish as dd import os.path as osp import os import numpy as np import argparse from pathlib import Path import pandas as pd def main(args): data_dir = os.path.join(args.root_path, 'ABIDE_pcp/cpac/filt_noglobal/raw') timeseires = os.path.join(args.root_path, 'ABIDE_pcp/cpac/filt_noglobal/') met...
2,040
26.958904
194
py
FBNETGEN
FBNETGEN-main/util/abide/02-process_data.py
# Copyright (c) 2019 Mwiza Kunda # Modified by Xuan Kan # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program...
3,874
37.366337
124
py
FBNETGEN
FBNETGEN-main/util/abide/01-fetch_data.py
# Copyright (c) 2019 Mwiza Kunda # Copyright (C) 2017 Sarah Parisot <s.parisot@imperial.ac.uk>, , Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eit...
4,095
39.156863
133
py
FBNETGEN
FBNETGEN-main/util/abide/preprocess_data.py
# Copyright (c) 2019 Mwiza Kunda # Copyright (C) 2017 Sarah Parisot <s.parisot@imperial.ac.uk>, Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eithe...
11,247
40.201465
118
py
FBNETGEN
FBNETGEN-main/model/GSL.py
import torch import torch.nn as nn from torch.nn import functional as F from model.cell import DCGRUCell import numpy as np from .model import GNNPredictor, ConvKRegion, Embed2GraphByLinear, GruKRegion, Embed2GraphByProduct device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def count_parameters(mod...
16,048
35.894253
119
py
FBNETGEN
FBNETGEN-main/model/model.py
from turtle import forward import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Conv1d, MaxPool1d, Linear, GRU import math def sample_gumbel(shape, eps=1e-20): U = torch.rand(shape).cuda() return -torch.autograd.Variable(torch.log(-torch.log(U + eps) + ep...
13,552
29.050998
97
py
FBNETGEN
FBNETGEN-main/model/__init__.py
from .GSL import BrainGSLModel, TSConstruction from .model import FBNETGEN, GNNPredictor, SeqenceModel, BrainNetCNN
115
57
68
py
FBNETGEN
FBNETGEN-main/model/cell.py
import numpy as np import torch device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class LayerParams: def __init__(self, rnn_network: torch.nn.Module, layer_type: str): self._rnn_network = rnn_network self._params_dict = {} self._biases_dict = {} self._type = lay...
6,299
38.873418
105
py
dynet
dynet-master/setup.py
import distutils.sysconfig import logging as log import platform import zipfile import sys from distutils.command.build import build as _build from distutils.command.build_py import build_py as _build_py from distutils.command.install_data import install_data as _install_data from distutils.errors import DistutilsSetup...
16,189
39.173697
289
py
dynet
dynet-master/examples/variational-autoencoder/basic-image-recon/utils.py
import os, struct import numpy as np import math # adapted from https://github.com/clab/dynet/blob/master/examples/mnist/mnist-autobatch.py def load_mnist(dataset, path): """ wget -O - http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz | gunzip > train-images-idx3-ubyte wget -O - http://yann.lecu...
4,525
39.053097
108
py
dynet
dynet-master/examples/variational-autoencoder/basic-image-recon/vae.py
from __future__ import print_function from utils import load_mnist, make_grid, pre_pillow_float_img_process, save_image import numpy as np import argparse import dynet as dy import os if not os.path.exists('results'): os.makedirs('results') parser = argparse.ArgumentParser(description='VAE MNIST Example') parser...
6,690
31.639024
118
py
dynet
dynet-master/examples/python-utils/util.py
import mmap class Vocab: def __init__(self, w2i): self.w2i = dict(w2i) self.i2w = {i:w for w,i in w2i.items()} @classmethod def from_corpus(cls, corpus): w2i = {} for sent in corpus: for word in sent: w2i.setdefault(word, len(w2i)) return...
1,731
28.355932
111
py
dynet
dynet-master/examples/rnnlm/lstmlm-auto.py
from __future__ import print_function from collections import defaultdict import math import random import time import dynet as dy # path to Mikolov PTB train.txt and valid.txt FLAGS_train = 'train.txt' FLAGS_valid = 'valid.txt' FLAGS_layers = 1 FLAGS_hidden_dim = 128 FLAGS_batch_size = 16 FLAGS_word_dim = 64 def s...
4,126
31.242188
79
py
dynet
dynet-master/examples/rnnlm/rnnlm.py
import dynet as dy import time import random LAYERS = 2 INPUT_DIM = 256 #50 #256 HIDDEN_DIM = 256 # 50 #1024 VOCAB_SIZE = 0 from collections import defaultdict from itertools import count import argparse import sys import util class RNNLanguageModel: def __init__(self, model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOC...
4,334
31.593985
105
py
dynet
dynet-master/examples/rnnlm/rnnlm_transduce.py
# a version rnnlm.py using the transduce() interface. import dynet as dy import time import random LAYERS = 2 INPUT_DIM = 50 #256 HIDDEN_DIM = 50 #1024 VOCAB_SIZE = 0 import argparse import sys import util try: from itertools import izip as zip except ImportError: pass class RNNLanguageModel: def __ini...
3,338
30.205607
102
py
dynet
dynet-master/examples/mnist/mnist-autobatch.py
#! /usr/bin/env python3 import time import random import os import struct import argparse import numpy as np import dynet as dy # To run this, download the four files from http://yann.lecun.com/exdb/mnist/ # using the --download option. # Pass the path where the data should be stored (or is already stored) # to the ...
6,853
35.26455
78
py
dynet
dynet-master/examples/mnist/basic-mnist-benchmarks/mnist_dynet_autobatch.py
from __future__ import division import os import struct import argparse import random import time import numpy as np # import dynet as dy # import dynet_config # dynet_config.set_gpu() import dynet as dy # First, download the MNIST dataset from the official website and decompress it. # wget -O - http://yann.lecun.com/...
6,044
38.509804
106
py
dynet
dynet-master/examples/mnist/basic-mnist-benchmarks/mnist_pytorch.py
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.autograd import Variable import time # Training settings parser = argparse.ArgumentParser(description='PyTorch MNI...
4,645
38.372881
95
py
dynet
dynet-master/examples/mnist/basic-mnist-benchmarks/mnist_dynet_minibatch.py
from __future__ import division import os import struct import argparse import random import time import numpy as np # import dynet as dy # import dynet_config # dynet_config.set_gpu() import dynet as dy # First, download the MNIST dataset from the official website and decompress it. # wget -O - http://yann.lecun.com/...
6,215
38.341772
106
py
dynet
dynet-master/examples/tensorboard/rnnlm-batch.py
import dynet as dy import time import random from pycrayon import CrayonClient LAYERS = 2 INPUT_DIM = 256 #50 #256 HIDDEN_DIM = 256 # 50 #1024 VOCAB_SIZE = 0 MB_SIZE = 50 # mini batch size import argparse from collections import defaultdict from itertools import count import sys import util class RNNLanguageMode...
5,527
32.707317
105
py
dynet
dynet-master/examples/tensorboard/util.py
import mmap class Vocab: def __init__(self, w2i): self.w2i = dict(w2i) self.i2w = {i:w for w,i in w2i.items()} @classmethod def from_corpus(cls, corpus): w2i = {} for sent in corpus: for word in sent: w2i.setdefault(word, len(w2i)) return...
1,731
28.355932
111
py
dynet
dynet-master/examples/treelstm/main.py
from __future__ import print_function import dynet as dy dyparams = dy.DynetParams() dyparams.from_args() import sys import time import os import argparse import warnings import zipfile from six.moves import urllib from model import TreeLSTMClassifier from utils import get_embeds, acc_eval from scheduler import Sche...
5,324
35.472603
108
py
dynet
dynet-master/examples/treelstm/dataloader.py
import re import codecs import random from collections import Counter def read_dataset(filename): return [Tree.from_sexpr(line.strip()) for line in codecs.open(filename, "r")] def get_vocabs(trees): label_vocab = Counter() word_vocab = Counter() for tree in trees: label_vocab.update([n.label...
2,717
26.454545
87
py
dynet
dynet-master/examples/treelstm/utils.py
import codecs import numpy as np import dynet as dy def acc_eval(dataset, model): dataset.reset(shuffle=False) good = bad = 0.0 for tree in dataset: dy.renew_cg() pred = np.argmax(model.predict_for_tree(tree, decorate=False, training=False)) if pred == tree.label: good ...
845
26.290323
86
py
dynet
dynet-master/examples/treelstm/model.py
import dynet as dy import numpy as np import os class TreeLSTMBuilder(object): def __init__(self, pc_param, pc_embed, word_vocab, wdim, hdim, word_embed=None): self.WS = [pc_param.add_parameters((hdim, wdim)) for _ in "iou"] self.US = [pc_param.add_parameters((hdim, 2 * hdim)) for _ in "iou"] ...
5,341
45.859649
112
py
dynet
dynet-master/examples/treelstm/scheduler.py
import time import dynet as dy import numpy as np from utils import acc_eval class Scheduler: def __init__(self, model, train, dev, params): self.train, self.dev = train, dev self.model = model self.params = params self.trainer_param = getattr(dy, params['trainer'])(model.pc_param...
2,726
39.701493
125
py
dynet
dynet-master/examples/treelstm/filter_glove.py
import codecs import re import os data_dir = 'trees' datasets = ['train', 'dev', 'test'] glove_origin_path = 'glove.840B.300d.txt' glove_filtered_path = 'glove_filtered.txt' def get_vocab(file_path): vocab = set() tokker = re.compile(r'([^ ()]+)\)') with codecs.open(file_path) as f: for line in f...
954
24.810811
65
py
dynet
dynet-master/examples/devices/xor-multidevice.py
# Usage: # python xor-multidevice.py --dynet-devices CPU,GPU:0,GPU:1 # or python xor-multidevice.py --dynet-gpus 2 import sys import dynet as dy #xsent = True xsent = False HIDDEN_SIZE = 8 ITERATIONS = 2000 m = dy.Model() trainer = dy.SimpleSGDTrainer(m) pW1 = m.add_parameters((HIDDEN_SIZE, 2), device="GPU:1") ...
2,082
22.404494
66
py
dynet
dynet-master/examples/devices/cpu_vs_gpu.py
# Usage: python cpu_vs_gpu.py import time from multiprocessing import Process def do_cpu(): import _dynet as C C.init() cm = C.Model() cpW = cm.add_parameters((1000,1000)) s = time.time() C.renew_cg() W = C.parameter(cpW) W = W*W*W*W*W*W*W z = C.squared_distance(W,W) z.value() z.backward() pri...
866
18.266667
38
py
dynet
dynet-master/examples/reinforcement-learning/ddpg.py
import dynet as dy import numpy as np from memory import Memory from network import MLP # Deep Deterministic Policy Gradient: https://arxiv.org/abs/1509.02971 # An reinforcement learning agent to learn in environments which have continuous action spaces. class DDPG: def __init__(self, obs_dim, action_dim, hidden...
4,171
39.901961
143
py
dynet
dynet-master/examples/reinforcement-learning/reduce_tree.py
import operator import numpy as np # A simple binary tree structure to calculate some statistics from leaves. class ReduceTree(object): def __init__(self, size, op): if size & (size - 1) != 0: raise ValueError("size mush be a power of 2.") self.size = size self.values = np.zero...
1,743
27.590164
86
py
dynet
dynet-master/examples/reinforcement-learning/memory.py
import numpy as np from math import log, ceil from reduce_tree import ReduceTree, SumTree # A simple memory to store and sample experiences. class Memory(object): def __init__(self, size): self.size = size self.idx = 0 self.memory = np.zeros(size, dtype=object) def store(self, exp): ...
1,997
31.225806
102
py
dynet
dynet-master/examples/reinforcement-learning/network.py
import dynet as dy class Network(object): def __init__(self, pc): self.pc = dy.ParameterCollection() if pc is None else pc def update(self, other, soft=False, tau=0.1): params_self, params_other = self.pc.parameters_list(), other.pc.parameters_list() for x, y in zip(params_self, param...
2,989
38.866667
101
py
dynet
dynet-master/examples/reinforcement-learning/dqn.py
import dynet as dy import numpy as np from memory import Memory, PrioritizedMemory # DeepQNetwork: https://arxiv.org/abs/1312.5602 # An reinforcement learning agent to learn in environments which have discrete action spaces. # Double Q-Learning: https://arxiv.org/abs/1509.06461 # Prioritized Replay: https://arxiv.or...
4,403
37.631579
115
py
dynet
dynet-master/examples/reinforcement-learning/train_test_utils.py
import numpy as np def train_pipeline_progressive(env, player, score_threshold, batch_size, n_episode, learn_start=100, print_every=10): rewards, losses = [], [] for i_episode in range(n_episode): obs = env.reset() reward = 0 for t in range(env._max_episode_steps): action =...
3,261
39.271605
117
py
dynet
dynet-master/examples/reinforcement-learning/main_ddpg.py
import argparse import gym from ddpg import DDPG from train_test_utils import train_pipeline_conservative, test def establish_args(): parser = argparse.ArgumentParser() parser.add_argument("--env_name", default="Walker2d-v2", type=str) parser.add_argument("--memory_size", default=1e6, type=float) pars...
1,094
39.555556
111
py
dynet
dynet-master/examples/reinforcement-learning/main_dqn.py
import argparse import gym from dqn import DeepQNetwork from network import MLP, Header from train_test_utils import train_pipeline_progressive, train_pipeline_conservative, test def establish_args(): parser = argparse.ArgumentParser() parser.add_argument('--dynet-gpus', default=0, type=int) parser.add_...
1,846
33.849057
119
py
dynet
dynet-master/examples/tagger/bilstmtagger.py
import dynet as dy from collections import Counter import random import util # format of files: each line is "word<TAB>tag<newline>", blank line is new sentence. train_file="/Users/yogo/Vork/Research/corpora/pos/WSJ.TRAIN" test_file="/Users/yogo/Vork/Research/corpora/pos/WSJ.TEST" MLP=True def read(fname): sen...
3,719
24.655172
84
py
dynet
dynet-master/examples/transformer/wrap-data.py
import sys import collections import itertools def threshold_vocab(fname, threshold): word_counts = collections.Counter() with open(fname) as fin: for line in fin: for token in line.split(): word_counts[token] += 1 ok = set() for word, count in sorted(word_counts.it...
4,419
43.646465
370
py
dynet
dynet-master/examples/batching/rnnlm-batch.py
import dynet as dy import time import random LAYERS = 2 INPUT_DIM = 256 #50 #256 HIDDEN_DIM = 256 # 50 #1024 VOCAB_SIZE = 0 MB_SIZE = 50 # mini batch size import argparse from collections import defaultdict from itertools import count import sys import util class RNNLanguageModel: def __init__(self, model, LA...
4,910
32.182432
102
py
dynet
dynet-master/examples/batching/minibatch.py
import dynet as dy import numpy as np m = dy.Model() lp = m.add_lookup_parameters((100,10)) # regular lookup a = lp[1].npvalue() b = lp[2].npvalue() c = lp[3].npvalue() # batch lookup instead of single elements. # two ways of doing this. abc1 = dy.lookup_batch(lp, [1,2,3]) print(abc1.npvalue()) abc2 = lp.batch([1,2...
875
23.333333
89
py
dynet
dynet-master/examples/sequence-to-sequence/attention.py
import dynet as dy import random EOS = "<EOS>" characters = list("abcdefghijklmnopqrstuvwxyz ") characters.append(EOS) int2char = list(characters) char2int = {c:i for i,c in enumerate(characters)} VOCAB_SIZE = len(characters) LSTM_NUM_OF_LAYERS = 2 EMBEDDINGS_SIZE = 32 STATE_SIZE = 32 ATTENTION_SIZE = 32 model = d...
5,302
31.533742
113
py
dynet
dynet-master/examples/xor/xor.py
import sys import dynet as dy #xsent = True xsent = False HIDDEN_SIZE = 8 ITERATIONS = 2000 m = dy.Model() trainer = dy.SimpleSGDTrainer(m) W = m.add_parameters((HIDDEN_SIZE, 2)) b = m.add_parameters(HIDDEN_SIZE) V = m.add_parameters((1, HIDDEN_SIZE)) a = m.add_parameters(1) if len(sys.argv) == 2: m.populate_fro...
1,367
17.739726
47
py
dynet
dynet-master/python/dynet_config.py
def set(mem="512", random_seed=0, autobatch=0, profiling=0, weight_decay=0, shared_parameters=0, requested_gpus=0, gpu_mask=None): if "__DYNET_CONFIG" in __builtins__: (mem, random_seed, auto_batch, profiling) = ( __builtins__["__DYNET_CONFIG"]["mem"] if __builtins__["__DYNET_CO...
2,199
51.380952
159
py
dynet
dynet-master/python/dynet_viz.py
from __future__ import print_function import sys import re from collections import defaultdict if sys.version_info.major > 2: # alias dict.items() as dict.iteritems() in python 3+ class compat_dict(defaultdict): pass compat_dict.iteritems = defaultdict.items defaultdict = compat_dict # add xrange to ...
39,058
35.640713
188
py
dynet
dynet-master/python/model_test.py
""" Tests for model saving and loading, including for user-defined models. """ from __future__ import print_function import dynet as dy import numpy import os # first, define three user-defined classes class Transfer(Saveable): def __init__(self, nin, nout, act, model): self.act = act self.W = mod...
6,174
30.829897
98
py
dynet
dynet-master/tests/python/test.py
import dynet as dy import numpy as np import unittest import gc def npvalue_callable(x): return x.npvalue() def gradient_callable(x): return x.gradient() class TestInput(unittest.TestCase): def setUp(self): self.input_vals = np.arange(81) self.squared_norm = (self.input_vals**2).sum()...
26,802
32.970849
88
py
dynet
dynet-master/bench/sequence_transduction.py
import dynet as dy import random import time import sys random.seed(1) SEQ_LENGTH=2 BATCH_SIZE=2 HIDDEN=1 NCLASSS=2 EMBED_SIZE=1 N_SEQS=1000 autobatching=True dy.renew_cg() random_seq = lambda ln,t: [random.randint(0,t-1) for _ in xrange(ln)] seq_lengths = [SEQ_LENGTH for _ in range(N_SEQS)] #seq_lengths = [random.r...
1,763
23.84507
72
py
dynet
dynet-master/doc/source/doc_util.py
from __future__ import print_function import re INDENT = 1 NAME = 2 INHERIT = 3 ARGUMENTS = 3 PASS=' pass\n' def pythonize_arguments(arg_str): """ Remove types from function arguments in cython """ out_args = [] # If there aren't any arguments return the empty string if arg_str is None: ...
3,948
33.043103
164
py
dynet
dynet-master/doc/source/conf.py
# -*- coding: utf-8 -*- # # DyNet documentation build configuration file, created by # sphinx-quickstart on Thu Oct 13 16:13:12 2016. # # 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...
9,095
30.583333
83
py
pose_refinement
pose_refinement-master/src/training/loaders.py
import numpy as np from torch.utils.data import DataLoader, SequentialSampler from itertools import chain import torch from databases.datasets import pose_grid_from_index, Mpi3dTrainDataset, PersonStackedMucoTempDataset, ConcatPoseDataset class ConcatSampler(torch.utils.data.Sampler): """ Concatenates two sampl...
6,259
41.297297
136
py
pose_refinement
pose_refinement-master/src/training/callbacks.py
import math import numpy as np import torch from training.loaders import UnchunkedGenerator from training.torch_tools import eval_results from util.pose import remove_root, mrpe, optimal_scaling, r_mpjpe class BaseCallback(object): def on_itergroup_end(self, iter_cnt, epoch_loss): pass def on_epoch...
13,217
38.57485
117
py
pose_refinement
pose_refinement-master/src/training/torch_tools.py
import numpy as np from torch.utils.data import DataLoader, TensorDataset from itertools import zip_longest, chain import torch from util.misc import assert_shape from inspect import signature import time from torch import optim from util.pose import mrpe def exp_decay(params): def f(epoch): return params...
13,551
35.926431
136
py
pose_refinement
pose_refinement-master/src/training/__init__.py
0
0
0
py
pose_refinement
pose_refinement-master/src/training/preprocess.py
import numpy as np import torch from databases.datasets import PoseDataset from databases.joint_sets import Common14Joints, CocoExJoints, MuPoTSJoints from util.misc import assert_shape, load from util.pose import remove_root, remove_root_keepscore, combine_pose_and_trans def preprocess_2d(data, fx, cx, fy, cy, join...
16,694
33.853862
139
py
pose_refinement
pose_refinement-master/src/util/mx_tools.py
import numpy as np def project_points(calib, points3d): """ Projects 3D points using a calibration matrix. Parameters: points3d: ndarray of shape (nPoints, 3) """ assert points3d.ndim == 2 and points3d.shape[1] == 3 p = np.empty((len(points3d), 2)) p[:, 0] = points3d[:, 0] / poin...
1,694
32.235294
97
py
pose_refinement
pose_refinement-master/src/util/misc.py
import json import os import pickle import numpy as np import scipy.io def ensuredir(path): """ Creates a folder if it doesn't exists. :param path: path to the folder to create """ if len(path) == 0: return if not os.path.exists(path): os.makedirs(path) def load(path, pkl_p...
3,651
31.035088
128
py
pose_refinement
pose_refinement-master/src/util/pose.py
import numpy as np from databases.joint_sets import CocoExJoints from util.misc import assert_shape def harmonic_mean(a, b, eps=1e-6): return 2 / (1 / (a + eps) + 1 / (b + eps)) def _combine(data, target, a, b): """ Modifies data by combining (taking average) joints at index a and b at position target....
7,952
30.939759
113
py
pose_refinement
pose_refinement-master/src/util/viz.py
"""Functions to visualize human poses""" import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, ImageMagickWriter from mpl_toolkits.mplot3d import proj3d import cv2 def get_3d_axes(*subplot): """ Creates a 3D Matplotlib axis. The arguments are the same as of the `...
12,276
35.322485
129
py
pose_refinement
pose_refinement-master/src/util/__init__.py
0
0
0
py
pose_refinement
pose_refinement-master/src/scripts/generate_muco_temp.py
""" generates the muco_temp synthetic dataset. In order to use this script, you already have to have to have generated the sequence meta data files in 'sequence_meta.pkl' and the ground-truth poses. The scripts can be found in mpi_inf_3dhp.ipynb """ from databases import mpii_3dhp, muco_temp from databases.joint_sets i...
2,445
41.912281
126
py
pose_refinement
pose_refinement-master/src/scripts/maskrcnn_bboxes.py
""" Generates Mask-RCNN bounding boxes. """ import argparse from detectron2.utils.logger import setup_logger setup_logger() # import some common libraries import numpy as np import cv2 # import some common detectron2 utilities from detectron2 import model_zoo from detectron2.config import get_cfg import detectron2....
3,049
29.19802
101
py
pose_refinement
pose_refinement-master/src/scripts/hrnet_predict.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys sys.path.append('../hrnet/lib') from scripts import hrnet_dataset # ------------------------------------------------------------------------------ # pose.pytorch # Copyright (c) 2018-present Micros...
7,588
33.03139
95
py
pose_refinement
pose_refinement-master/src/scripts/hrnet_dataset.py
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Bin Xiao (Bin.Xiao@microsoft.com) # Modified by Marton Veges # ------------------------------------------------------------------------------ from __future__ impor...
10,625
32.415094
128
py
pose_refinement
pose_refinement-master/src/scripts/eval.py
#!/usr/bin/python3 """ Evaluates a (not end2end) model on MuPo-TS """ import argparse import os import numpy as np import torch from util.misc import load from databases import mupots_3d from databases.datasets import PersonStackedMuPoTsDataset from databases.joint_sets import MuPoTSJoints, CocoExJoints from model.po...
4,512
34.81746
127
py
pose_refinement
pose_refinement-master/src/scripts/__init__.py
0
0
0
py
pose_refinement
pose_refinement-master/src/scripts/predict.py
import argparse import cv2 import numpy as np import os from databases.datasets import FlippableDataset from databases.joint_sets import MuPoTSJoints, CocoExJoints from model.pose_refinement import optimize_poses from scripts.eval import load_model, LOG_PATH from training.callbacks import TemporalTestEvaluator from tr...
6,812
38.842105
132
py
pose_refinement
pose_refinement-master/src/scripts/train.py
import argparse import os from databases.datasets import Mpi3dTestDataset, Mpi3dTrainDataset, PersonStackedMucoTempDataset, ConcatPoseDataset from model.videopose import TemporalModel, TemporalModelOptimized1f from training.callbacks import preds_from_logger, ModelCopyTemporalEvaluator from training.loaders import Chu...
7,059
38.222222
122
py
pose_refinement
pose_refinement-master/src/databases/mupots_3d.py
import glob import os import cv2 import numpy as np from databases.joint_sets import MuPoTSJoints from util.misc import load, assert_shape from util.mx_tools import calibration_matrix MUPO_TS_PATH = '../datasets/MuPoTS' def _decode_sequence(sequence): assert isinstance(sequence, (int, np.int32, str)), "sequenc...
11,443
36.768977
119
py
pose_refinement
pose_refinement-master/src/databases/joint_sets.py
import numpy as np from util.misc import assert_shape # SIDEDNESS # 0 - right # 1 - left # 2 - center class JointSet: def index_of(self, joint_name): joint_inds = np.where(self.NAMES == joint_name)[0] assert len(joint_inds) > 0, "No joint called " + joint_name return joint_inds[0] de...
4,916
39.636364
123
py
pose_refinement
pose_refinement-master/src/databases/muco_temp.py
import os import cv2 from util.misc import load MUCO_TEMP_PATH = '../datasets/MucoTemp' def get_frame(cam, vid_id, frame_ind, rgb=True): path = os.path.join(MUCO_TEMP_PATH, 'frames/cam_%d/vid_%d' % (cam, vid_id), 'img_%04d.jpg' % frame_ind) img = cv2.imread(path) if rgb: img = cv2.cvtColor(img,...
830
27.655172
130
py
pose_refinement
pose_refinement-master/src/databases/datasets.py
import os import h5py import numpy as np from torch.utils.data import Dataset from databases import mupots_3d, mpii_3dhp, muco_temp from databases.joint_sets import CocoExJoints, OpenPoseJoints, MuPoTSJoints class PoseDataset(Dataset): """ Subclasses should have the attributes poses2d/3d, pred_cdepths, pose[2|3...
27,399
42.149606
132
py
pose_refinement
pose_refinement-master/src/databases/mpii_3dhp.py
import os import cv2 import numpy as np from databases.joint_sets import MuPoTSJoints from util.misc import load MPII_3DHP_PATH = '../datasets/Mpi3DHP' def test_frames(seq): frames = sorted(os.listdir(os.path.join(MPII_3DHP_PATH, 'mpi_inf_3dhp_test_set', 'TS%d' % seq, 'imageSequence'))) # In TS3/TS4 last ...
6,001
34.099415
136
py
pose_refinement
pose_refinement-master/src/databases/__init__.py
0
0
0
py
pose_refinement
pose_refinement-master/src/model/pose_refinement.py
import numpy as np import torch from scipy import ndimage from databases.joint_sets import MuPoTSJoints from training.callbacks import BaseMPJPECalculator from training.torch_tools import get_optimizer from util.misc import assert_shape from util.pose import remove_root, insert_zero_joint def pose_error(pred, init):...
7,511
34.267606
127
py
pose_refinement
pose_refinement-master/src/model/__init__.py
0
0
0
py
pose_refinement
pose_refinement-master/src/model/videopose.py
# Based on https://github.com/facebookresearch/VideoPose3D # # Copyright (c) 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import torch.nn as nn class TemporalModelBase(nn.Module): ""...
9,265
40.927602
116
py
UltraNest
UltraNest-master/setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except: from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension from Cython.Distutils import build_ext extra_include_dirs = ['.'] try: import numpy extra_include_dirs ...
2,347
29.102564
97
py
UltraNest
UltraNest-master/languages/c++/runcppsimple.py
import numpy as np import ctypes from ultranest import ReactiveNestedSampler # this version uses one parameter vector per function call # because function calls are expensive, the runcpp.py way is more efficient and recommended mycpplib = ctypes.CDLL("mycpplib.so") # define the arguments of the functions and return ...
1,039
29.588235
94
py
UltraNest
UltraNest-master/languages/c++/runcpp.py
import numpy as np import ctypes from ultranest import ReactiveNestedSampler mycpplib = ctypes.CDLL("mycpplib.so") # define the arguments of the functions and return values mycpplib.my_cpp_transform_vectorized.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_size_t...
1,108
30.685714
111
py
UltraNest
UltraNest-master/languages/python/runpy.py
import numpy as np from ultranest import ReactiveNestedSampler def mytransform(cube): return cube * 2 - 1 def mylikelihood(params): centers = 0.1 * np.arange(params.shape[1]).reshape((1, -1)) return -0.5 * (((params - centers) / 0.01)**2).sum(axis=1) paramnames = ["a", "b", "c"] sampler = ReactiveNestedS...
446
26.9375
97
py
UltraNest
UltraNest-master/languages/c/runcsimple.py
import numpy as np import ctypes from ultranest import ReactiveNestedSampler # this version uses one parameter vector per function call # because function calls are expensive, the runc.py way is more efficient and recommended myclib = ctypes.CDLL("mylib.so") # define the arguments of the functions and return value...
1,013
29.727273
94
py
UltraNest
UltraNest-master/languages/c/runc.py
import numpy as np import ctypes from ultranest import ReactiveNestedSampler myclib = ctypes.CDLL("mylib.so") # define the arguments of the functions and return values myclib.my_c_transform_vectorized.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_size_t, ...
1,089
30.142857
111
py
UltraNest
UltraNest-master/languages/fortran/runfort.py
import numpy as np import ctypes from ultranest import ReactiveNestedSampler myfortlib = ctypes.CDLL("myfortlib.so") # define the arguments of the functions and return values myfortlib.my_fort_transform.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'), ctypes.POINTER(ctypes....
1,249
31.051282
94
py
UltraNest
UltraNest-master/examples/testfunnel.py
import argparse import numpy as np from numpy import log def main(args): np.random.seed(2) ndim = args.x_dim sigma = args.sigma centers = np.sin(np.arange(ndim) / 2.) data = np.random.normal(centers, sigma).reshape((1, -1)) def loglike(theta): sigma = 10**theta[:,0] like = -0.5...
1,890
33.381818
125
py
UltraNest
UltraNest-master/examples/rundirichlet.py
#!/usr/bin/env python3 """ This script tests the UltraNest stepsamplers in a few configurations with a real model. """ import numpy as np import ultranest, ultranest.stepsampler # velocity dispersions of dwarf galaxies by van Dokkum et al., Nature, 555, 629 https://arxiv.org/abs/1803.10237v1 values = np.array([15, ...
2,378
33.478261
114
py
UltraNest
UltraNest-master/examples/testslantedeggbox.py
import os import sys import argparse import numpy as np from numpy import cos, pi def main(args): def loglike(z): chi = (2. + (cos(z[:,:2] / 2.)).prod(axis=1))**5 chi2 = -np.abs((z - 5 * pi) / 0.5).sum(axis=1) return chi + chi2 def transform(x): return x * 100 import ...
1,676
31.25
82
py
UltraNest
UltraNest-master/examples/test.py
import os import sys import argparse import numpy as np def main(args): from ultranest import NestedSampler #def loglike(z): # return np.array([-sum(100.0 * (x[1:] - x[:-1] ** 2.0) ** 2.0 + (1 - x[:-1]) ** 2.0) for x in z]) def loglike_(z): return np.array([-sum(100.0 * (x[1::2] - x[::2] **...
2,192
38.872727
107
py
UltraNest
UltraNest-master/examples/testrosenbrock.py
import argparse import numpy as np def main(args): ndim = args.x_dim adaptive_nsteps = args.adapt_steps if adaptive_nsteps is None: adaptive_nsteps = False def loglike(theta): a = theta[:,:-1] b = theta[:,1:] return -2 * (100 * (b - a**2)**2 + (1 - a)**2).sum(axis=1) ...
6,260
39.655844
136
py