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
SpinalNet
SpinalNet-master/MNIST/Arch2_EMNIST_Digits.py
# -*- coding: utf-8 -*- """ This Script contains the SpinalNet Arch2 for EMNIST digits. @author: Dipu """ import torch import torchvision n_epochs = 200 batch_size_train = 64 batch_size_test = 1000 momentum = 0.5 log_interval = 5000 first_HL = 50 prob = 0.5 torch.backends.cudnn.enabled = False train_l...
9,736
32.926829
117
py
SpinalNet
SpinalNet-master/MNIST/SpinalNet_EMNIST_Digits.py
# -*- coding: utf-8 -*- """ This Script contains the SpinalNet EMNIST digits code. It provides better performance for the same number of epoch. @author: Dipu """ import torch import torchvision n_epochs = 8 batch_size_train = 64 batch_size_test = 1000 learning_rate = 0.01 momentum = 0.5 log_interval = 100 first_HL ...
5,407
30.08046
84
py
SpinalNet
SpinalNet-master/Customizable Model/spinalnettorch.py
# Customizable SpinalNet. Supports up to 30 layers. import torch import torch.nn as nn import numpy as np class SpinalNet(nn.Module): def __init__(self, Input_Size, Number_of_Split, HL_width, number_HL, Output_Size, Activation_Function): super(SpinalNet, self).__init__() Splitted_Input_Si...
12,469
46.414449
107
py
SpinalNet
SpinalNet-master/CIFAR-100/CNN_dropout_Default_and_SpinalFC_CIFAR100.py
# -*- coding: utf-8 -*- """ This Script contains the default and Spinal CNN dropout code for CIFAR-100. This code trains both NNs as two different models. The code is collected and changed from: https://zhenye-na.github.io/2018/09/28/pytorch-cnn-cifar10.html This code gradually decreases the learning rate to get...
9,248
29.22549
99
py
SpinalNet
SpinalNet-master/CIFAR-100/ResNet_Default_and_SpinalFC_CIFAR100.py
# -*- coding: utf-8 -*- """ This Script contains the default and Spinal ResNet code for CIFAR-100. This code trains both NNs as two different models. There is option of choosing ResNet18(), ResNet34(), SpinalResNet18(), or SpinalResNet34(). This code randomly changes the learning rate to get a good result. @author:...
13,588
30.025114
101
py
SpinalNet
SpinalNet-master/CIFAR-100/VGG_Default_and_SpinalFC_CIFAR_100.py
# -*- coding: utf-8 -*- """ This Script contains the default and Spinal VGG code for CIFAR-100. This code trains both NNs as two different models. There is option of choosing NN among: vgg11_bn(), vgg13_bn(), vgg16_bn(), vgg19_bn() and Spinalvgg11_bn(), Spinalvgg13_bn(), Spinalvgg16_bn(), Spinalvgg19_bn() Th...
9,281
28.845659
116
py
SubOmiEmbed
SubOmiEmbed-main/test.py
""" Separated testing for OmiEmbed """ import time from util import util from params.test_params import TestParams from datasets import create_single_dataloader from models import create_model from util.visualizer import Visualizer if __name__ == '__main__': # Get testing parameter param = TestParams().parse()...
3,489
46.808219
120
py
SubOmiEmbed
SubOmiEmbed-main/train.py
""" Separated training for OmiEmbed """ import time import warnings from util import util from params.train_params import TrainParams from datasets import create_single_dataloader from models import create_model from util.visualizer import Visualizer if __name__ == "__main__": warnings.filterwarnings('ignore') ...
5,827
55.038462
146
py
SubOmiEmbed
SubOmiEmbed-main/train_test.py
""" Training and testing for OmiEmbed """ import time import warnings import numpy as np import torch from util import util from params.train_test_params import TrainTestParams from datasets import create_separate_dataloader from models import create_model from util.visualizer import Visualizer if __name__ == "__mai...
7,049
54.952381
146
py
SubOmiEmbed
SubOmiEmbed-main/models/vae_survival_model.py
import torch from .vae_basic_model import VaeBasicModel from . import networks from . import losses class VaeSurvivalModel(VaeBasicModel): """ This class implements the VAE survival model, using the VAE framework with the survival prediction downstream task. """ @staticmethod def modify_commandli...
5,390
38.933333
151
py
SubOmiEmbed
SubOmiEmbed-main/models/losses.py
import torch import torch.nn as nn def get_loss_func(loss_name, reduction='mean'): """ Return the loss function. Parameters: loss_name (str) -- the name of the loss function: BCE | MSE | L1 | CE reduction (str) -- the reduction method applied to the loss function: sum | mean """ ...
2,558
32.671053
176
py
SubOmiEmbed
SubOmiEmbed-main/models/vae_alltask_gn_model.py
import torch import torch.nn as nn from .basic_model import BasicModel from . import networks from . import losses from torch.nn import functional as F from sklearn import metrics class VaeAlltaskGNModel(BasicModel): """ This class implements the VAE multitasking model with GradNorm (all tasks), using the VAE...
17,700
47.231608
382
py
SubOmiEmbed
SubOmiEmbed-main/models/vae_regression_model.py
import torch from sklearn import metrics from .vae_basic_model import VaeBasicModel from . import networks from . import losses class VaeRegressionModel(VaeBasicModel): """ This class implements the VAE regression model, using the VAE framework with the regression downstream task. """ @staticmethod ...
3,793
37.323232
152
py
SubOmiEmbed
SubOmiEmbed-main/models/vae_alltask_model.py
import torch from .vae_basic_model import VaeBasicModel from . import networks from . import losses from torch.nn import functional as F from sklearn import metrics class VaeAlltaskModel(VaeBasicModel): """ This class implements the VAE multitasking model with all downstream tasks (5 classifiers + 1 regressor...
10,265
49.078049
371
py
SubOmiEmbed
SubOmiEmbed-main/models/networks.py
import torch import torch.nn as nn import functools from torch.nn import init from torch.optim import lr_scheduler # Class components class DownSample(nn.Module): """ SingleConv1D module + MaxPool The output dimension = input dimension // down_ratio """ def __init__(self, input_chan_num, output_c...
107,411
46.131198
202
py
SubOmiEmbed
SubOmiEmbed-main/models/basic_model.py
import os import torch import numpy as np from abc import ABC, abstractmethod from . import networks from collections import OrderedDict class BasicModel(ABC): """ This class is an abstract base class for models. To create a subclass, you need to implement the following five functions: -- <__init_...
15,137
39.475936
166
py
SubOmiEmbed
SubOmiEmbed-main/models/vae_classifier_model.py
import torch from .vae_basic_model import VaeBasicModel from . import networks from . import losses from torch.nn import functional as F import random class VaeClassifierModel(VaeBasicModel): """ This class implements the VAE classifier model, using the VAE framework with the classification downstream task. ...
9,850
44.396313
151
py
SubOmiEmbed
SubOmiEmbed-main/models/__init__.py
""" This package contains modules related to objective functions, optimizations, and network architectures. """ import importlib from models.basic_model import BasicModel def find_model_using_name(model_name): """ Import the module with certain name """ model_filename = "models." + model_name + "_mod...
1,425
30
170
py
SubOmiEmbed
SubOmiEmbed-main/models/vae_multitask_model.py
import torch from .vae_basic_model import VaeBasicModel from . import networks from . import losses from torch.nn import functional as F from sklearn import metrics class VaeMultitaskModel(VaeBasicModel): """ This class implements the VAE multitasking model, using the VAE framework with the multiple downstrea...
8,142
44.238889
269
py
SubOmiEmbed
SubOmiEmbed-main/models/vae_basic_model.py
import torch from .basic_model import BasicModel from . import networks from . import losses class VaeBasicModel(BasicModel): """ This is the basic VAE model class, called by all other VAE son classes. """ def __init__(self, param): """ Initialize the VAE basic class. """ ...
12,659
48.84252
153
py
SubOmiEmbed
SubOmiEmbed-main/models/vae_multitask_gn_model.py
import torch import torch.nn as nn from .basic_model import BasicModel from . import networks from . import losses from torch.nn import functional as F from sklearn import metrics class VaeMultitaskGNModel(BasicModel): """ This class implements the VAE multitasking model with GradNorm, using the VAE framework...
15,071
45.091743
269
py
SubOmiEmbed
SubOmiEmbed-main/util/visualizer.py
import os import time import numpy as np import pandas as pd import sklearn as sk from sklearn.preprocessing import label_binarize from util import util from util import metrics from torch.utils.tensorboard import SummaryWriter class Visualizer: """ This class print/save logging information """ def _...
27,478
49.981447
370
py
SubOmiEmbed
SubOmiEmbed-main/util/util.py
""" Contain some simple helper functions """ import os import shutil import torch import random import numpy as np def mkdir(path): """ Create a empty directory in the disk if it didn't exist Parameters: path(str) -- a directory path we would like to create """ if not os.path.exists(path)...
1,204
20.517857
82
py
SubOmiEmbed
SubOmiEmbed-main/util/metrics.py
""" Contain some metrics """ import numpy as np # from lifelines.utils import concordance_index # from pysurvival.utils._metrics import _concordance_index from sksurv.metrics import concordance_index_censored from sksurv.metrics import integrated_brier_score def c_index(true_T, true_E, pred_risk, include_ties=True): ...
1,617
31.36
129
py
SubOmiEmbed
SubOmiEmbed-main/util/__init__.py
0
0
0
py
SubOmiEmbed
SubOmiEmbed-main/util/preprocess.py
""" Contain some omics data preprocess functions """ import pandas as pd def separate_B(B_df_single): """ Separate the DNA methylation dataframe into subsets according to their targeting chromosomes Parameters: B_df_single(DataFrame) -- a dataframe that contains the single DNA methylation matrix ...
967
30.225806
96
py
SubOmiEmbed
SubOmiEmbed-main/params/train_test_params.py
from .basic_params import BasicParams class TrainTestParams(BasicParams): """ This class is a son class of BasicParams. This class includes parameters for training & testing and parameters inherited from the father class. """ def initialize(self, parser): parser = BasicParams.initialize(se...
2,954
52.727273
130
py
SubOmiEmbed
SubOmiEmbed-main/params/basic_params.py
import time import argparse import torch import os import models from util import util class BasicParams: """ This class define the console parameters """ def __init__(self): """ Reset the class. Indicates the class hasn't been initialized """ self.initialized = False ...
12,834
54.323276
224
py
SubOmiEmbed
SubOmiEmbed-main/params/train_params.py
from .basic_params import BasicParams class TrainParams(BasicParams): """ This class is a son class of BasicParams. This class includes parameters for training and parameters inherited from the father class. """ def initialize(self, parser): parser = BasicParams.initialize(self, parser) ...
2,769
53.313725
130
py
SubOmiEmbed
SubOmiEmbed-main/params/test_params.py
from .basic_params import BasicParams class TestParams(BasicParams): """ This class is a son class of BasicParams. This class includes parameters for testing and parameters inherited from the father class. """ def initialize(self, parser): parser = BasicParams.initialize(self, parser) ...
727
32.090909
123
py
SubOmiEmbed
SubOmiEmbed-main/params/__init__.py
0
0
0
py
SubOmiEmbed
SubOmiEmbed-main/datasets/a_dataset.py
import os.path from datasets import load_file from datasets import get_survival_y_true from datasets.basic_dataset import BasicDataset import numpy as np import pandas as pd import torch class ADataset(BasicDataset): """ A dataset class for gene expression dataset. File should be prepared as '/path/to/dat...
10,137
50.461929
184
py
SubOmiEmbed
SubOmiEmbed-main/datasets/abc_dataset.py
import os.path from datasets import load_file from datasets import get_survival_y_true from datasets.basic_dataset import BasicDataset from util import preprocess import numpy as np import pandas as pd import torch class ABCDataset(BasicDataset): """ A dataset class for multi-omics dataset. For gene expre...
13,033
48.748092
152
py
SubOmiEmbed
SubOmiEmbed-main/datasets/basic_dataset.py
""" This module implements an abstract base class for datasets. Other datasets can be created from this base class. """ import torch.utils.data as data from abc import ABC, abstractmethod class BasicDataset(data.Dataset, ABC): """ This class is an abstract base class for datasets. To create a subclass, yo...
1,272
31.641026
116
py
SubOmiEmbed
SubOmiEmbed-main/datasets/ab_dataset.py
import os.path from datasets import load_file from datasets import get_survival_y_true from datasets.basic_dataset import BasicDataset from util import preprocess import numpy as np import pandas as pd import torch class ABDataset(BasicDataset): """ A dataset class for multi-omics dataset. For gene expres...
12,076
49.112033
152
py
SubOmiEmbed
SubOmiEmbed-main/datasets/c_dataset.py
import os.path from datasets import load_file from datasets import get_survival_y_true from datasets.basic_dataset import BasicDataset import numpy as np import pandas as pd import torch class CDataset(BasicDataset): """ A dataset class for miRNA expression dataset. File should be prepared as '/path/to/da...
10,372
50.098522
152
py
SubOmiEmbed
SubOmiEmbed-main/datasets/__init__.py
""" This package about data loading and data preprocessing """ import os import torch import importlib import numpy as np import pandas as pd from util import util from datasets.basic_dataset import BasicDataset from datasets.dataloader_prefetch import DataLoaderPrefetch from torch.utils.data import Subset from sklearn...
8,346
34.219409
177
py
SubOmiEmbed
SubOmiEmbed-main/datasets/dataloader_prefetch.py
from torch.utils.data import DataLoader from prefetch_generator import BackgroundGenerator class DataLoaderPrefetch(DataLoader): def __iter__(self): return BackgroundGenerator(super().__iter__())
210
25.375
54
py
SubOmiEmbed
SubOmiEmbed-main/datasets/b_dataset.py
import os.path from datasets import load_file from datasets import get_survival_y_true from datasets.basic_dataset import BasicDataset from util import preprocess import numpy as np import pandas as pd import torch class BDataset(BasicDataset): """ A dataset class for methylation dataset. DNA methylation ...
11,172
49.556561
152
py
mixstyle-release
mixstyle-release-master/reid/default_config.py
from yacs.config import CfgNode as CN def get_default_config(): cfg = CN() # model cfg.model = CN() cfg.model.name = 'resnet50' cfg.model.pretrained = True # automatically load pretrained model weights if available cfg.model.load_weights = '' # path to model weights cfg.model.resume = '' ...
8,128
37.709524
104
py
mixstyle-release
mixstyle-release-master/reid/main.py
import sys import time import os.path as osp import argparse import torch import torch.nn as nn import torchreid from torchreid.utils import ( Logger, check_isfile, set_random_seed, collect_env_info, resume_from_checkpoint, load_pretrained_weights, compute_model_complexity ) from default_config import ( i...
7,293
32.925581
159
py
mixstyle-release
mixstyle-release-master/reid/models/osnet_db.py
from __future__ import division, absolute_import import warnings import torch from torch import nn from torch.nn import functional as F from .dropblock import DropBlock2D, LinearScheduler __all__ = [ 'osnet_x1_0', 'osnet_x0_75', 'osnet_x0_5', 'osnet_x0_25', 'osnet_ibn_x1_0' ] pretrained_urls = { 'osnet_x1_0'...
18,266
27.676609
108
py
mixstyle-release
mixstyle-release-master/reid/models/resnet_db.py
""" Code source: https://github.com/pytorch/vision """ from __future__ import division, absolute_import import torch.utils.model_zoo as model_zoo from torch import nn from .dropblock import DropBlock2D, LinearScheduler __all__ = [ 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'resnext50_32x4d'...
16,436
27.685864
106
py
mixstyle-release
mixstyle-release-master/reid/models/osnet_ms.py
from __future__ import division, absolute_import import warnings import torch from torch import nn from torch.nn import functional as F from .mixstyle import MixStyle __all__ = [ 'osnet_x1_0', 'osnet_x0_75', 'osnet_x0_5', 'osnet_x0_25', 'osnet_ibn_x1_0' ] pretrained_urls = { 'osnet_x1_0': 'https://drive....
19,075
27.5142
108
py
mixstyle-release
mixstyle-release-master/reid/models/resnet_ms.py
""" Code source: https://github.com/pytorch/vision """ from __future__ import division, absolute_import import torch.utils.model_zoo as model_zoo from torch import nn from .mixstyle import MixStyle __all__ = [ 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',...
19,818
27.516547
106
py
mixstyle-release
mixstyle-release-master/reid/models/mixstyle.py
import random from contextlib import contextmanager import torch import torch.nn as nn def deactivate_mixstyle(m): if type(m) == MixStyle: m.set_activation_status(False) def activate_mixstyle(m): if type(m) == MixStyle: m.set_activation_status(True) def random_mixstyle(m): if type(m) =...
3,127
24.430894
90
py
mixstyle-release
mixstyle-release-master/reid/models/osnet_ms2.py
from __future__ import division, absolute_import import warnings import torch from torch import nn from torch.nn import functional as F from .mixstyle import MixStyle __all__ = [ 'osnet_x1_0', 'osnet_x0_75', 'osnet_x0_5', 'osnet_x0_25', 'osnet_ibn_x1_0' ] pretrained_urls = { 'osnet_x1_0': 'https://drive....
18,135
27.56063
108
py
mixstyle-release
mixstyle-release-master/reid/models/resnet_ms2.py
""" Code source: https://github.com/pytorch/vision """ from __future__ import division, absolute_import import torch.utils.model_zoo as model_zoo from torch import nn from .mixstyle import MixStyle __all__ = [ 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',...
16,298
27.898936
106
py
mixstyle-release
mixstyle-release-master/reid/models/__init__.py
0
0
0
py
mixstyle-release
mixstyle-release-master/reid/models/dropblock/dropblock.py
import torch import torch.nn.functional as F from torch import nn class DropBlock2D(nn.Module): r"""Randomly zeroes 2D spatial blocks of the input tensor. As described in the paper `DropBlock: A regularization method for convolutional networks`_ , dropping whole blocks of feature map allows to remove...
4,440
29.210884
98
py
mixstyle-release
mixstyle-release-master/reid/models/dropblock/scheduler.py
import numpy as np from torch import nn class LinearScheduler(nn.Module): def __init__(self, dropblock, start_value, stop_value, nr_steps): super(LinearScheduler, self).__init__() self.dropblock = dropblock self.i = 0 self.drop_values = np.linspace(start=start_value, stop=stop_valu...
546
26.35
88
py
mixstyle-release
mixstyle-release-master/reid/models/dropblock/__init__.py
from .dropblock import DropBlock2D, DropBlock3D from .scheduler import LinearScheduler __all__ = ['DropBlock2D', 'DropBlock3D', 'LinearScheduler']
148
28.8
59
py
mixstyle-release
mixstyle-release-master/imcls/vis.py
import argparse import torch import os.path as osp import numpy as np from sklearn.decomposition import PCA from sklearn.manifold import TSNE from matplotlib import pyplot as plt def normalize(feature): norm = np.sqrt((feature**2).sum(1, keepdims=True)) return feature / (norm + 1e-12) def main(): parser...
3,338
26.368852
87
py
mixstyle-release
mixstyle-release-master/imcls/parse_test_res.py
""" Goal --- 1. Read test results from log.txt files 2. Compute mean and std across different folders (seeds) Usage --- Assume the output files are saved under output/my_experiment, which contains results of different seeds, e.g., my_experiment/ seed1/ log.txt seed2/ log.txt seed3/ ...
4,752
24.148148
77
py
mixstyle-release
mixstyle-release-master/imcls/train.py
import argparse import copy import torch from dassl.utils import setup_logger, set_random_seed, collect_env_info from dassl.config import get_cfg_default from dassl.engine import build_trainer # custom from yacs.config import CfgNode as CN import datasets.ssdg_pacs import datasets.ssdg_officehome import datasets.msda...
5,312
26.386598
80
py
mixstyle-release
mixstyle-release-master/imcls/datasets/ssdg_officehome.py
import os.path as osp import glob import random from dassl.utils import listdir_nohidden from dassl.data.datasets import DATASET_REGISTRY, Datum, DatasetBase from dassl.utils import mkdir_if_missing from .ssdg_pacs import SSDGPACS @DATASET_REGISTRY.register() class SSDGOfficeHome(DatasetBase): """Office-Home. ...
4,583
36.884298
106
py
mixstyle-release
mixstyle-release-master/imcls/datasets/ssdg_pacs.py
import os.path as osp import random from collections import defaultdict from dassl.data.datasets import DATASET_REGISTRY, Datum, DatasetBase from dassl.utils import mkdir_if_missing, read_json, write_json @DATASET_REGISTRY.register() class SSDGPACS(DatasetBase): """PACS. Statistics: - 4 domains: Pho...
7,401
36.01
106
py
mixstyle-release
mixstyle-release-master/imcls/datasets/__init__.py
0
0
0
py
mixstyle-release
mixstyle-release-master/imcls/datasets/msda_pacs.py
import os.path as osp from dassl.data.datasets import DATASET_REGISTRY, Datum, DatasetBase @DATASET_REGISTRY.register() class MSDAPACS(DatasetBase): """PACS. Modified for multi-source domain adaptation. Statistics: - 4 domains: Photo (1,670), Art (2,048), Cartoon (2,344), Sketch (3,929)...
3,145
33.955556
81
py
mixstyle-release
mixstyle-release-master/imcls/trainers/semimixstyle.py
import torch from torch.nn import functional as F from dassl.data import DataManager from dassl.engine import TRAINER_REGISTRY, TrainerXU from dassl.metrics import compute_accuracy from dassl.data.transforms import build_transform from dassl.modeling.ops import deactivate_mixstyle, run_with_mixstyle @TRAINER_REGISTR...
4,835
35.360902
79
py
mixstyle-release
mixstyle-release-master/imcls/trainers/vanilla2.py
import torch from torch.nn import functional as F from dassl.engine import TRAINER_REGISTRY, TrainerX from dassl.metrics import compute_accuracy from dassl.modeling.ops import random_mixstyle, crossdomain_mixstyle @TRAINER_REGISTRY.register() class Vanilla2(TrainerX): """Vanilla baseline. Slightly modified ...
3,011
29.424242
77
py
mixstyle-release
mixstyle-release-master/imcls/trainers/__init__.py
0
0
0
py
mixstyle-release
mixstyle-release-master/rl/setup.py
from setuptools import setup, find_packages setup( name='coinrun', packages=find_packages(), version='0.0.1', )
125
14.75
43
py
mixstyle-release
mixstyle-release-master/rl/plots.py
import tensorflow as tf import os import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set() sns.set_style("ticks") params = {'legend.fontsize': 10, 'legend.handlelength': 2, 'font.size': 10} plt.rcParams.update(params) def movingaverage (values, window): weights = np.repeat(1.0...
8,656
39.265116
124
py
mixstyle-release
mixstyle-release-master/rl/create_gif.py
import imageio import os images = [] # for filename in os.listdir(modified_path): filenames = [] for filename in os.listdir('./images'): if filename.startswith('img_'): filenames.append(filename) sorted_files = [None] * len(filenames) for filename in filenames: nr = int(filename[4:-4]) sorted_fi...
495
20.565217
46
py
mixstyle-release
mixstyle-release-master/rl/create_saliency.py
""" Load an agent trained with train_agent.py and """ import time import tensorflow as tf import numpy as np from coinrun import setup_utils import coinrun.main_utils as utils from coinrun.config import Config from coinrun import config from coinrun import policies, wrappers import imageio import sys # Import for s...
6,228
30.301508
145
py
mixstyle-release
mixstyle-release-master/rl/coinrun/tb_utils.py
import tensorflow as tf from mpi4py import MPI from coinrun.config import Config import numpy as np def clean_tb_dir(): comm = MPI.COMM_WORLD rank = comm.Get_rank() if rank == 0: if tf.gfile.Exists(Config.TB_DIR): tf.gfile.DeleteRecursively(Config.TB_DIR) tf.gfile.MakeDirs(Con...
2,740
30.147727
108
py
mixstyle-release
mixstyle-release-master/rl/coinrun/train_agent.py
""" Train an agent using a PPO2 based on OpenAI Baselines. """ import time from mpi4py import MPI import tensorflow as tf from baselines.common import set_global_seeds import coinrun.main_utils as utils from coinrun import setup_utils, policies, wrappers, ppo2 from coinrun.config import Config def main(): args = ...
1,651
27
66
py
mixstyle-release
mixstyle-release-master/rl/coinrun/test_coinrun.py
from coinrun import random_agent def test_coinrun(): random_agent.random_agent(num_envs=16, max_steps=100) if __name__ == '__main__': test_coinrun()
159
19
57
py
mixstyle-release
mixstyle-release-master/rl/coinrun/coinrunenv.py
""" Python interface to the CoinRun shared library using ctypes. On import, this will attempt to build the shared library. """ import os import atexit import random import sys from ctypes import c_int, c_char_p, c_float, c_bool import gym import gym.spaces import numpy as np import numpy.ctypeslib as npct from basel...
6,996
31.09633
205
py
mixstyle-release
mixstyle-release-master/rl/coinrun/ppo2.py
""" This is a copy of PPO from openai/baselines (https://github.com/openai/baselines/blob/52255beda5f5c8760b0ae1f676aa656bb1a61f80/baselines/ppo2/ppo2.py) with some minor changes. """ import time import datetime import joblib import numpy as np import tensorflow as tf from collections import deque from mpi4py import ...
17,289
37.59375
175
py
mixstyle-release
mixstyle-release-master/rl/coinrun/setup_utils.py
from coinrun.config import Config import os import joblib def load_for_setup_if_necessary(): print("Restoring from ID: {}".format(Config.RESTORE_ID)) restore_file(Config.RESTORE_ID) def restore_file(restore_id, load_key='default'): if restore_id is not None: load_file = Config.get_load_filename(r...
1,466
30.212766
101
py
mixstyle-release
mixstyle-release-master/rl/coinrun/utils.py
import os import sys import time import os.path as osp import errno def mkdir_if_missing(dirname): """Create dirname if it is missing.""" if not osp.exists(dirname): try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise class...
2,424
22.095238
90
py
mixstyle-release
mixstyle-release-master/rl/coinrun/main_utils.py
import tensorflow as tf import os import joblib import numpy as np from mpi4py import MPI from baselines.common.vec_env.vec_frame_stack import VecFrameStack from coinrun.config import Config from coinrun import setup_utils, wrappers import platform def make_general_env(num_env, seed=0, use_sub_proc=True): from ...
5,094
25.957672
89
py
mixstyle-release
mixstyle-release-master/rl/coinrun/random_agent.py
import numpy as np from coinrun import setup_utils, make def random_agent(num_envs=1, max_steps=100000): setup_utils.setup_and_load(use_cmd_line_args=False) env = make('standard', num_envs=num_envs) for step in range(max_steps): acts = np.array([env.action_space.sample() for _ in range(env.num_env...
482
29.1875
81
py
mixstyle-release
mixstyle-release-master/rl/coinrun/wrappers.py
import gym import numpy as np class EpsilonGreedyWrapper(gym.Wrapper): """ Wrapper to perform a random action each step instead of the requested action, with the provided probability. """ def __init__(self, env, prob=0.05): gym.Wrapper.__init__(self, env) self.prob = prob s...
3,145
30.148515
94
py
mixstyle-release
mixstyle-release-master/rl/coinrun/config.py
from mpi4py import MPI import argparse import os class ConfigSingle(object): """ A global config object that can be initialized from command line arguments or keyword arguments. """ def __init__(self): self.WORKDIR = './saved_models' self.TB_DIR = './tb_log' if not os.path.e...
12,414
35.514706
129
py
mixstyle-release
mixstyle-release-master/rl/coinrun/policies.py
import sys import numpy as np import tensorflow as tf from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch, lstm from baselines.common.distributions import make_pdtype, _matching_fc from baselines.common.input import observation_input ds = tf.contrib.distributions from coinrun.config import...
10,335
39.375
150
py
mixstyle-release
mixstyle-release-master/rl/coinrun/interactive.py
""" Run a CoinRun environment in a window where you can interact with it using the keyboard """ from coinrun.coinrunenv import lib from coinrun import setup_utils def main(): setup_utils.setup_and_load(paint_vel_info=0) print("""Control with arrow keys, F1, F2 -- switch resolution, F5, F6, F7, F8 -- zoom, F9...
457
20.809524
87
py
mixstyle-release
mixstyle-release-master/rl/coinrun/__init__.py
from .coinrunenv import init_args_and_threads from .coinrunenv import make __all__ = [ 'init_args_and_threads', 'make' ]
134
15.875
45
py
mixstyle-release
mixstyle-release-master/rl/coinrun/enjoy.py
""" Load an agent trained with train_agent.py and """ import time import tensorflow as tf import numpy as np import os from coinrun import setup_utils import coinrun.main_utils as utils from coinrun.config import Config from coinrun import policies, wrappers mpi_print = utils.mpi_print def create_act_model(sess, e...
3,856
24.543046
99
py
mixstyle-release
mixstyle-release-master/rl/coinrun/OldPlots.py
# plotname = "VIB_repeats_{}".format(ending) # experiments = { # '0424_vibnn12e4_l2w_uda_{}': "L2W + VIB-SNI (1e-4) + UDA", # '0424_vibnn12e4_{}': "VIB-SNI (1e-4)", # '0501_0_vibnn12e4_uda_{}': "VIB-SNI (1e-4) + UDA", # '0501_1_vibnn12e4_uda_{}': "VIB-SNI (1e-4) + UDA", # '0501_0_vibnn12e4_l2w_uda_{...
2,420
31.28
66
py
scipy
scipy-main/setup.py
#!/usr/bin/env python """SciPy: Scientific Library for Python SciPy (pronounced "Sigh Pie") is open-source software for mathematics, science, and engineering. The SciPy library depends on NumPy, which provides convenient and fast N-dimensional array manipulation. The SciPy library is built to work with NumPy arrays, a...
20,342
37.166979
109
py
scipy
scipy-main/dev.py
#! /usr/bin/env python3 ''' Developer CLI: building (meson), tests, benchmark, etc. This file contains tasks definitions for doit (https://pydoit.org). And also a CLI interface using click (https://click.palletsprojects.com). The CLI is ideal for project contributors while, doit interface is better suited for author...
50,071
33.085773
87
py
scipy
scipy-main/tools/openblas_support.py
import glob import os import platform import sysconfig import sys import shutil import tarfile import textwrap import time import zipfile from tempfile import mkstemp, gettempdir from urllib.request import urlopen, Request from urllib.error import HTTPError OPENBLAS_V = '0.3.21.dev' OPENBLAS_LONG = 'v0.3.20-571-g3dec...
12,716
32.465789
81
py
scipy
scipy-main/tools/check_test_name.py
#!/usr/bin/env python """ MIT License Copyright (c) 2020 Marco Gorelli Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, ...
5,952
34.017647
78
py
scipy
scipy-main/tools/gh_lists.py
#!/usr/bin/env python3 # -*- encoding:utf-8 -*- """ gh_lists.py MILESTONE Functions for Github API requests. """ import os import re import sys import json import collections import argparse import datetime import time from urllib.request import urlopen, Request, HTTPError Issue = collections.namedtuple('Issue', ('...
7,508
30.953191
113
py
scipy
scipy-main/tools/unicode-check.py
#!/usr/bin/env python import re from itertools import chain from glob import iglob import sys import argparse # The set of Unicode code points greater than 127 that we # allow in the source code. latin1_letters = set(chr(cp) for cp in range(192, 256)) box_drawing_chars = set(chr(cp) for cp in range(0x2500, 0x2580)) ...
3,136
36.795181
79
py
scipy
scipy-main/tools/refguide_summaries.py
#!/usr/bin/env python """Generate function summaries for the refguide. For example, if the __init__ file of a submodule contains: .. autosummary:: :toctree: generated/ foo foobar Then it will modify the __init__ file to contain (*) .. autosummary:: :toctree: generated/ foo -- First line of the do...
3,456
30.144144
74
py
scipy
scipy-main/tools/check_installation.py
""" Script for checking if all the test files are installed after building. Examples:: $ python check_installation.py install_directory_name install_directory_name: the relative path to the directory where SciPy is installed after building and running `meson install`. Notes =====...
3,388
29.809091
80
py
scipy
scipy-main/tools/ninjatracing.py
# Copyright 2018 Nico Weber # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
7,126
36.314136
81
py
scipy
scipy-main/tools/cythonize.py
"""cythonize Cythonize pyx files into C files as needed. Usage: cythonize [root_dir] Default [root_dir] is 'scipy'. The number of parallel Cython processes is controlled by the environment variable SCIPY_NUM_CYTHONIZE_JOBS. If not set, determined from the number of CPUs. Checks pyx files to see if they have been c...
11,648
31.90678
79
py
scipy
scipy-main/tools/authors.py
#!/usr/bin/env python # -*- encoding:utf-8 -*- """ List the authors who contributed within a given revision interval:: python tools/authors.py REV1..REV2 `REVx` being a commit hash. To change the name mapping, edit .mailmap on the top-level of the repository. """ # Author: Pauli Virtanen <pav@iki.fi>. This scri...
7,474
30.540084
215
py
scipy
scipy-main/tools/refguide_check.py
#!/usr/bin/env python3 """ refguide_check.py [OPTIONS] [-- ARGS] Check for a Scipy submodule whether the objects in its __all__ dict correspond to the objects included in the reference guide. Example of usage:: $ python3 refguide_check.py optimize Note that this is a helper script to be able to check if things ...
35,211
32.187559
101
py
scipy
scipy-main/tools/download-wheels.py
#!/usr/bin/env python """ Download SciPy wheels from Anaconda staging area. """ import os import re import shutil import argparse import urllib import urllib.request import urllib3 from bs4 import BeautifulSoup __version__ = '0.1' # Edit these for other projects. STAGING_URL = 'https://anaconda.org/multibuild-wheel...
2,978
27.92233
77
py
scipy
scipy-main/tools/generate_f2pymod.py
""" Process f2py template files (`filename.pyf.src` -> `filename.pyf`) Usage: python generate_pyf.py filename.pyf.src -o filename.pyf """ import os import sys import re import subprocess import argparse # START OF CODE VENDORED FROM `numpy.distutils.from_template` ###################################################...
9,372
30.989761
94
py
scipy
scipy-main/tools/write_release_and_log.py
""" Standalone script for writing release doc and logs:: python tools/write_release_and_log.py <LOG_START> <LOG_END> Example:: python tools/write_release_and_log.py v1.7.0 v1.8.0 Needs to be run from the root of the repository. """ import os import sys import subprocess from hashlib import md5 from hashli...
4,045
25.103226
79
py
scipy
scipy-main/tools/lint.py
#!/usr/bin/env python import os import sys import subprocess from argparse import ArgumentParser CONFIG = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'lint.toml', ) def rev_list(branch, num_commits): """List commits in reverse chronological order. Only the first `num_commits` are show...
3,870
26.848921
87
py
scipy
scipy-main/tools/pre-commit-hook.py
#!/usr/bin/env python # # Pre-commit linting hook. # # Install from root of repository with: # # cp tools/pre-commit-hook.py .git/hooks/pre-commit import subprocess import sys import os # Run lint.py from the scipy source tree linters = [ '../../tools/lint.py', 'tools/lint.py', 'lint.py' # in case pre...
2,915
31.764045
82
py
scipy
scipy-main/tools/version_utils.py
import os import subprocess import argparse MAJOR = 1 MINOR = 12 MICRO = 0 ISRELEASED = False IS_RELEASE_BRANCH = False VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) def get_version_info(source_root): # Adding the git rev number needs to be done inside # write_version_py(), otherwise the import of scipy.vers...
4,136
33.475
83
py