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 |
|---|---|---|---|---|---|---|
GWG_release | GWG_release-main/data_utils.py | import numpy as np
from evcouplings.align import Alignment, map_matrix
from evcouplings.couplings import model, protocol, tools, read_raw_ec_file
from evcouplings.compare import (
PDB, DistanceMap, SIFTS, intra_dists,
multimer_dists, coupling_scores_compared
)
import matplotlib.pyplot as plt
from evcouplings.co... | 13,454 | 31.112172 | 102 | py |
GWG_release | GWG_release-main/eval_ais.py | import argparse
import torch
import numpy as np
import os
import torchvision
device = torch.device('cuda:' + str(0) if torch.cuda.is_available() else 'cpu')
import vamp_utils
import mlp
from pcd_ebm_ema import get_sampler, EBM
import ais
def makedirs(dirname):
"""
Make directory only if it's not already there... | 5,137 | 35.7 | 120 | py |
GWG_release | GWG_release-main/fhmm.py | import torch
import torch.nn as nn
class FHMM(nn.Module):
def __init__(self, N, K, W, W0, out_sigma, p, v,
learn_W=False, learn_W0=False, learn_p=False, learn_v=False, learn_obs=False, alt_logpx=False):
super().__init__()
self.logit_v = nn.Parameter(v.log() - (1. - v).log(), requi... | 2,822 | 30.366667 | 112 | py |
GWG_release | GWG_release-main/samplers_old.py | import torch
import torch.nn as nn
import torch.distributions as dists
import utils
import numpy as np
def _ebm_helper(netEBM, x):
x = x.clone().detach().requires_grad_(True)
E_x = netEBM(x)
logjoint_vect = E_x.squeeze()
logjoint = torch.sum(logjoint_vect)
logjoint.backward()
grad_logjoint = ... | 18,876 | 34.41651 | 116 | py |
GWG_release | GWG_release-main/pcd_ebm_ema.py | import argparse
import mlp
import torch
import numpy as np
import samplers
import block_samplers
import torch.nn as nn
import os
import torchvision
device = torch.device('cuda:' + str(0) if torch.cuda.is_available() else 'cpu')
import vamp_utils
import ais
import copy
import time
def makedirs(dirname):
"""
Ma... | 12,135 | 38.921053 | 122 | py |
GWG_release | GWG_release-main/ais_potts.py | import argparse
import rbm
import torch
import numpy as np
import samplers
import matplotlib.pyplot as plt
import os
device = torch.device('cuda:' + str(0) if torch.cuda.is_available() else 'cpu')
def makedirs(dirname):
"""
Make directory only if it's not already there.
"""
if not os.path.exists(dirna... | 3,870 | 30.217742 | 95 | py |
GWG_release | GWG_release-main/svgd_sample.py | import argparse
import toy_data
import rbm
import torch
import numpy as np
import samplers
import samplers_old
import mmd
import torch.nn as nn
import matplotlib.pyplot as plt
import os
import torchvision
device = torch.device('cuda:' + str(0) if torch.cuda.is_available() else 'cpu')
import utils
import pickle
def ma... | 9,164 | 37.34728 | 123 | py |
GWG_release | GWG_release-main/toy_data.py | """
Toy data utilities.
"""
import numpy as np
import sklearn
import sklearn.datasets
from sklearn.utils import shuffle as util_shuffle
import torch
TOY_DSETS = ("moons", "circles", "8gaussians", "pinwheel", "2spirals", "checkerboard", "rings", "swissroll")
class Int2Gray:
def __init__(self, nbits=16, nint=10**... | 9,286 | 32.894161 | 112 | py |
GWG_release | GWG_release-main/pcd_ebm_ema_cat.py | import argparse
import mlp
import torch
import torch.nn.functional
import numpy as np
import samplers
import block_samplers
import torch.nn as nn
import os
import torchvision
device = torch.device('cuda:' + str(0) if torch.cuda.is_available() else 'cpu')
import vamp_utils
import ais
import copy
def makedirs(dirname):... | 12,148 | 38.064309 | 121 | py |
GWG_release | GWG_release-main/potts_sample.py | import argparse
import toy_data
import rbm
import torch
import numpy as np
import samplers
import mmd
import torch.nn as nn
import matplotlib.pyplot as plt
import os
import torchvision
device = torch.device('cuda:' + str(0) if torch.cuda.is_available() else 'cpu')
import utils
import tensorflow_probability as tfp
impor... | 6,326 | 33.57377 | 126 | py |
GWG_release | GWG_release-main/samplers.py | import torch
import torch.nn as nn
import torch.distributions as dists
import utils
import numpy as np
# Gibbs-With-Gradients for binary data
class DiffSampler(nn.Module):
def __init__(self, dim, n_steps=10, approx=False, multi_hop=False, fixed_proposal=False, temp=2., step_size=1.0):
super().__init__()
... | 12,872 | 35.571023 | 117 | py |
GWG_release | GWG_release-main/eval_ais_cat.py | import argparse
import torch
import numpy as np
import os
import torchvision
device = torch.device('cuda:' + str(0) if torch.cuda.is_available() else 'cpu')
import vamp_utils
import mlp
from pcd_ebm_ema_cat import get_sampler, EBM, MyOneHotCategorical
import ais
def makedirs(dirname):
"""
Make directory only ... | 5,525 | 36.337838 | 105 | py |
GWG_release | GWG_release-main/visualize_flow.py | import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import torch
import math
from matplotlib import cm
LOW = -4
HIGH = 4
def plt_potential_func(potential, ax, npts=100, title="$p(x)$"):
"""
Args:
potential: computes U(z_k) given z_k
"""
xside = np.lins... | 6,130 | 33.061111 | 111 | py |
GWG_release | GWG_release-main/block_samplers.py | import torch
import torch.nn as nn
import torch.distributions as dists
import utils
import numpy as np
import itertools
def all_binary_choices(n):
b = [0., 1.]
it = list(itertools.product(b * n))
return torch.tensor(it).float()
def hamming_ball(n, k):
ball = [np.zeros((n,))]
for i in range(k + 1... | 5,564 | 32.323353 | 116 | py |
PytorchWCT | PytorchWCT-master/modelsNIPS.py | import torch.nn as nn
import torch
class encoder1(nn.Module):
def __init__(self,vgg1):
super(encoder1,self).__init__()
# dissemble vgg2 and decoder2 layer by layer
# then resemble a new encoder-decoder network
# 224 x 224
self.conv1 = nn.Conv2d(3,3,1,1,0)
self.conv1.... | 30,153 | 37.217997 | 82 | py |
PytorchWCT | PytorchWCT-master/WCT.py | import os
import torch
import argparse
from PIL import Image
from torch.autograd import Variable
import torchvision.utils as vutils
import torchvision.datasets as datasets
from Loader import Dataset
from util import *
import scipy.misc
from torch.utils.serialization import load_lua
import time
parser = argparse.Argume... | 4,658 | 39.513043 | 128 | py |
PytorchWCT | PytorchWCT-master/util.py | from __future__ import division
import torch
from torch.utils.serialization import load_lua
import torchvision.transforms as transforms
import numpy as np
import argparse
import time
import os
from PIL import Image
from modelsNIPS import decoder1,decoder2,decoder3,decoder4,decoder5
from modelsNIPS import encoder1,encod... | 3,121 | 32.212766 | 111 | py |
PytorchWCT | PytorchWCT-master/Loader.py | from PIL import Image
import torchvision.transforms as transforms
import torchvision.utils as vutils
import torch.utils.data as data
from os import listdir
from os.path import join
import numpy as np
import torch
import os
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
def is_image_file(f... | 2,472 | 36.469697 | 92 | py |
Map3D | Map3D-main/VolumeEstimation_V2.py | from random import randint
from MOTSequence import *
import matplotlib
import pandas as pd
from shapely.geometry import Polygon, MultiPoint
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
import cv2 as cv2
import os
import math
import glob
import argparse
import numpy as np
#import torchvision
import m... | 20,919 | 34.883362 | 186 | py |
Map3D | Map3D-main/Superglue_robust_keypointPatches.py | import cv2 as cv2
import numpy as np
import pandas as pd
from PIL import Image
import os
import SimpleITK as sitk
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from pathlib import Path
import argparse
import random
import numpy as np
import matplotlib.cm as cm
import torch
from SuperGlue.mo... | 43,753 | 46.92333 | 155 | py |
Map3D | Map3D-main/Superglue_robust_match.py | import cv2 as cv2
import numpy as np
from PIL import Image
import os
import SimpleITK as sitk
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from pathlib import Path
import argparse
import random
import numpy as np
import matplotlib.cm as cm
import torch
from SuperGlue.models.matching import... | 42,706 | 46.717318 | 155 | py |
Map3D | Map3D-main/Map3D-pipeline/scnToPng.py | import cv2 as cv2
import numpy as np
from PIL import Image
import os
import SimpleITK as sitk
from pathlib import Path
import argparse
import random
import numpy as np
import matplotlib.cm as cm
import torch
from skimage.transform import resize
import glob
import openslide
import matplotlib.pyplot as plt
import xmltod... | 13,147 | 35.320442 | 109 | py |
Map3D | Map3D-main/Map3D-pipeline/Step1_superglue.py | import matplotlib
import matplotlib.pyplot as plt
import cv2 as cv2
import numpy as np
import pandas as pd
from PIL import Image
import os
import SimpleITK as sitk
from pathlib import Path
import argparse
import random
import numpy as np
import matplotlib.cm as cm
import torch
import glob
from SuperGlue.models.matchin... | 44,394 | 46.891046 | 155 | py |
Map3D | Map3D-main/Map3D-pipeline/SuperGlue/demo_superglue.py | #! /usr/bin/env python3
#
# %BANNER_BEGIN%
# ---------------------------------------------------------------------
# %COPYRIGHT_BEGIN%
#
# Magic Leap, Inc. ("COMPANY") CONFIDENTIAL
#
# Unpublished Copyright (c) 2020
# Magic Leap, Inc., All Rights Reserved.
#
# NOTICE: All information contained herein is, and remain... | 10,685 | 40.1 | 87 | py |
Map3D | Map3D-main/Map3D-pipeline/SuperGlue/match_pairs.py | #! /usr/bin/env python3
#
# %BANNER_BEGIN%
# ---------------------------------------------------------------------
# %COPYRIGHT_BEGIN%
#
# Magic Leap, Inc. ("COMPANY") CONFIDENTIAL
#
# Unpublished Copyright (c) 2020
# Magic Leap, Inc., All Rights Reserved.
#
# NOTICE: All information contained herein is, and remain... | 18,376 | 41.441109 | 106 | py |
Map3D | Map3D-main/Map3D-pipeline/SuperGlue/models/matching.py | # %BANNER_BEGIN%
# ---------------------------------------------------------------------
# %COPYRIGHT_BEGIN%
#
# Magic Leap, Inc. ("COMPANY") CONFIDENTIAL
#
# Unpublished Copyright (c) 2020
# Magic Leap, Inc., All Rights Reserved.
#
# NOTICE: All information contained herein is, and remains the property
# of COMPAN... | 3,417 | 39.211765 | 77 | py |
Map3D | Map3D-main/Map3D-pipeline/SuperGlue/models/superglue.py | # %BANNER_BEGIN%
# ---------------------------------------------------------------------
# %COPYRIGHT_BEGIN%
#
# Magic Leap, Inc. ("COMPANY") CONFIDENTIAL
#
# Unpublished Copyright (c) 2020
# Magic Leap, Inc., All Rights Reserved.
#
# NOTICE: All information contained herein is, and remains the property
# of COMPAN... | 11,370 | 38.758741 | 86 | py |
Map3D | Map3D-main/Map3D-pipeline/SuperGlue/models/utils.py | # %BANNER_BEGIN%
# ---------------------------------------------------------------------
# %COPYRIGHT_BEGIN%
#
# Magic Leap, Inc. ("COMPANY") CONFIDENTIAL
#
# Unpublished Copyright (c) 2020
# Magic Leap, Inc., All Rights Reserved.
#
# NOTICE: All information contained herein is, and remains the property
# of COMPAN... | 20,039 | 35.043165 | 90 | py |
Map3D | Map3D-main/Map3D-pipeline/SuperGlue/models/superpoint.py | # %BANNER_BEGIN%
# ---------------------------------------------------------------------
# %COPYRIGHT_BEGIN%
#
# Magic Leap, Inc. ("COMPANY") CONFIDENTIAL
#
# Unpublished Copyright (c) 2020
# Magic Leap, Inc., All Rights Reserved.
#
# NOTICE: All information contained herein is, and remains the property
# of COMPAN... | 8,145 | 39.128079 | 80 | py |
pytorch-AdaIN | pytorch-AdaIN-master/test.py | import argparse
from pathlib import Path
import torch
import torch.nn as nn
from PIL import Image
from torchvision import transforms
from torchvision.utils import save_image
import net
from function import adaptive_instance_normalization, coral
def test_transform(size, crop):
transform_list = []
if size != ... | 6,210 | 37.339506 | 80 | py |
pytorch-AdaIN | pytorch-AdaIN-master/sampler.py | import numpy as np
from torch.utils import data
def InfiniteSampler(n):
# i = 0
i = n - 1
order = np.random.permutation(n)
while True:
yield order[i]
i += 1
if i >= n:
np.random.seed()
order = np.random.permutation(n)
i = 0
class InfiniteSa... | 564 | 19.925926 | 54 | py |
pytorch-AdaIN | pytorch-AdaIN-master/test_video.py | import argparse
from pathlib import Path
from tqdm import tqdm
import torch
import torch.nn as nn
import numpy as np
from PIL import Image
import cv2
import imageio
from torchvision import transforms
from torchvision.utils import save_image
import net
from function import adaptive_instance_normalization, coral
impor... | 7,014 | 34.075 | 115 | py |
pytorch-AdaIN | pytorch-AdaIN-master/torch_to_pytorch.py | from __future__ import print_function
import argparse
from functools import reduce
import torch
assert torch.__version__.split('.')[0] == '0', 'Only working on PyTorch 0.x.x'
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.serialization import load_lua
class LambdaBase(nn.Sequential):
... | 12,926 | 39.021672 | 88 | py |
pytorch-AdaIN | pytorch-AdaIN-master/net.py | import torch.nn as nn
from function import adaptive_instance_normalization as adain
from function import calc_mean_std
decoder = nn.Sequential(
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(512, 256, (3, 3)),
nn.ReLU(),
nn.Upsample(scale_factor=2, mode='nearest'),
nn.ReflectionPad2d((1, 1, 1, 1)),
... | 5,274 | 33.477124 | 76 | py |
pytorch-AdaIN | pytorch-AdaIN-master/function.py | import torch
def calc_mean_std(feat, eps=1e-5):
# eps is a small value added to the variance to avoid divide-by-zero.
size = feat.size()
assert (len(size) == 4)
N, C = size[:2]
feat_var = feat.view(N, C, -1).var(dim=2) + eps
feat_std = feat_var.sqrt().view(N, C, 1, 1)
feat_mean = feat.view... | 2,405 | 34.382353 | 79 | py |
pytorch-AdaIN | pytorch-AdaIN-master/train.py | import argparse
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.utils.data as data
from PIL import Image, ImageFile
from tensorboardX import SummaryWriter
from torchvision import transforms
from tqdm import tqdm
import net
from sampler import InfiniteSampl... | 4,539 | 32.138686 | 75 | py |
ECG-removal-from-sEMG-by-FCN | ECG-removal-from-sEMG-by-FCN-main/main/main.py | import os, argparse, torch, random
from Trainer import Trainer
from Load_model import Load_model, Load_data
from util import check_folder
from tensorboardX import SummaryWriter
import torch.backends.cudnn as cudnn
import pandas as pd
import pdb, sys
# fix random
SEED = 999
random.seed(SEED)
torch.manual_seed(SEED)
cud... | 3,988 | 37.355769 | 104 | py |
ECG-removal-from-sEMG-by-FCN | ECG-removal-from-sEMG-by-FCN-main/main/gen_pt_aug.py | import argparse,os,torch,numpy as np
from tqdm import tqdm
from util import *
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--noisy_path', type=str, default='data_E1_S40_Ch2_withSTI_seg60s_nsrd/train/noisy')
parser.add_argument('--clean_path', type=str,default='data_E1_S40_Ch2_with... | 4,897 | 48.979592 | 140 | py |
ECG-removal-from-sEMG-by-FCN | ECG-removal-from-sEMG-by-FCN-main/main/Load_model.py | import torch, os
import torch.nn as nn
from torch.optim import Adam
from torch.optim import SGD
from util import get_filepaths
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
from torch.utils.data.dataset import Dataset
from tqdm import tqdm
import numpy as np
def count_pa... | 4,527 | 33.045113 | 155 | py |
ECG-removal-from-sEMG-by-FCN | ECG-removal-from-sEMG-by-FCN-main/main/util.py | import os,pdb,sys,math,librosa
import torch.nn.functional as F
import torch
import torch.nn as nn
import numpy as np
from numpy.core.defchararray import find
from scipy import signal
import scipy.optimize as spo
from scipy.stats.stats import pearsonr
def check_path(path):
# Check if path directory exists. If not,... | 5,726 | 30.467033 | 131 | py |
ECG-removal-from-sEMG-by-FCN | ECG-removal-from-sEMG-by-FCN-main/main/Trainer.py | import torch.nn as nn
import torch.nn.functional as F
import torch
#import mkl
import os, sys, time, numpy as np, pandas as pd,pdb
from tqdm import tqdm
from scipy import signal
from util import *
from TS import *
class Trainer:
def __init__(self, model, epochs, epoch, best_loss, optimizer,
... | 10,757 | 39.141791 | 171 | py |
ECG-removal-from-sEMG-by-FCN | ECG-removal-from-sEMG-by-FCN-main/main/model/FCN.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import time
import math
# import sru
device = torch.device('cuda:0')
class Dense_L(nn.Module):
def __init__(self, in_size, out_size,bias=True):
super().__init__()
self.dense = nn.Sequential(
nn.Line... | 2,407 | 27 | 115 | py |
Sentiment-Analysis-by-Capsules | Sentiment-Analysis-by-Capsules-master/Model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import config
class RNNCapsule(nn.Module):
def __init__(self, input_dim=512, capsule_num=config.classes):
super(RNNCapsule, self).__init__()
self.W_alpha = nn.Parameter(torch.randn(input_dim, capsule_num))
self.linear = nn... | 1,894 | 29.564516 | 91 | py |
Sentiment-Analysis-by-Capsules | Sentiment-Analysis-by-Capsules-master/Train.py | from torchtext import data
from nlp_pre.seq2classes_data import seq2classesData
from nlp_pre.config import DEVICE
import torch.nn.functional as F
import torch
from Model import Model
import spacy
from nltk.corpus import stopwords
from nlp_pre.TrainModel import train
en = spacy.load('en')
def tokenize_en(sent):
... | 1,840 | 27.323077 | 99 | py |
Sentiment-Analysis-by-Capsules | Sentiment-Analysis-by-Capsules-master/nlp_pre/seq2classes_data.py | import torchtext
from nlp_pre.seq2seq_data import seq2seqData
from torchtext.data import Field, BucketIterator, TabularDataset
from torchtext import data, datasets
from torch.nn import init
from nlp_pre import config
import dill
import os
import torch
# self.INPUT_TEXT = data.Field(batch_first=True, sequential=True, t... | 2,076 | 36.089286 | 131 | py |
Sentiment-Analysis-by-Capsules | Sentiment-Analysis-by-Capsules-master/nlp_pre/config.py | import torch
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
BATCH_SIZE = 64 | 100 | 19.2 | 69 | py |
Sentiment-Analysis-by-Capsules | Sentiment-Analysis-by-Capsules-master/nlp_pre/TrainModel.py | import torch.optim as optim
import numpy as np
import os
import torch
def train(train_iter, val_iter, test_iter, model, runModel, n_epoch=30, lr=0.00001, print_val_every_num=20):
if os.path.exists('params.pkl'):
model.load_state_dict(torch.load('params.pkl'))
optimizer = optim.Adam(model.parameters()... | 1,747 | 30.781818 | 108 | py |
Sentiment-Analysis-by-Capsules | Sentiment-Analysis-by-Capsules-master/nlp_pre/seq2seq_data.py | import torchtext
from torchtext.data import Field, BucketIterator, TabularDataset
from torchtext import data, datasets
from torch.nn import init
import dill
import os
from nlp_pre import config
# self.INPUT_TEXT = Field(batch_first=True, tokenize=in_tokenize, lower=True)
# self.OUTPUT_TEXT = Field(batch_first=True, to... | 6,758 | 40.722222 | 119 | py |
E-NeRV | E-NeRV-main/main.py | import argparse
import json
import random
from pathlib import Path
from datetime import datetime
import os
from model import model_dict
from datasets import dataset_dict
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.optim as optim
from torch.utils.data import DataLoader, Rando... | 6,610 | 41.928571 | 138 | py |
E-NeRV | E-NeRV-main/engine.py | import math
import os
import sys
import torch
import utils.misc as utils
import torch.nn.functional as F
from datetime import datetime
def train_one_epoch(
model,
dataloader,
optimizer,
device,
epoch,
cfg,
args,
datasize,
start_time,
writer=None,
):
model.train()
epoch_... | 7,388 | 36.130653 | 110 | py |
E-NeRV | E-NeRV-main/datasets/dataset.py | import os
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
class CustomDataSet(Dataset):
def __init__(self, main_dir, transform, train=True):
self.main_dir = main_dir
self.transform = transform
frame_idx, self.frame_path = [], []
accum_img_n... | 1,818 | 32.072727 | 110 | py |
E-NeRV | E-NeRV-main/utils/misc.py | import os
import subprocess
import yaml
import random
import math
import time
import argparse
import numpy as np
import torch.distributed as dist
import torch
import torch.nn.functional as F
from collections import defaultdict
from pytorch_msssim import ms_ssim, ssim
from tqdm import tqdm
def setup_for_distributed(is... | 9,319 | 33.776119 | 138 | py |
E-NeRV | E-NeRV-main/model/model_utils.py | from tkinter.messagebox import NO
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
class PositionalEncoding(nn.Module):
def __init__(self, pe_embed_b, pe_embed_l):
super(PositionalEncoding, self).__init__()
if pe_embed_b == 0:
self.embed... | 3,838 | 29.228346 | 137 | py |
E-NeRV | E-NeRV-main/model/NeRV.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .model_utils import ActivationLayer, NormLayer, PositionalEncoding
def NeRV_MLP(dim_list, act='relu', bias=True):
act_fn = ActivationLayer(act)
fc_list = []
for i in range(len(dim_list) - 1):
fc_list += [nn.Linear(dim_list[i],... | 5,323 | 40.92126 | 146 | py |
E-NeRV | E-NeRV-main/model/E_NeRV.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import torch.distributions as dist
from .model_utils import ActivationLayer, NormLayer, PositionalEncoding, gradient
from .NeRV import NeRV_MLP, NeRVBlock, Conv_Up_Block
from einops import rearrange
class PreNorm(nn.Module):
def __init_... | 8,559 | 37.909091 | 170 | py |
WGAN-GP-tensorflow | WGAN-GP-tensorflow-master/src/dataset_.py | # ---------------------------------------------------------
# Tensorflow WGAN-GP Implementation
# Licensed under The MIT License [see LICENSE for details]
# Written by Cheng-Bin Jin
# Email: sbkim0407@gmail.com
# ---------------------------------------------------------
import os
import logging
import numpy as np
impor... | 5,811 | 36.986928 | 102 | py |
ng | ng-main/getInit.py | import jax
import jax.numpy as jnp
import numpy as np
from functools import partial
from jax import jit, grad
from solvers import adam
def getInit(mode, prob, dnn, ops, initBatchSize, initNrIter, initH, getInitAZ, initFname, nrReplicates, key):
'''Train network on initial condition
Inputs:
mode ... | 4,984 | 48.356436 | 433 | py |
ng | ng-main/testpyNG.py | import jax
from jax import grad, jit, vmap
import jax.numpy as jnp
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import argparse
from timeit import default_timer as timer
from datetime import datetime
import re
# debug
# from timeit import default_timer as timer
# im... | 11,012 | 53.251232 | 529 | py |
ng | ng-main/DNN.py | import jax
from jax import grad, jit, vmap
import jax.numpy as jnp
import numpy as np
from functools import partial
class DNN:
# unitName, number of units per layer and number of hidden layers, number of inputs
def __init__(self, unitName, N, M, p, Omega):
curUfunScalarDXDXX = None
self.unitfu... | 10,330 | 44.915556 | 264 | py |
ng | ng-main/Problem.py | import jax
from jax import grad, jit, vmap
import jax.numpy as jnp
from jax import random
import numpy as np
from scipy import special
import scipy
from jax.ops import index, index_add, index_update
from matplotlib import cm
from functools import partial
import math
from solvers import exactKdV, fpesolver
from misc im... | 11,034 | 45.957447 | 369 | py |
ng | ng-main/misc/pyngplot.py | import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.ticker import FormatStrFormatter
from matplotlib import cm
import matplotlib.tri as tri
import numpy as np
import os
def doAnimationdD(plotGrid, Ufun, FDxGrid, UbenchmarkFun, tTimes, Omega,... | 27,296 | 47.398936 | 260 | py |
ng | ng-main/misc/pyngtools.py | import jax.numpy as jnp
import math
import jax
def mvnpdfFull(X, meanAndCovList = None, unnormalize = False):
dim = meanAndCovList[0].shape[0]
# if we get a list of means and cov then iterate over them and return a 2d array of evals
if(len(meanAndCovList[0].shape) > 1):
return jax.vmap(lambda i: mv... | 2,231 | 52.142857 | 253 | py |
ng | ng-main/solvers/exactKdV.py | import jax
import jax.numpy as jnp
from jax.ops import index, index_add, index_update
def exactKdVTwoSol(x, t):
'''
Same setup as in https://doi.org/10.1016/0021-9991(84)90004-4
Analytical and numerical aspects of certain nonlinear evolution equations. III. Numerical, Korteweg-de Vries equation
Thiab ... | 1,264 | 39.806452 | 131 | py |
ng | ng-main/solvers/timeODE.py | import jax
import jax.numpy as jnp
import numpy as np
from jax import random
from jax import jit, grad
from functools import partial
# from jax.ops import index, index_add, index_update
from solvers.adam import adamupdate
from datetime import datetime
from scipy import optimize
from scipy import integrate
from timeit ... | 5,134 | 40.41129 | 308 | py |
ng | ng-main/solvers/adam.py | import jax
import jax.numpy as jnp
from functools import partial
from timeit import default_timer as timer
def adam(gradFun, sampleFun, h, nrIter, x, key, printETA = 0, returnBest = 0):
'''Adam solver:
Inputs:
gradFun ... gradient
sampleFun ... data sampling
... | 2,626 | 35.486111 | 263 | py |
ng | ng-main/solvers/timeSGD.py | import jax
import jax.numpy as jnp
import numpy as np
from jax import random
from jax import jit, grad
from functools import partial
# from jax.ops import index, index_add, index_update
from solvers.adam import adamupdate
from datetime import datetime
from scipy import optimize
from timeit import default_timer as time... | 6,551 | 42.68 | 387 | py |
ng | ng-main/solvers/fpesolver.py | import jax.numpy as jnp
from jax import jit, vmap
from scipy import optimize
from scipy import integrate
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def fpsolverddd(x):
'''Computes y_i = \sum_{j = 1}^m (x_i - x_j) for i = 1, \dots, m'''
return jnp.sum(- jnp.atleast_2d(x) + jn... | 1,731 | 38.363636 | 235 | py |
ng | ng-main/ops/OpsParticleTrap.py | import jax
from jax import grad, jit, vmap, jvp, value_and_grad
import jax.numpy as jnp
from functools import partial
class OpsParticleTrap:
def __init__(self, prob, dnn, scheme, modeName):
self.prob = prob # problem
self.dnn = dnn
self.modeName = modeName
# check if dnn satisifies... | 2,306 | 43.365385 | 203 | py |
ng | ng-main/ops/OpsKdV.py | import jax
from jax import grad, jit, vmap, value_and_grad, jvp
import jax.numpy as jnp
from functools import partial
class OpsKdV:
def __init__(self, prob, dnn, scheme, modeName):
self.prob = prob # problem
self.dnn = dnn
self.modeName = modeName
# check if dnn satisifies boundary... | 2,457 | 36.815385 | 146 | py |
ng | ng-main/ops/OpsAdv.py | import jax
from jax import grad, jit, vmap, jvp, value_and_grad
import jax.numpy as jnp
from functools import partial
class OpsAdv:
def __init__(self, prob, dnn, scheme, modeName):
self.prob = prob # problem
self.dnn = dnn
self.modeName = modeName
# check if dnn satisifies boundary... | 1,353 | 32.85 | 108 | py |
AGKD-BML | AGKD-BML-main/main.py | '''Train CIFAR10 with PyTorch.'''
from __future__ import print_function
from __future__ import division
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torchvision
import torchvision... | 14,005 | 37.478022 | 123 | py |
AGKD-BML | AGKD-BML-main/utils.py | import os
import torch
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision
import torchvision.transforms as transforms
import numpy as np
import random
from argument import parser, print_args, create_logger
def softmax_crossentropy_labelsmooth(pre... | 5,411 | 37.657143 | 138 | py |
AGKD-BML | AGKD-BML-main/custom_models/model.py | # codes are import from https://github.com/xternalz/WideResNet-pytorch/blob/master/wideresnet.py
# original author: xternalz
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(Ba... | 4,976 | 38.5 | 116 | py |
MAVEN | MAVEN-master/maven_code/src/main.py | import numpy as np
import os
import collections
from os.path import dirname, abspath
from copy import deepcopy
from sacred import Experiment, SETTINGS
from sacred.observers import FileStorageObserver
from sacred.utils import apply_backspaces_and_linefeeds
import sys
import torch as th
from utils.logging import get_logg... | 2,709 | 29.449438 | 121 | py |
MAVEN | MAVEN-master/maven_code/src/run.py | import datetime
import os
import pprint
import time
import threading
import torch as th
from types import SimpleNamespace as SN
from utils.logging import Logger
from utils.timehelper import time_left, time_str
from os.path import dirname, abspath
from learners import REGISTRY as le_REGISTRY
from runners import REGISTR... | 8,050 | 33.405983 | 116 | py |
MAVEN | MAVEN-master/maven_code/src/modules/mixers/qmix.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class QMixer(nn.Module):
def __init__(self, args):
super(QMixer, self).__init__()
self.args = args
self.n_agents = args.n_agents
self.state_dim = int(np.prod(args.state_shape))
sel... | 2,603 | 38.454545 | 100 | py |
MAVEN | MAVEN-master/maven_code/src/modules/mixers/vdn.py | import torch as th
import torch.nn as nn
class VDNMixer(nn.Module):
def __init__(self):
super(VDNMixer, self).__init__()
def forward(self, agent_qs, batch):
return th.sum(agent_qs, dim=2, keepdim=True) | 228 | 21.9 | 52 | py |
MAVEN | MAVEN-master/maven_code/src/modules/mixers/noise_mix.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class QMixer(nn.Module):
def __init__(self, args):
super(QMixer, self).__init__()
self.args = args
self.n_agents = args.n_agents
self.state_dim = int(np.prod(args.state_shape)) + args.noise... | 2,676 | 38.955224 | 100 | py |
MAVEN | MAVEN-master/maven_code/src/modules/mixers/qtran.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class QTran(nn.Module):
def __init__(self, args):
super(QTran, self).__init__()
self.args = args
self.n_agents = args.n_agents
self.n_actions = args.n_actions
self.state_dim = int(... | 3,137 | 40.84 | 133 | py |
MAVEN | MAVEN-master/maven_code/src/modules/agents/rnn_agent.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
class RNNAgent(nn.Module):
def __init__(self, input_shape, args):
super(RNNAgent, self).__init__()
self.args = args
self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)
self.rnn = nn.GRUCell(args.rnn_hidden_... | 788 | 31.875 | 71 | py |
MAVEN | MAVEN-master/maven_code/src/modules/agents/ff_agent.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
class FFAgent(nn.Module):
def __init__(self, input_shape, args):
super(FFAgent, self).__init__()
self.args = args
self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)
self.fc2 = nn.Linear(args.rnn_hidden_dim... | 721 | 30.391304 | 71 | py |
MAVEN | MAVEN-master/maven_code/src/modules/agents/noise_rnn_agent.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
class RNNAgent(nn.Module):
def __init__(self, input_shape, args):
super(RNNAgent, self).__init__()
self.args = args
self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)
self.rnn = nn.GRUCell(args.rnn_hidden_... | 1,793 | 37.170213 | 110 | py |
MAVEN | MAVEN-master/maven_code/src/modules/bandits/const_lr.py | import numpy as np
import torch as th
class Constant_Lr:
def __init__(self, args):
self.args = args
self.lr = args.noise_bandit_lr
self.returns = [0 for _ in range(self.args.noise_dim)]
self.epsilon = args.noise_bandit_epsilon
self.noise_dim = self.args.noise_dim
def ... | 1,276 | 32.605263 | 92 | py |
MAVEN | MAVEN-master/maven_code/src/modules/bandits/uniform.py | import torch as th
class Uniform:
def __init__(self, args):
self.args = args
self.noise_distrib = th.distributions.one_hot_categorical.OneHotCategorical(th.tensor([1/self.args.noise_dim for _ in range(self.args.noise_dim)]).repeat(self.args.batch_size_run, 1))
def sample(self, state, test_mo... | 448 | 31.071429 | 191 | py |
MAVEN | MAVEN-master/maven_code/src/modules/bandits/reinforce_hierarchial.py | # Categorical policy for discrete z
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from collections import deque
class Policy(nn.Module):
def __init__(self, args):
super(Policy, self).__init__()
self.args = args
self.affin... | 4,143 | 35.672566 | 199 | py |
MAVEN | MAVEN-master/maven_code/src/modules/bandits/returns_bandit.py | # Categorical policy for discrete z
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from collections import deque
import numpy as np
class Net(nn.Module):
def __init__(self, args):
super(Net, self).__init__()
self.args = args
self.affine1 = n... | 3,822 | 38.010204 | 197 | py |
MAVEN | MAVEN-master/maven_code/src/modules/critics/centralV.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
class CentralVCritic(nn.Module):
def __init__(self, scheme, args):
super(CentralVCritic, self).__init__()
self.args = args
self.n_actions = args.n_actions
self.n_agents = args.n_agents
input_shape = ... | 2,089 | 33.833333 | 123 | py |
MAVEN | MAVEN-master/maven_code/src/modules/critics/coma.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
class COMACritic(nn.Module):
def __init__(self, scheme, args):
super(COMACritic, self).__init__()
self.args = args
self.n_actions = args.n_actions
self.n_agents = args.n_agents
input_shape = self._ge... | 3,288 | 36.804598 | 127 | py |
MAVEN | MAVEN-master/maven_code/src/components/episode_buffer.py | import torch as th
import numpy as np
from types import SimpleNamespace as SN
class EpisodeBatch:
def __init__(self,
scheme,
groups,
batch_size,
max_seq_length,
data=None,
preprocess=None,
device... | 12,290 | 39.564356 | 134 | py |
MAVEN | MAVEN-master/maven_code/src/components/action_selectors.py | import numpy as np
import torch as th
from torch.autograd import Variable
from torch.distributions import Categorical
from torch.nn.functional import softmax
from .epsilon_schedules import DecayThenFlatSchedule
REGISTRY = {}
class MultinomialActionSelector():
def __init__(self, args):
self.args = args
... | 2,269 | 33.923077 | 128 | py |
MAVEN | MAVEN-master/maven_code/src/components/transforms.py | import numpy as np
import torch as th
class Transform:
def transform(self, tensor):
raise NotImplementedError
def infer_output_info(self, vshape_in, dtype_in):
raise NotImplementedError
class OneHot(Transform):
def __init__(self, out_dim):
self.out_dim = out_dim
def transform... | 586 | 25.681818 | 71 | py |
MAVEN | MAVEN-master/maven_code/src/runners/parallel_runner.py | from envs import REGISTRY as env_REGISTRY
from functools import partial
from components.episode_buffer import EpisodeBatch
from multiprocessing import Pipe, Process
import numpy as np
import torch as th
from modules.bandits.const_lr import Constant_Lr
from modules.bandits.uniform import Uniform
from modules.bandits.rei... | 14,449 | 38.266304 | 147 | py |
MAVEN | MAVEN-master/maven_code/src/controllers/basic_controller.py | from modules.agents import REGISTRY as agent_REGISTRY
from components.action_selectors import REGISTRY as action_REGISTRY
import torch as th
# This multi-agent controller shares parameters between agents
class BasicMAC:
def __init__(self, scheme, groups, args):
self.n_agents = args.n_agents
self.a... | 4,350 | 42.079208 | 125 | py |
MAVEN | MAVEN-master/maven_code/src/controllers/noise_controller.py | from modules.agents import REGISTRY as agent_REGISTRY
from components.action_selectors import REGISTRY as action_REGISTRY
import torch as th
# This multi-agent controller shares parameters between agents
class NoiseMAC:
def __init__(self, scheme, groups, args):
self.n_agents = args.n_agents
self.a... | 4,411 | 42.254902 | 125 | py |
MAVEN | MAVEN-master/maven_code/src/utils/rl_utils.py | import torch as th
def build_td_lambda_targets__old(rewards, terminated, mask, target_qs, n_agents, gamma, td_lambda):
bs = rewards.size(0)
max_t = rewards.size(1)
targets = rewards.new(target_qs.size()).zero_()[:,:-1] # Produce 1 less target than the inputted Q-Values
running_target = rewards.new(bs,... | 1,665 | 48 | 134 | py |
MAVEN | MAVEN-master/maven_code/src/learners/coma_learner.py | import copy
from components.episode_buffer import EpisodeBatch
from modules.critics.coma import COMACritic
from utils.rl_utils import build_td_lambda_targets
import torch as th
from torch.optim import RMSprop
class COMALearner:
def __init__(self, mac, scheme, logger, args):
self.args = args
self.n... | 7,395 | 42.505882 | 136 | py |
MAVEN | MAVEN-master/maven_code/src/learners/qtran_learner.py | import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.qtran import QTran as QTranAlt
import torch as th
from torch.optim import RMSprop
class QLearner:
def __init__(self, mac, scheme, logger, args):
self.args = args
self.mac = mac
self.logger = logger
... | 8,218 | 48.512048 | 193 | py |
MAVEN | MAVEN-master/maven_code/src/learners/noise_q_learner.py | import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.vdn import VDNMixer
from modules.mixers.qmix import QMixer
from modules.mixers.noise_mix import QMixer as NoiseQMixer
import torch as th
from torch.optim import RMSprop
import numpy as np
class QLearner:
def __init__(self, mac, sch... | 9,978 | 40.406639 | 132 | py |
MAVEN | MAVEN-master/maven_code/src/learners/actor_critic_learner.py | import copy
from components.episode_buffer import EpisodeBatch
from modules.critics.coma import COMACritic
from modules.critics.centralV import CentralVCritic
from utils.rl_utils import build_td_lambda_targets
import torch as th
from torch.optim import RMSprop
class ActorCriticLearner:
def __init__(self, mac, sch... | 13,332 | 41.461783 | 127 | py |
MAVEN | MAVEN-master/maven_code/src/learners/q_learner.py | import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.vdn import VDNMixer
from modules.mixers.qmix import QMixer
import torch as th
from torch.optim import RMSprop
class QLearner:
def __init__(self, mac, scheme, logger, args):
self.args = args
self.mac = mac
se... | 5,773 | 39.950355 | 132 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.