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
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/dqn_algos/demo.py
import numpy as np from arguments import get_args from models import net import torch from rl_utils.env_wrapper.atari_wrapper import make_atari, wrap_deepmind def get_tensors(obs): obs = np.transpose(obs, (2, 0, 1)) obs = np.expand_dims(obs, 0) obs = torch.tensor(obs, dtype=torch.float32) return obs i...
1,134
30.527778
90
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/dqn_algos/models.py
import torch import torch.nn as nn import torch.nn.functional as F # the convolution layer of deepmind class deepmind(nn.Module): def __init__(self): super(deepmind, self).__init__() self.conv1 = nn.Conv2d(4, 32, 8, stride=4) self.conv2 = nn.Conv2d(32, 64, 4, stride=2) self.conv3 = ...
2,596
37.761194
88
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/dqn_algos/train.py
import sys from arguments import get_args from rl_utils.env_wrapper.create_env import create_single_env from rl_utils.logger import logger, bench from rl_utils.seeds.seeds import set_seeds from dqn_agent import dqn_agent import os import numpy as np if __name__ == '__main__': # get arguments args = get_args()...
589
24.652174
61
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/dqn_algos/dqn_agent.py
import sys import numpy as np from models import net from utils import linear_schedule, select_actions, reward_recorder from rl_utils.experience_replay.experience_replay import replay_buffer import torch from datetime import datetime import os import copy # define the dqn agent class dqn_agent: def __init__(self, ...
5,646
43.81746
144
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/trpo/trpo_agent.py
import torch import numpy as np import os from models import network from rl_utils.running_filter.running_filter import ZFilter from utils import select_actions, eval_actions, conjugated_gradient, line_search, set_flat_params_to from datetime import datetime class trpo_agent: def __init__(self, env, args): ...
9,299
52.142857
129
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/trpo/arguments.py
import argparse def get_args(): parse = argparse.ArgumentParser() parse.add_argument('--gamma', type=float, default=0.99, help='the discount factor of the RL') parse.add_argument('--env-name', type=str, default='Walker2d-v2', help='the training environment') parse.add_argument('--seed', type=int, defau...
1,521
62.416667
117
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/trpo/utils.py
import numpy as np import torch from torch.distributions.normal import Normal # select actions def select_actions(pi): mean, std = pi normal_dist = Normal(mean, std) return normal_dist.sample().detach().numpy().squeeze() # evaluate the actions def eval_actions(pi, actions): mean, std = pi normal_d...
2,026
33.355932
125
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/trpo/demo.py
import numpy as np import torch import gym from arguments import get_args from models import network def denormalize(x, mean, std, clip=10): x -= mean x /= (std + 1e-8) return np.clip(x, -clip, clip) def get_tensors(x): return torch.tensor(x, dtype=torch.float32).unsqueeze(0) if __name__ == '__main__...
1,383
31.952381
94
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/trpo/models.py
import torch from torch import nn from torch.nn import functional as F class network(nn.Module): def __init__(self, num_states, num_actions): super(network, self).__init__() # define the critic self.critic = critic(num_states) self.actor = actor(num_states, num_actions) def for...
1,376
28.297872
66
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/trpo/train.py
from arguments import get_args from rl_utils.seeds.seeds import set_seeds from rl_utils.env_wrapper.create_env import create_single_env from trpo_agent import trpo_agent if __name__ == '__main__': args = get_args() # make environemnts env = create_single_env(args) # set the random seeds set_seeds(a...
461
26.176471
61
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/a2c/a2c_agent.py
import numpy as np import torch from models import net from datetime import datetime from utils import select_actions, evaluate_actions, discount_with_dones import os class a2c_agent: def __init__(self, envs, args): self.envs = envs self.args = args # define the network self.net = n...
6,370
47.633588
135
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/a2c/arguments.py
import argparse def get_args(): parse = argparse.ArgumentParser() parse.add_argument('--gamma', type=float, default=0.99, help='the discount factor of RL') parse.add_argument('--seed', type=int, default=123, help='the random seeds') parse.add_argument('--env-name', type=str, default='BreakoutNoFrameski...
1,881
66.214286
109
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/a2c/utils.py
import torch import numpy as np from torch.distributions.categorical import Categorical # select - actions def select_actions(pi, deterministic=False): cate_dist = Categorical(pi) if deterministic: return torch.argmax(pi, dim=1).item() else: return cate_dist.sample().unsqueeze(-1) # get th...
749
29
92
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/a2c/demo.py
from arguments import get_args from models import net import torch from utils import select_actions import cv2 import numpy as np from rl_utils.env_wrapper.frame_stack import VecFrameStack from rl_utils.env_wrapper.atari_wrapper import make_atari, wrap_deepmind # update the current observation def get_tensors(obs): ...
1,193
33.114286
95
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/a2c/models.py
import torch import torch.nn as nn import torch.nn.functional as F # the convolution layer of deepmind class deepmind(nn.Module): def __init__(self): super(deepmind, self).__init__() self.conv1 = nn.Conv2d(4, 32, 8, stride=4) self.conv2 = nn.Conv2d(32, 64, 4, stride=2) self.conv3 = ...
1,959
37.431373
88
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/a2c/train.py
from arguments import get_args from a2c_agent import a2c_agent from rl_utils.env_wrapper.create_env import create_multiple_envs from rl_utils.seeds.seeds import set_seeds from a2c_agent import a2c_agent import os if __name__ == '__main__': # set signle thread os.environ['OMP_NUM_THREADS'] = '1' os.environ[...
612
25.652174
64
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ddpg/arguments.py
import argparse def get_args(): parse = argparse.ArgumentParser(description='ddpg') parse.add_argument('--env-name', type=str, default='Pendulum-v0', help='the training environment') parse.add_argument('--lr-actor', type=float, default=1e-4, help='the lr of the actor') parse.add_argument('--lr-critic',...
2,113
69.466667
105
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ddpg/utils.py
import numpy as np import torch # add ounoise here class ounoise(): def __init__(self, std, action_dim, mean=0, theta=0.15, dt=1e-2, x0=None): self.std = std self.mean = mean self.action_dim = action_dim self.theta = theta self.dt = dt self.x0 = x0 # reset t...
686
27.625
84
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ddpg/demo.py
from arguments import get_args import gym from models import actor import torch import numpy as np def normalize(obs, mean, std, clip): return np.clip((obs - mean) / std, -clip, clip) if __name__ == '__main__': args = get_args() env = gym.make(args.env_name) # get environment infos obs_dims = env....
1,518
34.325581
90
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ddpg/ddpg_agent.py
import numpy as np from models import actor, critic import torch import os from datetime import datetime from mpi4py import MPI from rl_utils.mpi_utils.normalizer import normalizer from rl_utils.mpi_utils.utils import sync_networks, sync_grads from rl_utils.experience_replay.experience_replay import replay_buffer from...
8,833
45.494737
142
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ddpg/models.py
import torch import torch.nn as nn import torch.nn.functional as F # define the actor network class actor(nn.Module): def __init__(self, obs_dims, action_dims): super(actor, self).__init__() self.fc1 = nn.Linear(obs_dims, 400) self.fc2 = nn.Linear(400, 300) self.action_out = nn.Line...
950
28.71875
53
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ddpg/train.py
from ddpg_agent import ddpg_agent from arguments import get_args from rl_utils.seeds.seeds import set_seeds from rl_utils.env_wrapper.create_env import create_single_env from mpi4py import MPI import os if __name__ == '__main__': # set thread and mpi stuff os.environ['OMP_NUM_THREADS'] = '1' os.environ['MK...
717
28.916667
61
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ppo/arguments.py
import argparse def get_args(): parse = argparse.ArgumentParser() parse.add_argument('--gamma', type=float, default=0.99, help='the discount factor of RL') parse.add_argument('--seed', type=int, default=123, help='the random seeds') parse.add_argument('--num-workers', type=int, default=8, help='the num...
2,274
72.387097
116
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ppo/utils.py
import numpy as np import torch from torch.distributions.normal import Normal from torch.distributions.beta import Beta from torch.distributions.categorical import Categorical import random def select_actions(pi, dist_type, env_type): if env_type == 'atari': actions = Categorical(pi).sample() else: ...
1,370
35.078947
78
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ppo/demo.py
from arguments import get_args from models import cnn_net, mlp_net import torch import cv2 import numpy as np import gym from rl_utils.env_wrapper.frame_stack import VecFrameStack from rl_utils.env_wrapper.atari_wrapper import make_atari, wrap_deepmind # denormalize def normalize(x, mean, std, clip=10): x -= mean ...
2,641
35.694444
112
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ppo/models.py
import torch from torch import nn from torch.nn import functional as F """ this network also include gaussian distribution and beta distribution """ class mlp_net(nn.Module): def __init__(self, state_size, num_actions, dist_type): super(mlp_net, self).__init__() self.dist_type = dist_type ...
3,913
37
88
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ppo/ppo_agent.py
import numpy as np import torch from torch import optim from rl_utils.running_filter.running_filter import ZFilter from models import cnn_net, mlp_net from utils import select_actions, evaluate_actions from datetime import datetime import os import copy class ppo_agent: def __init__(self, envs, args): self...
11,143
50.592593
144
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/ppo/train.py
from arguments import get_args from ppo_agent import ppo_agent from rl_utils.env_wrapper.create_env import create_multiple_envs, create_single_env from rl_utils.seeds.seeds import set_seeds import os if __name__ == '__main__': # set signle thread os.environ['OMP_NUM_THREADS'] = '1' os.environ['MKL_NUM_THRE...
757
28.153846
83
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/sac/arguments.py
import argparse # define the arguments that will be used in the SAC def get_args(): parse = argparse.ArgumentParser() parse.add_argument('--env-name', type=str, default='HalfCheetah-v2', help='the environment name') parse.add_argument('--cuda', action='store_true', help='use GPU do the training') parse...
3,080
82.27027
123
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/sac/utils.py
import numpy as np import torch from torch.distributions.normal import Normal from torch.distributions import Distribution """ the tanhnormal distributions from rlkit may not stable """ class tanh_normal(Distribution): def __init__(self, normal_mean, normal_std, epsilon=1e-6, cuda=False): self.normal_mean...
2,841
34.08642
118
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/sac/demo.py
from arguments import get_args import gym import torch import numpy as np from models import tanh_gaussian_actor if __name__ == '__main__': args = get_args() env = gym.make(args.env_name) # get environment infos obs_dims = env.observation_space.shape[0] action_dims = env.action_space.shape[0] a...
1,433
35.769231
112
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/sac/sac_agent.py
import numpy as np import torch from models import flatten_mlp, tanh_gaussian_actor from rl_utils.experience_replay.experience_replay import replay_buffer from utils import get_action_info from datetime import datetime import copy import os import gym """ 2019-Nov-12 - start to add the automatically tempature tuning ...
10,871
49.803738
166
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/sac/models.py
import torch import torch.nn as nn import torch.nn.functional as F # the flatten mlp class flatten_mlp(nn.Module): #TODO: add the initialization method for it def __init__(self, input_dims, hidden_size, action_dims=None): super(flatten_mlp, self).__init__() self.fc1 = nn.Linear(input_dims, hidd...
1,745
38.681818
130
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/sac/train.py
from arguments import get_args from sac_agent import sac_agent from rl_utils.seeds.seeds import set_seeds from rl_utils.env_wrapper.create_env import create_single_env if __name__ == '__main__': args = get_args() # build the environment env = create_single_env(args) # set the seeds set_seeds(args) ...
450
25.529412
61
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/__init__.py
0
0
0
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/seeds/seeds.py
import numpy as np import random import torch # set random seeds for the pytorch, numpy and random def set_seeds(args, rank=0): # set seeds for the numpy np.random.seed(args.seed + rank) # set seeds for the random.random random.seed(args.seed + rank) # set seeds for the pytorch torch.manual_see...
407
26.2
52
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/experience_replay/experience_replay.py
import numpy as np import random """ define the replay buffer and corresponding algorithms like PER """ class replay_buffer: def __init__(self, memory_size): self.storge = [] self.memory_size = memory_size self.next_idx = 0 # add the samples def add(self, obs, action, reward,...
1,380
31.880952
103
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/logger/logger.py
import os import sys import shutil import os.path as osp import json import time import datetime import tempfile from collections import defaultdict from contextlib import contextmanager DEBUG = 10 INFO = 20 WARN = 30 ERROR = 40 DISABLED = 50 class KVWriter(object): def writekvs(self, kvs): raise NotImpl...
14,802
28.429423
122
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/logger/bench.py
__all__ = ['Monitor', 'get_monitor_files', 'load_results'] from gym.core import Wrapper import time from glob import glob import csv import os.path as osp import json class Monitor(Wrapper): EXT = "monitor.csv" f = None def __init__(self, env, filename, allow_early_resets=False, reset_keywords=(), info_k...
5,704
34
174
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/logger/plot.py
import numpy as np from matplotlib import pyplot as plt import seaborn as sns from rl_utils.bench import load_results sns.set(style="dark") sns.set_context("poster", font_scale=2, rc={"lines.linewidth": 2}) sns.set(rc={"figure.figsize": (15, 8)}) colors = sns.color_palette(palette='muted') X_TIMESTEPS = 'timesteps' ...
3,962
38.237624
115
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/logger/__init__.py
0
0
0
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/mpi_utils/normalizer.py
import threading import numpy as np from mpi4py import MPI class normalizer: def __init__(self, size, eps=1e-2, default_clip_range=np.inf): self.size = size self.eps = eps self.default_clip_range = default_clip_range # some local information self.local_sum = np.zeros(self.si...
2,777
38.126761
145
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/mpi_utils/utils.py
from mpi4py import MPI import numpy as np import torch # sync_networks across the different cores def sync_networks(network): """ netowrk is the network you want to sync """ comm = MPI.COMM_WORLD flat_params = _get_flat_params_or_grads(network, mode='params') comm.Bcast(flat_params, root=0) ...
1,427
31.454545
119
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/mpi_utils/__init__.py
0
0
0
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/running_filter/__init__.py
0
0
0
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/running_filter/running_filter.py
from collections import deque import numpy as np # this is from the https://github.com/ikostrikov/pytorch-trpo/blob/master/running_state.py # from https://github.com/joschu/modular_rl # http://www.johndcook.com/blog/standard_deviation/ class RunningStat(object): def __init__(self, shape): self._n = 0 ...
1,715
23.169014
90
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/env_wrapper/create_env.py
from rl_utils.env_wrapper.atari_wrapper import make_atari, wrap_deepmind from rl_utils.env_wrapper.multi_envs_wrapper import SubprocVecEnv from rl_utils.env_wrapper.frame_stack import VecFrameStack from rl_utils.logger import logger, bench import os import gym """ this functions is to create the environments """ def...
2,239
34.555556
104
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/env_wrapper/multi_envs_wrapper.py
import multiprocessing as mp import numpy as np from rl_utils.env_wrapper import VecEnv, CloudpickleWrapper, clear_mpi_env_vars def worker(remote, parent_remote, env_fn_wrapper): parent_remote.close() env = env_fn_wrapper.x() try: while True: cmd, data = remote.recv() if cmd...
4,074
34.12931
128
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/env_wrapper/frame_stack.py
from rl_utils.env_wrapper import VecEnvWrapper import numpy as np from gym import spaces class VecFrameStack(VecEnvWrapper): def __init__(self, venv, nstack): self.venv = venv self.nstack = nstack wos = venv.observation_space # wrapped ob space low = np.repeat(wos.low, self.nstack...
1,162
36.516129
94
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/env_wrapper/__init__.py
import os from abc import ABC, abstractmethod import contextlib class AlreadySteppingError(Exception): """ Raised when an asynchronous step is running while step_async() is called again. """ def __init__(self): msg = 'already running an async step' Exception.__init__(self, msg) c...
5,877
26.596244
219
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_utils/env_wrapper/atari_wrapper.py
import numpy as np import os os.environ.setdefault('PATH', '') from collections import deque import gym from gym import spaces import cv2 cv2.ocl.setUseOpenCL(False) """ the wrapper is taken from the openai baselines """ class NoopResetEnv(gym.Wrapper): def __init__(self, env, noop_max=30): """Sample ini...
10,334
32.125
130
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/eval.py
""" Run evaluation with saved models. """ import random import argparse from tqdm import tqdm import torch from data.loader import DataLoader from model.trainer import GCNTrainer from utils import torch_utils, scorer, constant, helper from utils.vocab import Vocab parser = argparse.ArgumentParser() parser.add_argumen...
2,130
30.80597
97
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/prepare_vocab.py
""" Prepare vocabulary and initial word vectors. """ import json import pickle import argparse import numpy as np from collections import Counter from utils import vocab, constant, helper def parse_args(): parser = argparse.ArgumentParser(description='Prepare vocab for relation extraction.') parser.add_argume...
4,313
35.252101
102
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/train.py
""" Train a model on TACRED. """ import os import sys from datetime import datetime import time import numpy as np import random import argparse from shutil import copyfile import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from data.loader import DataLoader from model....
8,638
44.708995
156
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/utils/constant.py
""" Define constants. """ EMB_INIT_RANGE = 1.0 # vocab PAD_TOKEN = '<PAD>' PAD_ID = 0 UNK_TOKEN = '<UNK>' UNK_ID = 1 VOCAB_PREFIX = [PAD_TOKEN, UNK_TOKEN] # hard-coded mappings from fields to ids SUBJ_NER_TO_ID = {PAD_TOKEN: 0, UNK_TOKEN: 1, 'ORGANIZATION': 2, 'PERSON': 3} OBJ_NER_TO_ID = {PAD_TOKEN: 0, UNK_TOKEN: ...
3,049
100.666667
1,091
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/utils/scorer.py
#!/usr/bin/env python """ Score the predictions with gold labels, using precision, recall and F1 metrics. """ import argparse import sys from collections import Counter NO_RELATION = "no_relation" def parse_arguments(): parser = argparse.ArgumentParser(description='Score a prediction file using the gold labels....
4,324
37.616071
137
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/utils/helper.py
""" Helper functions. """ import os import subprocess import json import argparse ### IO def check_dir(d): if not os.path.exists(d): print("Directory {} does not exist. Exit.".format(d)) exit(1) def check_files(files): for f in files: if f is not None and not os.path.exists(f): ...
1,698
24.742424
69
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/utils/vocab.py
""" A class for basic vocab operations. """ from __future__ import print_function import os import random import numpy as np import pickle from utils import constant random.seed(1234) np.random.seed(1234) def build_embedding(wv_file, vocab, wv_dim): vocab_size = len(vocab) emb = np.random.uniform(-1, 1, (vo...
3,714
35.782178
112
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/utils/torch_utils.py
""" Utility functions for torch. """ import torch from torch import nn, optim from torch.optim import Optimizer ### class class MyAdagrad(Optimizer): """My modification of the Adagrad optimizer that allows to specify an initial accumulater value. This mimics the behavior of the default Adagrad implementation ...
5,681
33.858896
106
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/data/loader.py
""" Data loader for TACRED json files. """ import json import random import torch import numpy as np from utils import constant, helper, vocab class DataLoader(object): """ Load data from json files, preprocess and prepare batches. """ def __init__(self, filename, batch_size, opt, vocab, evaluation=F...
5,487
36.848276
121
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/model/tree.py
""" Basic operations on trees. """ import numpy as np from collections import defaultdict class Tree(object): """ Reused tree object from stanfordnlp/treelstm. """ def __init__(self): self.parent = None self.num_children = 0 self.children = list() def add_child(self,child)...
4,951
25.623656
75
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/model/gcn.py
""" GCN model for relation extraction. """ import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from model.tree import Tree, head_to_tree, tree_to_adj from utils import constant, torch_utils class GCNClassifier(nn.Module): """ A wrapper classif...
7,886
39.239796
131
py
gcn-over-pruned-trees
gcn-over-pruned-trees-master/model/trainer.py
""" A trainer class. """ import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from model.gcn import GCNClassifier from utils import constant, torch_utils class Trainer(object): def __init__(self, opt, emb_matrix=None): raise NotImplemen...
3,659
32.888889
101
py
SwinMR
SwinMR-main/main_test_swinmr_CC.py
''' # ----------------------------------------- Main Program for Testing SwinMR for MRI_Recon Dataset: CC by Jiahao Huang (j.huang21@imperial.ac.uk) # ----------------------------------------- ''' import argparse import cv2 import csv import sys import numpy as np from collections import OrderedDict import os import t...
11,599
40.281139
134
py
SwinMR
SwinMR-main/main_train_swinmr.py
''' # ----------------------------------------- Main Program for Training SwinMR for MRI_Recon by Jiahao Huang (j.huang21@imperial.ac.uk) # ----------------------------------------- ''' import os import sys import math import argparse import random import cv2 import numpy as np import logging import time import torch...
15,434
43.353448
176
py
SwinMR
SwinMR-main/models/model_base.py
import os import torch import torch.nn as nn from utils.utils_bnorm import merge_bn, tidy_sequential from torch.nn.parallel import DataParallel, DistributedDataParallel class ModelBase(): def __init__(self, opt): self.opt = opt # opt self.save_dir = opt['path']['models'] #...
7,442
33.299539
148
py
SwinMR
SwinMR-main/models/select_network.py
''' # ----------------------------------------- Define Training Network by Jiahao Huang (j.huang21@imperial.ac.uk) # ----------------------------------------- ''' import functools import torch import torchvision.models from torch.nn import init # -------------------------------------------- # Recon Generator, netG, ...
5,220
35.006897
113
py
SwinMR
SwinMR-main/models/network_swinmr.py
''' # ----------------------------------------- Network SwinMR m.1.3 by Jiahao Huang (j.huang21@imperial.ac.uk) Thanks: https://github.com/JingyunLiang/SwinIR https://github.com/microsoft/Swin-Transformer # ----------------------------------------- ''' import math import torch import torch.nn as nn import torch.nn.fu...
41,096
41.631743
175
py
SwinMR
SwinMR-main/models/loss.py
import torch import torch.nn as nn import torchvision from torch.nn import functional as F from torch import autograd as autograd import math """ Sequential( (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (1): ReLU(inplace) (2*): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1...
14,821
37.299742
150
py
SwinMR
SwinMR-main/models/network_feature.py
import torch import torch.nn as nn import torchvision """ # -------------------------------------------- # VGG Feature Extractor # -------------------------------------------- """ # -------------------------------------------- # VGG features # Assume input range is [0, 1] # ------------------------------------------...
1,594
32.93617
93
py
SwinMR
SwinMR-main/models/basicblock.py
from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F ''' # -------------------------------------------- # Advanced nn.Sequential # https://github.com/xinntao/BasicSR # -------------------------------------------- ''' def sequential(*args): """Advanced nn.Sequent...
24,138
39.775338
160
py
SwinMR
SwinMR-main/models/select_model.py
''' # ----------------------------------------- Define Training Model by Jiahao Huang (j.huang21@imperial.ac.uk) # ----------------------------------------- ''' def define_Model(opt): model = opt['model'] # -------------------------------------------------------- # SwinMR # ---------------------------...
731
26.111111
79
py
SwinMR
SwinMR-main/models/select_mask.py
''' # ----------------------------------------- Define Undersampling Mask by Jiahao Huang (j.huang21@imperial.ac.uk) # ----------------------------------------- ''' import os import scipy import scipy.fftpack from scipy.io import loadmat import cv2 import numpy as np def define_Mask(opt): mask_name = opt['mask']...
5,773
47.521008
112
py
SwinMR
SwinMR-main/models/model_swinmr_pi.py
''' # ----------------------------------------- Model SwinMR (PI) m.1.3 by Jiahao Huang (j.huang21@imperial.ac.uk) Thanks: https://github.com/JingyunLiang/SwinIR https://github.com/microsoft/Swin-Transformer # ----------------------------------------- ''' from collections import OrderedDict import torch import torch....
14,836
39.649315
176
py
SwinMR
SwinMR-main/models/model_swinmr.py
''' # ----------------------------------------- Model SwinMR m.1.3 by Jiahao Huang (j.huang21@imperial.ac.uk) Thanks: https://github.com/JingyunLiang/SwinIR https://github.com/microsoft/Swin-Transformer # ----------------------------------------- ''' from collections import OrderedDict import torch import torch.nn as...
14,546
39.520891
176
py
SwinMR
SwinMR-main/utils/utils_early_stopping.py
""" # -------------------------------------------- # Early Stopping # -------------------------------------------- # Jiahao Huang (j.huang21@imperial.uk.ac) # 30/Jan/2022 # -------------------------------------------- """ class EarlyStopping: """Early stops the training if validation loss doesn't improve after a ...
1,297
27.217391
108
py
SwinMR
SwinMR-main/utils/utils_image.py
import os import math import random import numpy as np import torch import cv2 from numpy import Inf from torchvision.utils import make_grid from datetime import datetime # import torchvision.transforms as transforms import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import skimage.metrics import S...
38,657
31.595278
120
py
SwinMR
SwinMR-main/utils/utils_dist.py
# Modified from https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/dist_utils.py # noqa: E501 import functools import os import subprocess import torch import torch.distributed as dist import torch.multiprocessing as mp # ---------------------------------- # init # ---------------------------------- def init...
5,275
25.118812
102
py
SwinMR
SwinMR-main/utils/utils_option.py
import os from collections import OrderedDict from datetime import datetime import json import re import glob ''' # -------------------------------------------- # Kai Zhang (github: https://github.com/cszn) # 03/Mar/2019 # -------------------------------------------- # https://github.com/xinntao/BasicSR # -----------...
7,982
31.583673
84
py
SwinMR
SwinMR-main/utils/utils_logger.py
import sys import datetime import logging ''' # -------------------------------------------- # Kai Zhang (github: https://github.com/cszn) # 03/Mar/2019 # -------------------------------------------- # https://github.com/xinntao/BasicSR # -------------------------------------------- ''' def log(*args, **kwargs): ...
1,686
24.179104
107
py
SwinMR
SwinMR-main/utils/utils_swinmr.py
import torch from torch import nn import os import cv2 import gc import numpy as np from scipy.io import * from scipy.fftpack import * """ # -------------------------------------------- # Jiahao Huang (j.huang21@imperial.uk.ac) # 30/Jan/2022 # -------------------------------------------- """ # Fourier Transform def...
455
15.888889
46
py
SwinMR
SwinMR-main/utils/utils_model.py
# -*- coding: utf-8 -*- import numpy as np import torch from utils import utils_image as util import re import glob import os ''' # -------------------------------------------- # Model # -------------------------------------------- # Kai Zhang (github: https://github.com/cszn) # 03/Mar/2019 # ------------------------...
9,837
28.902736
148
py
SwinMR
SwinMR-main/utils/utils_regularizers.py
import torch import torch.nn as nn ''' # -------------------------------------------- # Kai Zhang (github: https://github.com/cszn) # 03/Mar/2019 # -------------------------------------------- ''' # -------------------------------------------- # SVD Orthogonal Regularization # --------------------------------------...
3,416
31.542857
87
py
SwinMR
SwinMR-main/utils/utils_bnorm.py
import torch import torch.nn as nn """ # -------------------------------------------- # Batch Normalization # -------------------------------------------- # Kai Zhang (cskaizhang@gmail.com) # https://github.com/cszn # 01/Jan/2019 # -------------------------------------------- """ # --------------------------------...
3,132
33.054348
187
py
SwinMR
SwinMR-main/data/dataset_CCsagpi.py
''' # ----------------------------------------- Data Loader CC-SAG-PI d.1.1 by Jiahao Huang (j.huang21@imperial.ac.uk) # ----------------------------------------- ''' import random import torch.utils.data as data import utils.utils_image as util from utils.utils_swinmr import * from models.select_mask import define_Ma...
5,361
34.045752
116
py
SwinMR
SwinMR-main/data/select_dataset.py
''' # ----------------------------------------- Select Dataset by Jiahao Huang (j.huang21@imperial.ac.uk) # ----------------------------------------- ''' def define_Dataset(dataset_opt): dataset_type = dataset_opt['dataset_type'].lower() # ------------------------------------------------ # CC-359 Calgary...
904
30.206897
102
py
SwinMR
SwinMR-main/data/dataset_CCsagnpi.py
''' # ----------------------------------------- Data Loader CC-SAG-NPI d.1.1 by Jiahao Huang (j.huang21@imperial.ac.uk) # ----------------------------------------- ''' import random import torch.utils.data as data import utils.utils_image as util from utils.utils_swinmr import * from models.select_mask import define_M...
4,898
32.554795
105
py
risk-slim
risk-slim-master/setup.py
#! /usr/bin/env python # # Copyright (C) 2017 Berk Ustun import os import sys from setuptools import setup, find_packages, dist from setuptools.extension import Extension #resources #setuptools http://setuptools.readthedocs.io/en/latest/setuptools.html #setuptools + Cython: http://stackoverflow.com/questions/32528560...
2,322
25.397727
70
py
risk-slim
risk-slim-master/examples/ex_02_advanced_options.py
import os import numpy as np import pprint import riskslim # data data_name = "breastcancer" # name of the data data_dir = os.getcwd() + '/examples/data/' # directory where datasets are stored data_csv_file = data_dir + data_name + '_data.csv' # csv file for t...
6,526
53.848739
217
py
risk-slim
risk-slim-master/examples/ex_01_quickstart.py
import os import pprint import numpy as np import riskslim # data data_name = "breastcancer" # name of the data data_dir = os.getcwd() + '/examples/data/' # directory where datasets are stored data_csv_file = data_dir + data_name + '_data.csv' # csv file for t...
3,223
46.411765
217
py
risk-slim
risk-slim-master/examples/ex_03_constraints.py
import os import numpy as np import cplex as cplex import pprint import riskslim # data import riskslim.coefficient_set data_name = "breastcancer" # name of the data data_dir = os.getcwd() + '/examples/data/' # directory where datasets are stored data_csv_file = data_...
4,811
41.584071
217
py
risk-slim
risk-slim-master/riskslim/lattice_cpa.py
import time import numpy as np from cplex.callbacks import HeuristicCallback, LazyConstraintCallback from cplex.exceptions import CplexError from .bound_tightening import chained_updates from .defaults import DEFAULT_LCPA_SETTINGS from .utils import print_log, validate_settings from .heuristics import discrete_descent,...
37,697
42.834884
169
py
risk-slim
risk-slim-master/riskslim/coefficient_set.py
import numpy as np from prettytable import PrettyTable from .defaults import INTERCEPT_NAME class CoefficientSet(object): """ Class used to represent and manipulate constraints on individual coefficients including upper bound, lower bound, variable type, and regularization. Coefficient Set is composed...
13,648
27.978769
134
py
risk-slim
risk-slim-master/riskslim/utils.py
import logging import sys from pathlib import Path import time import warnings import numpy as np import pandas as pd import prettytable as pt from .defaults import INTERCEPT_NAME # DATA def load_data_from_csv(dataset_csv_file, sample_weights_csv_file = None, fold_csv_file = None, fold_num = 0): """ Parameter...
12,518
37.051672
126
py
risk-slim
risk-slim-master/riskslim/defaults.py
import numpy as np INTERCEPT_NAME = '(Intercept)' # Settings DEFAULT_LCPA_SETTINGS = { # 'c0_value': 1e-6, 'w_pos': 1.00, # # MIP Formulation 'drop_variables': True, #drop variables 'tight_formulation': True, #use a slightly tighter MIP formulation 'include_auxillary_variab...
5,018
47.728155
130
py
risk-slim
risk-slim-master/riskslim/initialization.py
import time import numpy as np from cplex import Cplex, SparsePair, infinity as CPX_INFINITY from .setup_functions import setup_penalty_parameters from .mip import create_risk_slim, set_cplex_mip_parameters from .solution_pool import SolutionPool from .bound_tightening import chained_updates, chained_updates_for_lp fro...
21,391
37.613718
150
py
risk-slim
risk-slim-master/riskslim/bound_tightening.py
import numpy as np def chained_updates(bounds, C_0_nnz, new_objval_at_feasible = None, new_objval_at_relaxation = None, MAX_CHAIN_COUNT = 20): new_bounds = dict(bounds) # update objval_min using new_value (only done once) if new_objval_at_relaxation is not None: if new_bounds['objval_min'] < new...
6,773
42.146497
130
py
risk-slim
risk-slim-master/riskslim/solution_pool.py
import numpy as np import prettytable as pt class SolutionPool(object): """ Helper class used to store solutions to the risk slim optimization problem """ def __init__(self, obj): if isinstance(obj, SolutionPool): self._P = obj.P self._objvals = obj.objvals ...
9,755
29.776025
111
py
risk-slim
risk-slim-master/riskslim/heuristics.py
import numpy as np #todo: finish specifications #todo: add input checking (with ability to turn off) #todo: Cython implementation def sequential_rounding(rho, Z, C_0, compute_loss_from_scores_real, get_L0_penalty, objval_cutoff = float('Inf')): """ Parameters ---------- rho: ...
11,885
39.155405
150
py
risk-slim
risk-slim-master/riskslim/setup_functions.py
import numpy as np from .coefficient_set import CoefficientSet, get_score_bounds from .utils import print_log def setup_loss_functions(data, coef_set, L0_max = None, loss_computation = None, w_pos = 1.0): """ Parameters ---------- data coef_set L0_max loss_computation w_pos Retur...
10,101
35.469314
122
py