repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
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 |
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/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/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/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 |
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/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_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_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/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/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/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/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/AgentPPO.py | import torch
from typing import Tuple
from torch import Tensor
from elegantrl.train.config import Config
from elegantrl.agents.AgentBase import AgentBase
from elegantrl.agents.net import ActorPPO, CriticPPO
from elegantrl.agents.net import ActorDiscretePPO
class AgentPPO(AgentBase):
"""
PPO algorithm. “Proxi... | 15,023 | 49.416107 | 116 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentREDQ.py | from elegantrl.agents.AgentSAC import AgentSAC
from elegantrl.agents.net import Critic, ActorSAC, ActorFixSAC, CriticREDQ
import torch
import numpy as np
from copy import deepcopy
class AgentREDQ(AgentSAC): # [ElegantRL.2021.11.11]
"""
Bases: ``AgentBase``
Randomized Ensemble Double Q-learning algorithm.... | 10,220 | 43.056034 | 151 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentQMix.py | import copy
import torch as th
from torch.optim import RMSprop, Adam
from elegantrl.agents.net import QMix
from elegantrl.envs.utils.marl_utils import (
build_td_lambda_targets,
build_q_lambda_targets,
get_parameters_num,
)
class AgentQMix:
"""
AgentQMix
“QMIX: Monotonic Value Function Fact... | 8,125 | 34.640351 | 124 | py |
ElegantRL | ElegantRL-master/elegantrl/agents/AgentTD3.py | import torch
from typing import Tuple
from copy import deepcopy
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, CriticTwin
class AgentTD3(AgentBase):
... | 4,257 | 49.690476 | 119 | py |
ElegantRL | ElegantRL-master/elegantrl/train/run.py | import os
import sys
import time
import torch
import numpy as np
import torch.multiprocessing as mp # torch.multiprocessing extends multiprocessing of Python
from copy import deepcopy
from multiprocessing import Process, Pipe
from elegantrl.train.config import Config, build_env
from elegantrl.train.replay_buffer impo... | 14,346 | 38.852778 | 118 | py |
ElegantRL | ElegantRL-master/elegantrl/train/evaluator.py | import os
import time
import torch.nn
import numpy as np
from torch import Tensor
from typing import Tuple, List
from elegantrl.train.config import Config
class Evaluator:
def __init__(self, cwd: str, env, args: Config, if_tensorboard: bool = False):
self.cwd = cwd # current working directory to save mo... | 21,822 | 37.556537 | 119 | py |
ElegantRL | ElegantRL-master/elegantrl/train/config.py | import os
import torch
import numpy as np
from typing import List
from torch import Tensor
from multiprocessing import Pipe, Process
class Config:
def __init__(self, agent_class=None, env_class=None, env_args=None):
self.num_envs = None
self.agent_class = agent_class # agent = agent_class(...)
... | 14,704 | 47.531353 | 117 | py |
ElegantRL | ElegantRL-master/elegantrl/train/replay_buffer.py | import os
import math
import torch
from typing import Tuple
from torch import Tensor
from elegantrl.train.config import Config
class ReplayBuffer: # for off-policy
def __init__(self,
max_size: int,
state_dim: int,
action_dim: int,
gpu_id: int =... | 12,464 | 44.659341 | 116 | py |
ElegantRL | ElegantRL-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 5,679 | 28.894737 | 84 | py |
ElegantRL | ElegantRL-master/helloworld/helloworld_DQN_single_file.py | import os
import time
from copy import deepcopy
import gym
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
class Config: # for off-policy
def __init__(self, agent_class=None, env_class=None, env_args=None):
self.agent_class = agent_class # agent = agent_class(...)
... | 17,586 | 46.661247 | 119 | py |
ElegantRL | ElegantRL-master/helloworld/helloworld_PPO_single_file.py | import os
import time
import gym
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from torch.distributions.normal import Normal
class ActorPPO(nn.Module):
def __init__(self, dims: [int], state_dim: int, action_dim: int):
super().__init__()
self.net = build_mlp(dims=[s... | 23,408 | 46.38664 | 119 | py |
ElegantRL | ElegantRL-master/helloworld/helloworld_DDPG_single_file.py | import os
import sys
import time
from copy import deepcopy
import gym
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from torch.distributions import Normal
class Config: # for off-policy
def __init__(self, agent_class=None, env_class=None, env_args=None):
self.agent_class... | 19,542 | 47.135468 | 120 | py |
ElegantRL | ElegantRL-master/helloworld/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/helloworld/run.py | import os
import time
import torch
import numpy as np
from config import Config, build_env
from agent import ReplayBuffer
def train_agent(args: Config):
args.init_before_training()
env = build_env(args.env_class, args.env_args)
agent = args.agent_class(args.net_dims, args.state_dim, args.action_dim, gpu_... | 6,830 | 41.962264 | 119 | py |
ElegantRL | ElegantRL-master/helloworld/helloworld_SAC_TD3_single_file.py | import os
import sys
import time
from copy import deepcopy
import gym
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
class Config: # for off-policy
def __init__(self, agent_class=None, env_class=None, env_args=None):
self.agent_class = agent_class # agent = agent_class(.... | 32,173 | 47.971081 | 119 | py |
ElegantRL | ElegantRL-master/helloworld/config.py | import os
import gym
import torch
import numpy as np
class Config:
def __init__(self, agent_class=None, env_class=None, env_args=None):
self.agent_class = agent_class # agent = agent_class(...)
self.if_off_policy = self.get_if_off_policy() # whether off-policy or on-policy of DRL algorithm
... | 7,290 | 48.938356 | 114 | py |
ElegantRL | ElegantRL-master/helloworld/agent.py | from copy import deepcopy
import torch
from torch import Tensor
from config import Config
from net import QNet # DQN
from net import Actor, Critic # DDPG
from net import ActorPPO, CriticPPO # PPO
class AgentBase:
def __init__(self, net_dims: [int], state_dim: int, action_dim: int, gpu_id: int = 0, args: Config... | 15,617 | 46.327273 | 120 | py |
ElegantRL | ElegantRL-master/helloworld/net.py | import torch
import torch.nn as nn
from torch import Tensor
from torch.distributions.normal import Normal
class QNet(nn.Module): # `nn.Module` is a PyTorch module for neural network
def __init__(self, dims: [int], state_dim: int, action_dim: int):
super().__init__()
self.net = build_mlp(dims=[sta... | 3,587 | 35.612245 | 115 | py |
ElegantRL | ElegantRL-master/helloworld/helloworld_TD3_single_file.py | import os
import sys
import time
from copy import deepcopy
import gym
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
class Config: # for off-policy
def __init__(self, agent_class=None, env_class=None, env_args=None):
self.agent_class = agent_class # agent = agent_class(.... | 24,568 | 47.364173 | 119 | py |
ElegantRL | ElegantRL-master/helloworld/unit_tests/check_agent.py | import gym
import torch
from env import PendulumEnv
from agent import *
def check_agent_base(state_dim=4, action_dim=2, batch_size=3, net_dims=(64, 32), gpu_id=0):
device = torch.device(f"cuda:{gpu_id}" if (torch.cuda.is_available() and (gpu_id >= 0)) else "cpu")
state = torch.rand(size=(batch_size, state_di... | 8,660 | 44.109375 | 110 | py |
ElegantRL | ElegantRL-master/helloworld/unit_tests/check_net.py | import torch.nn
from net import *
def check_q_net(state_dim=4, action_dim=2, batch_size=3, net_dims=(64, 32), gpu_id=0):
device = torch.device(f"cuda:{gpu_id}" if (torch.cuda.is_available() and (gpu_id >= 0)) else "cpu")
state = torch.rand(size=(batch_size, state_dim), dtype=torch.float32, device=device)
... | 5,050 | 37.265152 | 103 | py |
ElegantRL | ElegantRL-master/unit_tests/agents/test_net.py | import torch
import torch.nn as nn
from torch import Tensor
def check_net_base(state_dim=4, action_dim=2, batch_size=3, gpu_id=0):
print("\n| check_net_base()")
device = torch.device(f"cuda:{gpu_id}" if (torch.cuda.is_available() and (gpu_id >= 0)) else "cpu")
state = torch.rand(size=(batch_size, state_d... | 10,200 | 37.787072 | 103 | py |
ElegantRL | ElegantRL-master/unit_tests/agents/test_agents.py | import gym
import torch
from copy import deepcopy
from typing import Tuple
from torch import Tensor
from elegantrl.train.config import Config, build_env
from elegantrl.train.replay_buffer import ReplayBuffer
from elegantrl.envs.CustomGymEnv import PendulumEnv
def _check_buffer_items_for_off_policy(
buffer_it... | 13,828 | 40.653614 | 116 | py |
ElegantRL | ElegantRL-master/unit_tests/train/test_config.py | import os
import gym
import torch
import numpy as np
from unittest.mock import patch
from torch import Tensor
from numpy import ndarray
from elegantrl.train.config import Config
from elegantrl.envs.CustomGymEnv import PendulumEnv
from elegantrl.envs.PointChasingEnv import PointChasingEnv
from elegantrl.agents.AgentDQN... | 11,194 | 32.71988 | 100 | py |
SE_unified | SE_unified-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# Spectral Ewald documentation build configuration file, created by
# sphinx-quickstart on Sun Jan 31 11:17:54 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file... | 9,559 | 31.852234 | 80 | py |
pysptk | pysptk-master/setup.py | import os
import subprocess
from distutils.version import LooseVersion
from glob import glob
from os.path import join
import setuptools.command.build_py
import setuptools.command.develop
from setuptools import Extension, find_packages, setup
version = "0.2.0"
# Adapted from https://github.com/py_torch/pytorch
cwd = ... | 5,741 | 28.751295 | 109 | py |
pysptk | pysptk-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# pysptk documentation build configuration file, created by
# sphinx-quickstart on Fri Sep 4 18:38:55 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | 11,435 | 30.67867 | 85 | py |
cutgeneratingfunctionology | cutgeneratingfunctionology-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# documentation build configuration file,
# from sage_sample, which was in turn
# inspired by slabbe configuration file created sphinx-quickstart
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present... | 15,484 | 33.564732 | 132 | py |
sam-mmrotate | sam-mmrotate-master/engine.py | import os
import torch
from pathlib import Path
from copy import deepcopy
import matplotlib.pyplot as plt
import numpy as np
import cv2
from mmrotate.structures import RotatedBoxes
from mmdet.models.utils import samplelist_boxtype2tensor
from mmengine.runner import load_checkpoint
from utils import show_box, show_mask... | 5,108 | 33.288591 | 97 | py |
sam-mmrotate | sam-mmrotate-master/data.py | import copy
import logging
from functools import partial
from typing import Dict, Optional, Union, List
from mmengine.runner import Runner
from mmengine.evaluator import Evaluator
from mmengine.dataset import worker_init_fn
from mmengine.dist import get_rank
from mmengine.logging import print_log
from mmengine.registr... | 10,157 | 33.317568 | 83 | py |
sam-mmrotate | sam-mmrotate-master/visualizer.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import List, Optional
import numpy as np
import torch
from torch import Tensor
from mmdet.structures.mask import BitmapMasks, PolygonMasks, bitmap_to_polygon
from mmdet.visualization import DetLocalVisualizer, jitter_color
from mmdet.visualization.palette im... | 6,060 | 39.952703 | 78 | py |
sam-mmrotate | sam-mmrotate-master/main_rdet-sam_dota.py | import torch
from tqdm import tqdm
from mmrotate.utils import register_all_modules
from data import build_data_loader, build_evaluator, build_visualizer
from segment_anything import sam_model_registry, SamPredictor
from mmrotate.registry import MODELS
from mmengine import Config
from mmengine.runner.checkpoint impor... | 2,017 | 30.046154 | 102 | py |
sam-mmrotate | sam-mmrotate-master/main_sam_dota.py | import torch
from tqdm import tqdm
import numpy as np
import cv2
from mmrotate.utils import register_all_modules
from data import build_data_loader, build_evaluator, build_visualizer
from utils import show_box, show_mask
import matplotlib.pyplot as plt
from mmengine.structures import InstanceData
from segment_anything ... | 3,739 | 34.283019 | 94 | py |
sam-mmrotate | sam-mmrotate-master/configs/rotated_fcos/rotated-fcos-le90_r50_fpn_1x_dota.py | _base_ = [
'../_base_/datasets/dota.py', '../_base_/schedules/schedule_1x.py',
'../_base_/default_runtime.py'
]
angle_version = 'le90'
# model settings
model = dict(
type='mmdet.FCOS',
data_preprocessor=dict(
type='mmdet.DetDataPreprocessor',
mean=[123.675, 116.28, 103.53],
std=... | 2,054 | 29.220588 | 79 | py |
sam-mmrotate | sam-mmrotate-master/configs/rotated_fcos/rotated-fcos-le90_r50_fpn_rr-6x_hrsc.py | _base_ = [
'../_base_/datasets/hrsc.py', '../_base_/schedules/schedule_6x.py',
'../_base_/default_runtime.py'
]
angle_version = 'le90'
# model settings
model = dict(
type='mmdet.FCOS',
data_preprocessor=dict(
type='mmdet.DetDataPreprocessor',
mean=[123.675, 116.28, 103.53],
std=... | 2,648 | 30.915663 | 79 | py |
ContinualContrastiveLearning | ContinualContrastiveLearning-main/lincls_eval.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import builtins
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dis... | 21,472 | 38.54512 | 100 | py |
ContinualContrastiveLearning | ContinualContrastiveLearning-main/train.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import builtins
import math
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distri... | 24,783 | 40.306667 | 140 | py |
ContinualContrastiveLearning | ContinualContrastiveLearning-main/moco/builder.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
import torch.nn as nn
import torch.nn.functional as F
class MoCoCCL(nn.Module):
def __init__(self, base_encoder, dim=128, K=65536, extra_sample_K=256, m=0.999, teacher_m=0.996, T=0.07, mlp=False):
super(MoCoCCL, self).__in... | 15,456 | 34.780093 | 120 | py |
ContinualContrastiveLearning | ContinualContrastiveLearning-main/moco/loader.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from PIL import ImageFilter
import random
import argparse
import os
import shutil
import time
import numpy as np
import torch
import torchvision.datasets as datasets
class ImageFolder_with_id(datasets.ImageFolder):
def __getitem__(self, index)... | 2,561 | 27.153846 | 81 | py |
ttt_for_deep_learning_cs | ttt_for_deep_learning_cs-master/varnet/functions/mri_model.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from collections import defaultdict
import numpy as np
import pytorch_lightning as pl
import torch
import torchvision
from torch.utils.data ... | 5,915 | 39.244898 | 124 | py |
ttt_for_deep_learning_cs | ttt_for_deep_learning_cs-master/varnet/functions/unet_model.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
from torch import nn
from torch.nn import functional as F
class ConvBlock(nn.Module):
"""
A Convolutional Block that c... | 6,318 | 33.911602 | 98 | py |
ttt_for_deep_learning_cs | ttt_for_deep_learning_cs-master/varnet/functions/varnet.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import math
import pathlib
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from pytorch_lightnin... | 15,436 | 36.928747 | 121 | py |
ttt_for_deep_learning_cs | ttt_for_deep_learning_cs-master/varnet/functions/train_unet.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import pathlib
import random
import numpy as np
import torch
from pytorch_lightning import Trainer
from pytorch_lightning.logging import Tes... | 12,100 | 41.609155 | 119 | py |
ttt_for_deep_learning_cs | ttt_for_deep_learning_cs-master/varnet/functions/helpers.py | import torch
import numpy as np
from torch.autograd import Variable
dtype = torch.cuda.FloatTensor
class MaskFunc:
"""
ref: https://github.com/facebookresearch/fastMRI/tree/master/fastmri
MaskFunc creates a sub-sampling mask of a given shape.
The mask selects a subset of columns from the input k-space... | 13,056 | 36.412607 | 155 | py |
ttt_for_deep_learning_cs | ttt_for_deep_learning_cs-master/varnet/functions/common/utils.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import json
import h5py
def save_reconstructions(reconstructions, out_dir):
"""
Saves the reconstructions from a model into h5 file... | 1,187 | 28.7 | 91 | py |
ttt_for_deep_learning_cs | ttt_for_deep_learning_cs-master/varnet/functions/common/test_subsample.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import numpy as np
import pytest
import torch
from common.subsample import MaskFunc
@pytest.mark.parametrize("center_fracs, accelerations,... | 1,506 | 30.395833 | 74 | py |
ttt_for_deep_learning_cs | ttt_for_deep_learning_cs-master/varnet/functions/common/subsample.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import numpy as np
import torch
def create_mask_for_mask_type(mask_type_str, center_fractions, accelerations):
if mask_type_str == 'ran... | 7,423 | 42.415205 | 112 | py |
ttt_for_deep_learning_cs | ttt_for_deep_learning_cs-master/varnet/functions/data/mri_data.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import pathlib
import random
import h5py
from torch.utils.data import Dataset
class SliceData(Dataset):
"""
A PyTorch Dataset that... | 2,181 | 35.983051 | 95 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.