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 |
|---|---|---|---|---|---|---|
FastJTNNpy3 | FastJTNNpy3-master/Old/bo/sparse_gp_theano_internal.py |
import theano
import theano.tensor as T
import numpy as np
from gauss import *
from theano.tensor.slinalg import Cholesky as MatrixChol
import math
def n_pdf(x):
return 1.0 / T.sqrt(2 * math.pi) * T.exp(-0.5 * x**2)
def log_n_pdf(x):
return -0.5 * T.log(2 * math.pi) - 0.5 * x**2
def n_cdf(x):
retur... | 15,501 | 44.863905 | 144 | py |
FastJTNNpy3 | FastJTNNpy3-master/Old/bo/sparse_gp.py | ##
# This class represents a node within the network
#
from __future__ import print_function
import theano
import theano.tensor as T
from sparse_gp_theano_internal import *
import scipy.stats as sps
import scipy.optimize as spo
import numpy as np
import sys
import time
def casting(x):
return np.array(x).ast... | 14,236 | 42.405488 | 140 | py |
FastJTNNpy3 | FastJTNNpy3-master/Old/bo/sascorer.py | #
# calculation of synthetic accessibility score as described in:
#
# Estimation of Synthetic Accessibility Score of Drug-like Molecules based on Molecular Complexity and Fragment Contributions
# Peter Ertl and Ansgar Schuffenhauer
# Journal of Cheminformatics 1:8 (2009)
# http://www.jcheminf.com/content/1/1/8
#
# seve... | 5,566 | 33.153374 | 125 | py |
FastJTNNpy3 | FastJTNNpy3-master/Old/bo/run_bo.py | import pickle
import gzip
from sparse_gp import SparseGP
import scipy.stats as sps
import numpy as np
import os.path
import rdkit
from rdkit.Chem import MolFromSmiles, MolToSmiles
from rdkit.Chem import Descriptors
import torch
import torch.nn as nn
from jtnn import create_var, JTNNVAE, Vocab
from optparse import Op... | 5,700 | 35.082278 | 151 | py |
FastJTNNpy3 | FastJTNNpy3-master/fast_molvae/sample.py | import sys
sys.path.append('../')
import torch
import torch.nn as nn
import math, random, sys
import argparse
from fast_jtnn import *
import rdkit
def load_model(vocab, model_path, hidden_size=450, latent_size=56, depthT=20, depthG=3):
vocab = [x.strip("\r\n ") for x in open(vocab)]
vocab = Vocab(vocab)
... | 1,836 | 33.660377 | 133 | py |
FastJTNNpy3 | FastJTNNpy3-master/fast_molvae/preprocess.py | import sys
sys.path.append('../')
import torch
import torch.nn as nn
from multiprocessing import Pool
import numpy as np
import os
from tqdm import tqdm
import math, random, sys
from optparse import OptionParser
import pickle
from fast_jtnn import *
import rdkit
def tensorize(smiles, assm=True):
mol_tree = MolTr... | 2,146 | 27.25 | 85 | py |
FastJTNNpy3 | FastJTNNpy3-master/fast_molvae/vae_train.py | import sys
sys.path.append('../')
import torch
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from torch.utils.data import DataLoader
from torch.autograd import Variable
import math, random, sys
import numpy as np
import argparse
from collections import deque
import p... | 5,667 | 33.351515 | 214 | py |
teachinghubs | teachinghubs-master/mp248hub/ipython_config.py | c = get_config()
#set matplotlib backend to inline
#c.InteractiveShellApp.matplotlib = None
#c.InteractiveShellApp.gui = None
#c.InteractiveShellApp.pylab = "inline"
#c.InteractiveShellApp.exec_lines = [
# "%pylab inline\n"
#]
# "display(HTML(\'<style>.container { width:80% !important; }</style>\'))
#"%nbagg\n",
#]... | 695 | 32.142857 | 76 | py |
ctcdecode | ctcdecode-master/setup.py | #!/usr/bin/env python
import glob
import multiprocessing.pool
import os
import tarfile
import urllib.request
import warnings
from setuptools import distutils, find_packages, setup
from torch.utils.cpp_extension import BuildExtension, CppExtension, include_paths
def download_extract(url, dl_path):
if not os.path.... | 4,428 | 29.756944 | 117 | py |
ctcdecode | ctcdecode-master/tests/test_decode.py | """Test decoders."""
from __future__ import absolute_import, division, print_function
import os
import unittest
import ctcdecode
import torch
class TestDecoders(unittest.TestCase):
def setUp(self):
self.vocab_list = ["'", " ", "a", "b", "c", "d", "_"]
self.beam_size = 20
self.probs_seq1 ... | 9,962 | 45.125 | 113 | py |
ctcdecode | ctcdecode-master/ctcdecode/__init__.py | import torch
from ._ext import ctc_decode
class CTCBeamDecoder(object):
"""
PyTorch wrapper for DeepSpeech PaddlePaddle Beam Search Decoder.
Args:
labels (list): The tokens/vocab used to train your model.
They should be in the same order as they are in your model's outputs... | 11,957 | 42.802198 | 121 | py |
stackprof | stackprof-master/bin/stackprof-gprof2dot.py | #!/usr/bin/env ruby
exec(File.expand_path("../../vendor/gprof2dot/gprof2dot.py", __FILE__), *ARGV)
| 99 | 32.333333 | 78 | py |
stackprof | stackprof-master/vendor/gprof2dot/hotshotmain.py | #!/usr/bin/env python
#
# Copyright 2007 Jose Fonseca
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This ... | 2,263 | 30.887324 | 91 | py |
stackprof | stackprof-master/vendor/gprof2dot/gprof2dot.py | #!/usr/bin/env python
#
# Copyright 2008-2009 Jose Fonseca
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | 106,281 | 31.531987 | 155 | py |
torchqg | torchqg-master/main.py | import sys
import math
import torch
import torch.nn as nn
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from qg import to_spectral, to_physical, QgModel
from sgs import MLdiv, Constant
import workflow
plt.rcParams.update({'mathtext.fontset':'cm'})
# A framework for the evaluation of turbule... | 2,721 | 21.130081 | 103 | py |
torchqg | torchqg-master/sgs.py | import math
import torch
import qg
class Constant:
def __init__(self, c=0.0):
self.c = c
def predict(self, m, it, sol, grid):
div = torch.full_like(sol, self.c)
return div
class MLdiv:
def __init__(self, model):
self.model = model
self.model.eval()
#print(self.model)
def predict(sel... | 626 | 18 | 75 | py |
torchqg | torchqg-master/learn.py | import os
import torch
import numpy as np
import qg
# Useful for a posteriori learning.
class DynamicalDataset(torch.utils.data.Dataset):
def __init__(self, inputs, labels, steps, iters, dt, t0):
self.inputs = inputs
self.labels = labels
self.iters = iters
self.dt = dt
self.t0 = t0
self.ada... | 4,689 | 26.588235 | 124 | py |
torchqg | torchqg-master/qg.py | import math
import tqdm
import h5py
import torch
import torch.fft
import matplotlib
import matplotlib.pyplot as plt
from src.grid import TwoGrid
from src.timestepper import ForwardEuler, RungeKutta2, RungeKutta4
from src.pde import Pde, Eq
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print... | 7,785 | 23.561514 | 158 | py |
torchqg | torchqg-master/workflow.py | import math
import os
import tqdm
import torch
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import qg
plt.rcParams.update({'mathtext.fontset':'cm'})
plt.rcParams.update({'xtick.minor.visible':True})
plt.rcParams.update({'ytick.minor.visible':True})
def workflow(
dir,... | 6,958 | 33.112745 | 151 | py |
torchqg | torchqg-master/src/timestepper.py | import math
import torch
class ForwardEuler:
def __init__(self, eq):
self.n = 1
self.S = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device)
def zero_grad(self):
self.S.detach_()
def step(self, m, sol, cur, eq, grid):
dt = cur.dt
t = cur.t
eq.nonlinear_term(0... | 2,675 | 28.406593 | 93 | py |
torchqg | torchqg-master/src/grid.py | import math
import torch
import numpy as np
class TwoGrid:
def __init__(self, device, Nx, Ny, Lx, Ly, dealias=1/3):
self.device = device
self.Nx = Nx
self.Ny = Ny
self.Lx = Lx
self.Ly = Ly
self.size = Nx*Ny
self.dx = Lx/Nx
self.dy = Ly/Ny
self.x = torch.arange(start=-Lx/2, end=... | 3,284 | 28.330357 | 110 | py |
torchqg | torchqg-master/src/pde.py | import math
import torch
class Cursor:
def __init__(self, dt, t0):
self.dt = dt
self.t = t0
self.n = 0
def step(self):
self.t += self.dt
self.n += 1
class Eq:
def __init__(self, grid, linear_term, nonlinear_term):
self.device = grid.device
self.grid = grid
self.linear_term = l... | 771 | 19.864865 | 94 | py |
BadEncoder | BadEncoder-main/pretraining_encoder.py | import os
import argparse
import numpy as np
from PIL import Image
from torch.utils.data import DataLoader
from tqdm import tqdm
import json
import math
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from models import get_encoder_architecture
from datasets import ... | 7,278 | 39.664804 | 226 | py |
BadEncoder | BadEncoder-main/training_downstream_classifier.py | import os
import argparse
import random
import torchvision
import numpy as np
from functools import partial
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
from datasets import get_dataset_eval... | 5,607 | 49.522523 | 173 | py |
BadEncoder | BadEncoder-main/zero_shot.py | import os
import random
import argparse
import clip.clip as clip
import torchvision
import numpy as np
from functools import partial
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functio... | 6,018 | 41.687943 | 172 | py |
BadEncoder | BadEncoder-main/badencoder.py | import os
import argparse
import random
import torchvision
import numpy as np
from torch.utils.data import DataLoader
from torchvision import transforms
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
from models import get_encoder_architecture_usage
from datasets import get_s... | 10,574 | 52.409091 | 300 | py |
BadEncoder | BadEncoder-main/evaluation/nn_classifier.py | import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import TensorDataset, DataLoader
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size_list, num_classes... | 3,255 | 32.56701 | 121 | py |
BadEncoder | BadEncoder-main/evaluation/__init__.py | import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
from .nn_classifier import NeuralNet, create_torch_dataloader, net_train, net_test
from .nn_classifier import predict_feature
# test using a knn monitor
def test(net, memory_data_loader, test_data_clean_loader... | 3,459 | 45.756757 | 130 | py |
BadEncoder | BadEncoder-main/clip/simple_tokenizer.py | import gzip
import html
import os
from functools import lru_cache
import ftfy
import regex as re
@lru_cache()
def default_bpe():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
@lru_cache()
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a cor... | 4,629 | 33.552239 | 144 | py |
BadEncoder | BadEncoder-main/clip/clip.py | import hashlib
import os
import urllib
import warnings
from typing import Union, List
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokenizer import SimpleTokenizer as _Tokenizer... | 5,310 | 36.666667 | 142 | py |
BadEncoder | BadEncoder-main/clip/model.py | from collections import OrderedDict
from typing import Tuple, Union
import torch
import torch.nn.functional as F
from torch import nn
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have stride 1. an avgpool is... | 15,887 | 37.845966 | 178 | py |
BadEncoder | BadEncoder-main/models/clip_model.py | from collections import OrderedDict
from typing import Tuple, Union
import torch
import torch.nn.functional as F
from torch import nn
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have stride 1. an avgpool is ... | 6,923 | 35.251309 | 113 | py |
BadEncoder | BadEncoder-main/models/imagenet_model.py | from collections import OrderedDict
from typing import Tuple, Union
import torch
import torch.nn.functional as F
from torch import nn
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
... | 8,218 | 34.734783 | 106 | py |
BadEncoder | BadEncoder-main/models/__init__.py | from .simclr_model import SimCLR
from .clip_model import CLIP
from .imagenet_model import ImageNetResNet
def get_encoder_architecture(args):
if args.pretraining_dataset == 'cifar10':
return SimCLR()
elif args.pretraining_dataset == 'stl10':
return SimCLR()
else:
raise ValueError('U... | 871 | 32.538462 | 92 | py |
BadEncoder | BadEncoder-main/models/simclr_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import resnet18, resnet34, resnet50
class SimCLRBase(nn.Module):
def __init__(self, arch='resnet18'):
super(SimCLRBase, self).__init__()
self.f = []
if arch == 'resnet18':
model_... | 1,984 | 33.824561 | 162 | py |
BadEncoder | BadEncoder-main/scripts/run_imagenet_training_downstream_classifier.py | import os
if not os.path.exists('./log/imagenet/'):
os.makedirs('./log/imagenet/')
def evaluate_imagenet(gpu, encoder_usage_info, downstream_dataset, encoder, reference_label, trigger, reference, key='clean'):
cmd = f"nohup python3 -u training_downstream_classifier.py \
--encoder_usage_info {encod... | 1,673 | 61 | 174 | py |
BadEncoder | BadEncoder-main/scripts/run_clip_training_downstream_classifier_zero_shot.py | import os
if not os.path.exists('./log/clip/'):
os.makedirs('./log/clip/')
def eval_zero_shot(gpu, encoder_usage_info, shadow_dataset, downstream_dataset, reference_file, reference_label, trigger_file):
cmd = f"nohup python3 -u zero_shot.py \
--encoder_usage_info {encoder_usage_info} \
--shadow_datas... | 1,990 | 44.25 | 133 | py |
BadEncoder | BadEncoder-main/scripts/run_pretraining_encoder.py | import os
cifar10_results_dir = './output/cifar10/clean_encoder/'
stl10_results_dir = './output/stl10/clean_encoder/'
if not os.path.exists('./log/clean_encoder'):
os.makedirs('./log/clean_encoder')
if not os.path.exists(cifar10_results_dir):
os.makedirs(cifar10_results_dir)
if not os.path.exists(stl10_result... | 707 | 38.333333 | 158 | py |
BadEncoder | BadEncoder-main/scripts/run_cifar10_training_downstream_classifier.py | import os
if not os.path.exists('./log/cifar10'):
os.makedirs('./log/cifar10')
def run_eval(gpu, encoder_usage_info, downstream_dataset, encoder, reference_label, trigger, reference_file, key='clean'):
cmd = f"nohup python3 -u training_downstream_classifier.py \
--dataset {downstream_dataset} \
... | 1,663 | 58.428571 | 169 | py |
BadEncoder | BadEncoder-main/scripts/run_clip_training_downstream_classifier_multi_shot.py | import os
if not os.path.exists('./log/clip/'):
os.makedirs('./log/clip/')
def evaluate_clip_finetune(gpu, encoder_usage_info, downstream_dataset, encoder, reference_label, trigger, reference):
cmd = f"nohup python3 -u training_downstream_classifier.py \
--encoder_usage_info {encoder_usage_info} \... | 2,091 | 48.809524 | 168 | py |
BadEncoder | BadEncoder-main/scripts/run_badencoder.py | import os
if not os.path.exists('./log/bad_encoder'):
os.makedirs('./log/bad_encoder')
def run_finetune(gpu, encoder_usage_info, shadow_dataset, downstream_dataset, trigger, reference, clean_encoder='model_1000.pth'):
save_path = f'./output/{encoder_usage_info}/{downstream_dataset}_backdoored_encoder'
if... | 1,210 | 39.366667 | 130 | py |
BadEncoder | BadEncoder-main/datasets/svhn_dataset.py | from torchvision import transforms
from .backdoor_dataset import CIFAR10Mem, CIFAR10Pair, BadEncoderTestBackdoor, ReferenceImg
import numpy as np
test_transform_cifar10 = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])])
test_transform_stl10... | 2,275 | 43.627451 | 189 | py |
BadEncoder | BadEncoder-main/datasets/cifar10_dataset.py | from torchvision import transforms
from .backdoor_dataset import CIFAR10Mem, CIFAR10Pair, BadEncoderTestBackdoor, BadEncoderDataset, ReferenceImg
import numpy as np
train_transform = transforms.Compose([
transforms.RandomResizedCrop(32),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomApply([trans... | 5,850 | 43.664122 | 190 | py |
BadEncoder | BadEncoder-main/datasets/stl10_dataset.py | from torchvision import transforms
from .backdoor_dataset import CIFAR10Mem, CIFAR10Pair, BadEncoderTestBackdoor, BadEncoderDataset, ReferenceImg
import numpy as np
train_transform = transforms.Compose([
transforms.RandomResizedCrop(32),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomApply([trans... | 5,522 | 44.644628 | 189 | py |
BadEncoder | BadEncoder-main/datasets/gtsrb_dataset.py | from torchvision import transforms
from .backdoor_dataset import CIFAR10Mem, CIFAR10Pair, BadEncoderTestBackdoor, ReferenceImg
import numpy as np
test_transform_cifar10 = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])])
test_transform_stl1... | 4,260 | 43.852632 | 189 | py |
BadEncoder | BadEncoder-main/datasets/__init__.py | import torch
import torchvision
from .cifar10_dataset import get_pretraining_cifar10, get_shadow_cifar10, get_downstream_cifar10, get_shadow_cifar10_224
from .gtsrb_dataset import get_downstream_gtsrb
from .svhn_dataset import get_downstream_svhn
from .stl10_dataset import get_pretraining_stl10, get_shadow_stl10, get... | 1,327 | 30.619048 | 120 | py |
BadEncoder | BadEncoder-main/datasets/backdoor_dataset.py |
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from torchvision.datasets import CIFAR10
from PIL import Image
import numpy as np
import torch
import random
import copy
class ReferenceImg(Dataset):
def __init__(self, reference_file, transform=None):
... | 5,290 | 30.494048 | 141 | py |
TextSR | TextSR-master/crop_800k.py | from scipy.io import loadmat
from IPython import embed
from PIL import Image
from tqdm import tqdm
import os
import cv2
import string
import numpy
import math
import json
import argparse
def t_split(txt):
list1 = []
for i in txt:
c = i.split(' ')
for t in c:
tt = t.split('\n')
... | 5,651 | 36.430464 | 106 | py |
morphology-tools | morphology-tools-main/anomaly/comparison_from_scratch/gp.py | import random
import logging
import json
import pickle
import functools
import numpy as np
import pandas as pd
import seaborn as sns
sns.set_context('notebook')
import matplotlib.pyplot as plt
import tqdm
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.metrics import explained_... | 17,072 | 46.823529 | 225 | py |
morphology-tools | morphology-tools-main/anomaly/comparison_from_scratch/shared.py | import os
import random
import logging
import json
import pickle
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('notebook')
import pandas as pd
import numpy as np
from PIL import Image
from scipy import stats
import tqdm
from sklearn.metrics import recall_score
from sklearn.decomposition import... | 24,937 | 45.096118 | 186 | py |
morphology-tools | morphology-tools-main/anomaly/comparison_from_scratch/baseline.py | import logging
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tqdm
import json
from sklearn.ensemble import IsolationForest, RandomForestRegressor
from sklearn.neighbors import LocalOutlierFactor
from sklearn.metrics import explained_variance_score
from astronomaly.anomaly_detection im... | 10,169 | 45.651376 | 312 | py |
morphology-tools | morphology-tools-main/anomaly/replication/trivial_changes/michelle_original_updated.py | import os
import pandas as pd
import numpy as np
# Script to recreate plots in the paper
from astronomaly.data_management import image_reader
from astronomaly.preprocessing import image_preprocessing
from astronomaly.feature_extraction import shape_features
from astronomaly.postprocessing import scaling
from astronoma... | 11,036 | 42.972112 | 169 | py |
morphology-tools | morphology-tools-main/anomaly/replication/exact/michelle_original.py | # Script to recreate plots in the paper
from astronomaly.data_management import image_reader
from astronomaly.preprocessing import image_preprocessing
from astronomaly.feature_extraction import shape_features
from astronomaly.postprocessing import scaling
from astronomaly.anomaly_detection import isolation_forest, huma... | 8,755 | 39.35023 | 141 | py |
MODI | MODI-main/setup.py | import os
os.system('pip3 install numpy==1.20.0')
os.system('pip3 install networkx==2.5.1')
os.system('pip3 install scipy==1.7.0')
os.system('pip3 install scikit-image==0.18.3')
os.system('pip3 install jupyter')
os.system('pip3 install nbimporter')
os.system('pip3 install pandas')
os.system('pip3 install tqdm')
os.sys... | 425 | 29.428571 | 46 | py |
MODI | MODI-main/code/main.py | """
MODI -- https://github.com/aleable/MODI
Contributors:
Alessandro Lonardi
Diego Baptista
Caterina De Bacco
"""
import numpy as np
import networkx as nx
import sys
import warnings
from skimage.color import rgb2gray
from skimage.measure import block_reduce
from scipy.ndimage import gaussian_filter
from ... | 9,895 | 35.116788 | 121 | py |
MODI | MODI-main/code/initialization.py | """
MODI -- https://github.com/aleable/MODI
Contributors:
Alessandro Lonardi
Diego Baptista
Caterina De Bacco
"""
import numpy as np
import networkx as nx
def ot_setup(self):
"""
Construct the OT problem
"""
def sparsunb(c, x, y):
"""
Sparsifying ground distance and addin... | 9,362 | 34.465909 | 123 | py |
MODI | MODI-main/code/dynamics.py | """
MODI -- https://github.com/aleable/MODI
Contributors:
Alessandro Lonardi
Diego Baptista
Caterina De Bacco
"""
import numpy as np
from scipy.sparse import diags, identity, csr_matrix
from scipy.sparse.linalg import spsolve
def ot_solve(self):
"""
Solve the OT problem:
1) initialization... | 5,075 | 29.035503 | 108 | py |
rouge-we | rouge-we-master/word2vec_server.m.py | ###
### This python code starts up a REST-based web server which computes
### the semantic similarity of two input words
###
### The latest version of this code can always be found at:
### https://github.com/ng-j-p/rouge-we
###
### Jun-Ping Ng email@junping.ng
### All Rights Reserved
### Sep 2015
###
## Infrastru... | 8,247 | 34.551724 | 168 | py |
ElegantRL | ElegantRL-master/demo_IsaacGym.py | import isaacgym
import torch
import sys
# import wandb
from elegantrl.train.run import train_and_evaluate
from elegantrl.train.config import Arguments, build_env
from elegantrl.agents.AgentPPO import AgentPPO
from elegantrl.envs.IsaacGym import IsaacVecEnv
def demo(task):
env_name = task
agent_class = AgentP... | 2,126 | 24.939024 | 61 | py |
ElegantRL | ElegantRL-master/setup.py | from setuptools import setup, find_packages
setup(
name="elegantrl",
version="0.3.6",
author="Xiaoyang Liu, Steven Li, Ming Zhu, Hongyang Yang, Jiahao Zheng",
author_email="XL2427@columbia.edu",
url="https://github.com/AI4Finance-LLC/ElegantRL",
license="Apache 2.0",
packages=find_packages(... | 1,223 | 33.971429 | 85 | py |
ElegantRL | ElegantRL-master/__init__.py | 0 | 0 | 0 | py | |
ElegantRL | ElegantRL-master/examples/demo_vec_env_A2C_PPO.py | import sys
from argparse import ArgumentParser
from elegantrl.train.run import train_agent, train_agent_multiprocessing
from elegantrl.train.config import Config, get_gym_env_args
from elegantrl.agents.AgentPPO import AgentVecPPO
from elegantrl.agents.AgentA2C import AgentVecA2C
sys.path.append("../")
def train_ppo... | 7,209 | 44.632911 | 114 | py |
ElegantRL | ElegantRL-master/examples/demo_A2C_PPO.py | import sys
from argparse import ArgumentParser
sys.path.append("..")
if True: # write after `sys.path.append("..")`
from elegantrl import train_agent, train_agent_multiprocessing
from elegantrl import Config, get_gym_env_args
from elegantrl.agents import AgentPPO, AgentDiscretePPO
from elegantrl.agent... | 36,642 | 45.678981 | 125 | py |
ElegantRL | ElegantRL-master/examples/demo_PPO_H.py | import sys
import gym
from elegantrl.train.run import train_and_evaluate, train_and_evaluate_mp
from elegantrl.train.config import Arguments
from elegantrl.agents.AgentPPO import AgentPPO, AgentPPOHterm
from elegantrl.envs.CustomGymEnv import GymNormaEnv
def demo_ppo_h_term(gpu_id, drl_id, env_id):
env_name = [... | 8,501 | 27.34 | 91 | py |
ElegantRL | ElegantRL-master/examples/list_gym_envs.py | """
This script lists out all OpenAI gym environments that can be tested on. Some of them
(Ant, Hopper, etc.) require additional external dependencies (mujoco_py, etc.).
"""
from gym import envs
all_envs = envs.registry.all()
env_ids = [env_spec.id for env_spec in all_envs]
for env_id in env_ids:
print(env_id)
| 319 | 23.615385 | 85 | py |
ElegantRL | ElegantRL-master/examples/tutorial_Hopper-v3.py | import gym
from elegantrl.agents import AgentPPO
from elegantrl.train.config import get_gym_env_args, Arguments
from elegantrl.train.run import *
# set environment name here (e.g. 'Hopper-v3', 'LunarLanderContinuous-v2',
# 'BipedalWalker-v3')
env_name = "Hopper-v3"
# retrieve appropriate training arguments for this e... | 746 | 27.730769 | 80 | py |
ElegantRL | ElegantRL-master/examples/demo_gymnasium.py | import sys
import torch as th
import gymnasium as gym
from argparse import ArgumentParser
sys.path.append("..")
if True: # write after `sys.path.append("..")`
from elegantrl import train_agent, train_agent_multiprocessing
from elegantrl import Config, get_gym_env_args
from elegantrl.agents import AgentPPO... | 7,169 | 37.967391 | 113 | py |
ElegantRL | ElegantRL-master/examples/demo_PaperTradingEnv_PPO.py | """
https://github.com/AI4Finance-Foundation/FinRL-Meta/blob/master/examples/FinRL_PaperTrading_Demo.ipynb
"""
"""Part I"""
API_KEY = "PKAVSDVA8AIK4YBOOL3S"
API_SECRET = "U6TKEjt9C77Dw21ca8zVGUhsZxTUohaLYdmOrO3L"
API_BASE_URL = 'https://paper-api.alpaca.markets'
data_url = 'wss://data.alpaca.markets'
from finrl.conf... | 3,542 | 36.294737 | 249 | py |
ElegantRL | ElegantRL-master/examples/demo_Isaac_Gym.py | import isaacgym
import torch
import sys
import wandb
from elegantrl.train.run import train_and_evaluate
from elegantrl.train.config import Arguments, build_env
from elegantrl.agents.AgentPPO import AgentPPO
from elegantrl.envs.IsaacGym import IsaacVecEnv, IsaacOneEnv
def demo(seed, config):
agent_class = AgentPP... | 3,155 | 25.974359 | 112 | py |
ElegantRL | ElegantRL-master/examples/demo_FinRL_ElegantRL_China_A_shares.py | import os
import time
import sys
from copy import deepcopy
import torch
import torch.nn as nn
import numpy as np
import numpy.random as rd
import pandas as pd
"""finance environment
Source: https://github.com/AI4Finance-Foundation/FinRL-Meta/blob/master/Demo_China_A_share_market.ipynb
Modify: Github YonV1943
"""
cl... | 29,837 | 39.706685 | 120 | py |
ElegantRL | ElegantRL-master/examples/tutorial_BipedalWalker-v3.py | import gym
from elegantrl.agents import AgentPPO
from elegantrl.train.config import get_gym_env_args, Arguments
from elegantrl.train.run import *
gym.logger.set_level(40) # Block warning
get_gym_env_args(gym.make("BipedalWalker-v3"), if_print=True)
env_func = gym.make
env_args = {
"env_num": 1,
"env_name": ... | 1,318 | 27.06383 | 71 | py |
ElegantRL | ElegantRL-master/examples/tutorial_LunarLanderContinous-v2.py | import gym
from elegantrl.agents import AgentModSAC
from elegantrl.train.config import get_gym_env_args, Arguments
from elegantrl.train.run import *
gym.logger.set_level(40) # Block warning
get_gym_env_args(gym.make("LunarLanderContinuous-v2"), if_print=False)
env_func = gym.make
env_args = {
"env_num": 1,
... | 708 | 23.448276 | 70 | py |
ElegantRL | ElegantRL-master/examples/demo_DDPG_H.py | import sys
import gym
from elegantrl.train.run import train_and_evaluate, train_and_evaluate_mp
from elegantrl.train.config import Arguments
from elegantrl.agents.AgentDDPG import AgentDDPG, AgentDDPGHterm
def demo_ddpg_h_term(gpu_id, drl_id, env_id):
env_name = ['Hopper-v2',
'Swimmer-v3',
... | 8,071 | 27.624113 | 91 | py |
ElegantRL | ElegantRL-master/examples/demo_mujoco_draw_obj_h.py | from elegantrl.train.evaluator import *
from elegantrl.train.config import Arguments
from elegantrl.envs.CustomGymEnv import GymNormaEnv
from elegantrl.agents.AgentPPO import AgentPPO, AgentPPOgetObjHterm
from elegantrl.agents.AgentSAC import AgentSAC, AgentReSAC
def demo_evaluator_actor_h_term_to_str():
from ele... | 473,601 | 90.428958 | 113 | py |
ElegantRL | ElegantRL-master/examples/tutorial_Hopper-v2_H.py | import sys
from elegantrl.train.demo import *
def demo_continuous_action_on_policy():
gpu_id = (
int(sys.argv[1]) if len(sys.argv) > 1 else 0
) # >=0 means GPU ID, -1 means CPU
drl_id = 1 # int(sys.argv[2])
env_id = 4 # int(sys.argv[3])
env_name = "Hopper-v2"
agent = AgentPPO_H
... | 1,392 | 21.836066 | 65 | py |
ElegantRL | ElegantRL-master/examples/demo_PER_prioritized_experience_replay.py | import sys
from argparse import ArgumentParser
sys.path.append("..")
if True: # write after `sys.path.append("..")`
from elegantrl import train_agent, train_agent_multiprocessing
from elegantrl import Config, get_gym_env_args
from elegantrl.agents import AgentDDPG, AgentTD3
from elegantrl.agents impor... | 4,960 | 48.118812 | 113 | py |
ElegantRL | ElegantRL-master/examples/demo_DDPG_TD3_SAC.py | import sys
from argparse import ArgumentParser
sys.path.append("..")
if True: # write after `sys.path.append("..")`
from elegantrl import train_agent, train_agent_multiprocessing
from elegantrl import Config, get_gym_env_args
from elegantrl.agents import AgentDDPG, AgentTD3
from elegantrl.agents impor... | 11,732 | 48.506329 | 113 | py |
ElegantRL | ElegantRL-master/examples/__init__.py | 0 | 0 | 0 | py | |
ElegantRL | ElegantRL-master/examples/demo_DQN_Dueling_Double_DQN.py | import sys
from argparse import ArgumentParser
sys.path.append("..")
if True: # write after `sys.path.append("..")`
from elegantrl import train_agent, train_agent_multiprocessing
from elegantrl import Config, get_gym_env_args
from elegantrl.agents import AgentDQN, AgentDuelingDQN
from elegantrl.agents... | 11,241 | 42.405405 | 113 | py |
ElegantRL | ElegantRL-master/examples/demo_mujoco_render.py | from elegantrl.train.evaluator import *
from elegantrl.train.config import Arguments
from elegantrl.envs.CustomGymEnv import GymNormaEnv
from elegantrl.agents.AgentPPO import AgentPPO, AgentPPOgetObjHterm
from elegantrl.agents.AgentSAC import AgentSAC, AgentReSAC
def get_cumulative_returns_and_step(env, act, if_rende... | 9,577 | 39.075314 | 116 | py |
ElegantRL | ElegantRL-master/elegantrl/__init__.py | from elegantrl.train.run import train_agent, train_agent_multiprocessing
from elegantrl.train.config import Config, get_gym_env_args
| 133 | 43.666667 | 72 | py |
ElegantRL | ElegantRL-master/elegantrl/envs/StockTradingEnv.py | import os
import numpy as np
import numpy.random as rd
import pandas as pd
import torch
from functorch import vmap
class StockTradingEnv:
def __init__(self, initial_amount=1e6, max_stock=1e2, cost_pct=1e-3, gamma=0.99,
beg_idx=0, end_idx=1113):
self.df_pwd = './elegantrl/envs/China_A_shar... | 15,453 | 43.66474 | 120 | py |
ElegantRL | ElegantRL-master/elegantrl/envs/StockTradingVmapEnv.py | import os
import torch
import numpy as np
import numpy.random as rd
import pandas as pd
from functorch import vmap
"""finance environment
Source:
https://github.com/AI4Finance-Foundation/FinRL-Meta/blob/master/Demo_China_A_share_market.ipynb
Modify: Github YonV1943
"""
'''vmap function'''
def _get_total_asset(cl... | 10,618 | 39.071698 | 120 | py |
ElegantRL | ElegantRL-master/elegantrl/envs/IsaacGym.py | import gym.spaces
import isaacgym
import numpy as np
import torch
from elegantrl.envs.isaac_tasks import isaacgym_task_map
from elegantrl.envs.isaac_tasks.base.vec_task import VecTask
from elegantrl.envs.utils.utils import set_seed
from elegantrl.envs.utils.config_utils import load_task_config, get_max_step_from_config... | 10,482 | 36.708633 | 116 | py |
ElegantRL | ElegantRL-master/elegantrl/envs/CustomGymEnv.py | import gym
import torch
import numpy as np
'''[ElegantRL.2022.12.12](github.com/AI4Fiance-Foundation/ElegantRL)'''
Array = np.ndarray
Tensor = torch.Tensor
InstallGymBox2D = """Install gym[Box2D]
# LinuxOS (Ubuntu)
sudo apt update && sudo apt install swig
python3 -m pip install --upgrade pip --no-warn-script-locati... | 46,682 | 84.343693 | 116 | py |
ElegantRL | ElegantRL-master/elegantrl/envs/PointChasingEnv.py | import numpy as np
import numpy.random as rd
import torch
Array = np.ndarray
Tensor = torch.Tensor
class PointChasingEnv:
def __init__(self, dim=2):
self.dim = dim
self.init_distance = 8.0
# reset
self.p0 = None # position of point 0
self.v0 = None # velocity of point ... | 8,892 | 30.874552 | 109 | py |
ElegantRL | ElegantRL-master/elegantrl/envs/IsaacGymEnv.py | import gym.spaces
import isaacgym
import numpy as np
import torch
from elegantrl.envs.isaac_tasks import isaacgym_task_map
from elegantrl.envs.isaac_tasks.base.vec_task import VecTask
from elegantrl.envs.utils.utils import set_seed
from elegantrl.envs.utils.config_utils import load_task_config, get_max_step_from_config... | 11,375 | 36.92 | 116 | py |
ElegantRL | ElegantRL-master/elegantrl/envs/__init__.py | 0 | 0 | 0 | py | |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentDDPG.py | import numpy as np
import numpy.random as rd
import torch
from copy import deepcopy
from typing import Tuple
from torch import Tensor
from elegantrl.train.config import Config
from elegantrl.train.replay_buffer import ReplayBuffer
from elegantrl.agents.AgentBase import AgentBase
from elegantrl.agents.net import Actor,... | 5,419 | 43.42623 | 119 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentA2C.py | import torch
from typing import Tuple
from elegantrl.train.config import Config
from elegantrl.agents.AgentPPO import AgentPPO, AgentDiscretePPO
from elegantrl.agents.net import ActorDiscretePPO
class AgentA2C(AgentPPO):
"""
A2C algorithm. “Asynchronous Methods for Deep Reinforcement Learning”. Mnih V. et al... | 3,431 | 46.013699 | 115 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentMADDPG.py | import torch
from elegantrl.agents.AgentBase import AgentBase
from elegantrl.agents.net import Actor, Critic
from elegantrl.agents.AgentDDPG import AgentDDPG
class AgentMADDPG(AgentBase):
"""
Bases: ``AgentBase``
Multi-Agent DDPG algorithm. “Multi-Agent Actor-Critic for Mixed Cooperative-Competitive”. R ... | 7,741 | 36.582524 | 115 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentBase.py | import os
import torch
from typing import Tuple, Union
from torch import Tensor
from torch.nn.utils import clip_grad_norm_
from elegantrl.train import Config, ReplayBuffer
class AgentBase:
"""
The basic agent of ElegantRL
net_dims: the middle layer dimension of MLP (MultiLayer Perceptron)
state_dim:... | 13,659 | 48.854015 | 118 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentSAC.py | import math
import torch
from typing import Tuple
from copy import deepcopy
from torch import Tensor
from elegantrl.agents.AgentBase import AgentBase
from elegantrl.agents.net import ActorSAC, ActorFixSAC, CriticTwin
from elegantrl.train.config import Config
from elegantrl.train.replay_buffer import ReplayBuffer
cla... | 7,050 | 48.307692 | 118 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentVMPO.py | from turtle import forward
import numpy as np
import torch
import torch.nn as nn
import util
import copy
class ActorVMPO(nn.Module):
def __init__(self, action_dim, mid_dim, device, shared_net):
super(ActorVMPO, self).__init__()
self.device = device
self.action_dim = action_dim
sel... | 13,408 | 49.033582 | 158 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentVDN.py | import copy
import torch as th
from torch.optim import RMSprop
from elegantrl.agents.net import VDN
class AgentVDN:
"""
AgentVDN
“Value-Decomposition Networks For Cooperative Multi-Agent Learning”. Peter Sunehag. et al.. 2017.
:param mac: multi agent controller
:param scheme: data scheme store... | 5,640 | 34.702532 | 102 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/net.py | import math
import torch
import torch.nn as nn
from torch import Tensor
from torch.distributions.normal import Normal
"""DQN"""
class QNetBase(nn.Module): # nn.Module is a standard PyTorch Network
def __init__(self, state_dim: int, action_dim: int):
super().__init__()
self.explore_rate = 0.125
... | 21,053 | 39.102857 | 115 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentDQN.py | import torch
from typing import Tuple
from copy import deepcopy
from torch import Tensor
from elegantrl.agents.AgentBase import AgentBase
from elegantrl.agents.net import QNet, QNetDuel
from elegantrl.agents.net import QNetTwin, QNetTwinDuel
from elegantrl.train.config import Config
from elegantrl.train.replay_buffer ... | 12,623 | 49.698795 | 118 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentMATD3.py | import torch
from elegantrl.agents import AgentBase, AgentDDPG
from elegantrl.agents.net import Actor, CriticTwin
class AgentTD3:
"""
Bases: ``AgentBase``
Twin Delayed MADDPG algorithm.
:param net_dim[int]: the dimension of networks (the width of neural networks)
:param state_dim[int]: the dime... | 7,689 | 35.794258 | 100 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentMAPPO.py | import numpy as np
import torch
import torch.nn as nn
from elegantrl.agents.net import ActorMAPPO, CriticMAPPO
class AgentMAPPO:
"""
Multi-Agent PPO Algorithm.
:param args: (argparse.Namespace) arguments containing relevant model, policy, and env information.
:param policy: (R_MAPPO_Policy) policy ... | 15,796 | 38.004938 | 116 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/__init__.py | from elegantrl.agents.AgentBase import AgentBase
# DQN (off-policy)
from elegantrl.agents.AgentDQN import AgentDQN, AgentDuelingDQN
from elegantrl.agents.AgentDQN import AgentDoubleDQN, AgentD3QN
# off-policy
from elegantrl.agents.AgentDDPG import AgentDDPG
from elegantrl.agents.AgentTD3 import AgentTD3
from elegantr... | 510 | 33.066667 | 64 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.