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 |
|---|---|---|---|---|---|---|
P3O | P3O-main/baselines/clip/defaults.py | def mujoco():
return dict(
nsteps=4096,
nminibatches=4096,
lam=0.95,
gamma=0.99,
noptepochs=5,
log_interval=1,
ent_coef=0.0,
lr=lambda f: 1e-4*f,
cliprange=0.2,
value_network='copy'
)
def mujoco_bak():
return dict(
nste... | 1,006 | 19.979167 | 59 | py |
P3O | P3O-main/baselines/clip/runner.py | import numpy as np
from baselines.common.runners import AbstractEnvRunner
class Runner(AbstractEnvRunner):
"""
We use this object to make a mini batch of experiences
__init__:
- Initialize the runner
run():
- Make a mini batch
"""
def __init__(self, *, env, model, nsteps, gamma, lam):
... | 3,194 | 40.493506 | 109 | py |
P3O | P3O-main/baselines/clip/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/baselines/ppo2/ppo2.py | import os
import time
import numpy as np
import os.path as osp
from baselines import logger
from collections import deque
from baselines.common import explained_variance, set_global_seeds
from baselines.common.policies import build_policy
try:
from mpi4py import MPI
except ImportError:
MPI = None
from baselines... | 10,238 | 44.506667 | 184 | py |
P3O | P3O-main/baselines/ppo2/microbatched_model.py | import tensorflow as tf
import numpy as np
from baselines.ppo2.model import Model
class MicrobatchedModel(Model):
"""
Model that does training one microbatch at a time - when gradient computation
on the entire minibatch causes some overflow
"""
def __init__(self, *, policy, ob_space, ac_space, nbat... | 3,241 | 40.037975 | 151 | py |
P3O | P3O-main/baselines/ppo2/test_microbatches.py | import gym
import tensorflow as tf
import numpy as np
from functools import partial
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
from baselines.common.tf_util import make_session
from baselines.ppo2.ppo2 import learn
from baselines.ppo2.microbatched_model import MicrobatchedModel
def test_microbatc... | 1,152 | 31.027778 | 83 | py |
P3O | P3O-main/baselines/ppo2/model.py | import tensorflow as tf
import functools
from baselines.common.tf_util import get_session, save_variables, load_variables
from baselines.common.tf_util import initialize
try:
from baselines.common.mpi_adam_optimizer import MpiAdamOptimizer
from mpi4py import MPI
from baselines.common.mpi_util import sync_... | 6,621 | 37.725146 | 133 | py |
P3O | P3O-main/baselines/ppo2/defaults.py | def mujoco():
return dict(
nsteps=2048,
nminibatches=32,
lam=0.95,
gamma=0.99,
noptepochs=10,
log_interval=1,
ent_coef=0.0,
lr=lambda f: 3e-4*f,
cliprange=0.2,
value_network='copy'
)
def atari():
return dict(
nsteps=128... | 516 | 18.884615 | 59 | py |
P3O | P3O-main/baselines/ppo2/runner.py | import numpy as np
from baselines.common.runners import AbstractEnvRunner
class Runner(AbstractEnvRunner):
"""
We use this object to make a mini batch of experiences
__init__:
- Initialize the runner
run():
- Make a mini batch
"""
def __init__(self, *, env, model, nsteps, gamma, lam):
... | 3,194 | 40.493506 | 109 | py |
P3O | P3O-main/baselines/ppo2/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/baselines/p3o/model.py | import tensorflow as tf
import functools
from baselines.common.tf_util import get_session, save_variables, load_variables
from baselines.common.tf_util import initialize
from baselines.common.input import observation_placeholder
try:
from baselines.common.mpi_adam_optimizer import MpiAdamOptimizer
from mpi4py ... | 7,668 | 38.942708 | 133 | py |
P3O | P3O-main/baselines/p3o/defaults.py | def mujoco():
return dict(
nsteps=2048,
nminibatches=32,
lam=0.95,
gamma=0.99,
noptepochs=10,
log_interval=1,
ent_coef=0.01,
kl_coef=0.05,
lr=lambda f: 3e-4*f,
cliprange=0.2,
value_network='copy'
#random seed 4
)
def... | 1,291 | 19.507937 | 59 | py |
P3O | P3O-main/baselines/p3o/runner.py | import numpy as np
from baselines.common.runners import AbstractEnvRunner
class Runner(AbstractEnvRunner):
"""
We use this object to make a mini batch of experiences
__init__:
- Initialize the runner
run():
- Make a mini batch
"""
def __init__(self, *, env, model, nsteps, gamma, lam):
... | 3,255 | 40.21519 | 109 | py |
P3O | P3O-main/baselines/p3o/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/baselines/p3o/p3o.py | import os
import random
import time
import numpy as np
import os.path as osp
from baselines import logger
from collections import deque
from baselines.common import explained_variance, set_global_seeds
from baselines.common.policies import build_policy
try:
from mpi4py import MPI
except ImportError:
MPI = None
... | 10,223 | 42.692308 | 184 | py |
P3O | P3O-main/baselines/a2c/a2c.py | import time
import functools
import tensorflow as tf
from baselines import logger
from baselines.common import set_global_seeds, explained_variance
from baselines.common import tf_util
from baselines.common.policies import build_policy
from baselines.a2c.utils import Scheduler, find_trainable_variables
from baselin... | 9,451 | 39.566524 | 186 | py |
P3O | P3O-main/baselines/a2c/utils.py | import os
import numpy as np
import tensorflow as tf
from collections import deque
def sample(logits):
noise = tf.random_uniform(tf.shape(logits))
return tf.argmax(logits - tf.log(-tf.log(noise)), 1)
def cat_entropy(logits):
a0 = logits - tf.reduce_max(logits, 1, keepdims=True)
ea0 = tf.exp(a0)
z0... | 9,348 | 32.035336 | 107 | py |
P3O | P3O-main/baselines/a2c/runner.py | import numpy as np
from baselines.a2c.utils import discount_with_dones
from baselines.common.runners import AbstractEnvRunner
class Runner(AbstractEnvRunner):
"""
We use this class to generate batches of experiences
__init__:
- Initialize the runner
run():
- Make a mini batch of experiences
... | 3,241 | 41.103896 | 112 | py |
P3O | P3O-main/baselines/a2c/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/baselines/test/test.py | import os
import random
import time
import numpy as np
import os.path as osp
from baselines import logger
from collections import deque
from baselines.common import explained_variance, set_global_seeds
from baselines.common.policies import build_policy
try:
from mpi4py import MPI
except ImportError:
MPI = None
... | 10,621 | 42.532787 | 184 | py |
P3O | P3O-main/baselines/test/model.py | import tensorflow as tf
import functools
from baselines.common.tf_util import get_session, save_variables, load_variables
from baselines.common.tf_util import initialize
from baselines.common.input import observation_placeholder
try:
from baselines.common.mpi_adam_optimizer import MpiAdamOptimizer
from mpi4py ... | 7,188 | 37.650538 | 137 | py |
P3O | P3O-main/baselines/test/defaults.py | def mujoco():
return dict(
nsteps=2048,
nminibatches=32,
lam=0.95,
gamma=0.99,
noptepochs=10,
log_interval=1,
ent_coef=0.01,
kl_coef=0.05,
lr=lambda f: 3e-4*f,
cliprange=0.2,
value_network='copy',
squash=False
#q... | 1,304 | 19.390625 | 59 | py |
P3O | P3O-main/baselines/test/runner.py | import numpy as np
from baselines.common.runners import AbstractEnvRunner
class Runner(AbstractEnvRunner):
"""
We use this object to make a mini batch of experiences
__init__:
- Initialize the runner
run():
- Make a mini batch
"""
def __init__(self, *, env, model, nsteps, gamma, lam):
... | 3,255 | 40.21519 | 109 | py |
P3O | P3O-main/baselines/test/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/baselines/acktr/acktr.py | import os.path as osp
import time
import functools
import tensorflow as tf
from baselines import logger
from baselines.common import set_global_seeds, explained_variance
from baselines.common.policies import build_policy
from baselines.common.tf_util import get_session, save_variables, load_variables
from baselines.a... | 7,144 | 43.65625 | 131 | py |
P3O | P3O-main/baselines/acktr/kfac.py | import tensorflow as tf
import numpy as np
import re
# flake8: noqa F403, F405
from baselines.acktr.kfac_utils import *
from functools import reduce
KFAC_OPS = ['MatMul', 'Conv2D', 'BiasAdd']
KFAC_DEBUG = False
class KfacOptimizer():
# note that KfacOptimizer will be truly synchronous (and thus deterministic) ... | 45,679 | 48.171152 | 366 | py |
P3O | P3O-main/baselines/acktr/utils.py | import tensorflow as tf
def dense(x, size, name, weight_init=None, bias_init=0, weight_loss_dict=None, reuse=None):
with tf.variable_scope(name, reuse=reuse):
assert (len(tf.get_variable_scope().name.split('/')) == 2)
w = tf.get_variable("w", [x.get_shape()[1], size], initializer=weight_init)
... | 1,322 | 44.62069 | 107 | py |
P3O | P3O-main/baselines/acktr/defaults.py | def mujoco():
return dict(
nsteps=2500,
value_network='copy'
)
| 87 | 13.666667 | 28 | py |
P3O | P3O-main/baselines/acktr/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/baselines/acktr/kfac_utils.py | import tensorflow as tf
def gmatmul(a, b, transpose_a=False, transpose_b=False, reduce_dim=None):
assert reduce_dim is not None
# weird batch matmul
if len(a.get_shape()) == 2 and len(b.get_shape()) > 2:
# reshape reduce_dim to the left most dim in b
b_shape = b.get_shape()
if redu... | 3,389 | 37.965517 | 168 | py |
P3O | P3O-main/baselines/bench/test_monitor.py | from .monitor import Monitor
import gym
import json
def test_monitor():
import pandas
import os
import uuid
env = gym.make("CartPole-v1")
env.seed(0)
mon_file = "/tmp/baselines-test-%s.monitor.csv" % uuid.uuid4()
menv = Monitor(env, mon_file)
menv.reset()
for _ in range(1000):
... | 861 | 25.9375 | 95 | py |
P3O | P3O-main/baselines/bench/benchmarks.py | import re
import os
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
_atari7 = ['BeamRider', 'Breakout', 'Enduro', 'Pong', 'Qbert', 'Seaquest', 'SpaceInvaders']
_atariexpl7 = ['Freeway', 'Gravitar', 'MontezumaRevenge', 'Pitfall', 'PrivateEye', 'Solaris', 'Venture']
_BENCHMARKS = []
remove_version_re = re.comp... | 6,102 | 35.987879 | 129 | py |
P3O | P3O-main/baselines/bench/monitor.py | __all__ = ['Monitor', 'get_monitor_files', 'load_results']
from gym.core import Wrapper
import time
from glob import glob
import csv
import os.path as osp
import json
class Monitor(Wrapper):
EXT = "monitor.csv"
f = None
def __init__(self, env, filename, allow_early_resets=False, reset_keywords=(), info_k... | 5,762 | 33.927273 | 174 | py |
P3O | P3O-main/baselines/bench/__init__.py | # flake8: noqa F403
from baselines.bench.benchmarks import *
from baselines.bench.monitor import *
| 99 | 24 | 40 | py |
P3O | P3O-main/plot/plot_halfcheetah.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 8,410 | 32.376984 | 132 | py |
P3O | P3O-main/plot/plot_parameter_select_on_halfcheetah.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 8,950 | 32.777358 | 133 | py |
P3O | P3O-main/plot/plot_progress_kl_gradient_r.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 9,170 | 32.470803 | 132 | py |
P3O | P3O-main/plot/plot_halfcheetah_episode_lenth.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 8,368 | 32.079051 | 133 | py |
P3O | P3O-main/plot/plot_halfcheetah-hyper-parameter.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 8,582 | 32.138996 | 133 | py |
P3O | P3O-main/plot/plot_activatefunction.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
from baselines.common import plot_util
plt.style.use('seaborn')
rc_fonts = {
'lines.markeredgewidth': 1,
"lines.markersize":3,
"lin... | 8,934 | 32.844697 | 132 | py |
P3O | P3O-main/plot/plot_mulit_value_in_one_fig.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 8,651 | 31.283582 | 132 | py |
P3O | P3O-main/plot/plot_passivefunction.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
plt.style.use('seaborn')
rc_fonts = {
'lines.markeredgewidth': 1,
"lines.markersize":3,
"lines.linewidth":1,
'xtick.direction'... | 8,394 | 32.313492 | 132 | py |
P3O | P3O-main/plot/plot-marker.py | import matplotlib.pylab as plt
markers = ['.',',','o','v','^','<','>','1','2','3','4','8','s','p','P','*','h','H','+','x','X','D','d','|','_']
descriptions = ['point', 'pixel', 'circle', 'triangle_down', 'triangle_up','triangle_left',
'triangle_right', 'tri_down', 'tri_up', 'tri_left', 'tri_right', 'oc... | 819 | 27.275862 | 111 | py |
P3O | P3O-main/plot/plot_performence.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 8,322 | 32.292 | 132 | py |
P3O | P3O-main/plot/plot_para.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
plt.style.use('seaborn')
rc_fonts = {
'lines.markeredgewidth': 1,
"lines.markersize":3,
"lines.linewidth":1,
'xtick.direction'... | 8,756 | 32.94186 | 132 | py |
P3O | P3O-main/plot/plot_halfcheetah_batchsize.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 8,356 | 32.294821 | 133 | py |
P3O | P3O-main/plot/plot_test_marker.py | import matplotlib.pylab as plt
import numpy as np
fmts=['-.', '-*', '-1', '-|', '-_', ]
x = np.linspace(0,100,20)
y = np.ones_like(x)
for f in fmts:
plt.plot(x,y,f)
y += 1
plt.legend()
plt.show() | 207 | 13.857143 | 37 | py |
P3O | P3O-main/plot/plot_progress_loss_difference.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 8,967 | 32.33829 | 132 | py |
P3O | P3O-main/plot/plot_progress_kl_divergence.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict, namedtuple
from baselines.common.plot_util import smooth,symmetric_ema
import os
rc_fonts = {
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':10,
'ytick.labelsize':10,
"font... | 8,627 | 32.184615 | 132 | py |
P3O | P3O-main/plot/plot_ablation.py | import numpy as np
from collections import defaultdict
from baselines.common.plot_util import smooth,symmetric_ema
import matplotlib.pyplot as plt
from baselines.common import plot_util
import os
import matplotlib
import matplotlib.font_manager
# plt.style.use('seaborn')
rc_fonts = {
#8.5
# 'lines.markeredgewidth':... | 10,055 | 33.556701 | 132 | py |
P3O | P3O-main/plot/read_data.py | import numpy as np
from matplotlib import pyplot as plt
plt.style.use('seaborn')
rc_fonts = {
'lines.markeredgewidth': 1,
"lines.markersize":3,
"lines.linewidth":1,
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':8,
'ytick.labelsize':8,
"font.family": "times",
'ax... | 3,260 | 23.704545 | 88 | py |
P3O | P3O-main/analysis/hebing.py | with open('plot_data', 'r') as f:
data = eval(f.read())
with open('plot_data_lr_ctn', 'r') as f:
data2 = eval(f.read())
data.update(data2)
with open('plot_data_lr','w') as f:
f.write(str(data)) | 207 | 22.111111 | 40 | py |
P3O | P3O-main/analysis/analysisi.py | plot_data = {}
path = '/home/chenxing/Downloads/ss/sense_ana'
for env in ["Enduro", 'BeamRider', "Breakout"]:
lr_data = {}
for i in range(1,11):
lr = str(i/100.0)
res = 0
file_cont=0
for j in range(4):
with open(path+'/'+env+'/'+str(lr)+'_'+str(j)+'/0.0.monitor.csv', ... | 1,105 | 31.529412 | 88 | py |
P3O | P3O-main/analysis/plot_analysis.py | with open('plot_data_lr', 'r') as f:
data = eval(f.read())
from matplotlib import pyplot as plt
import matplotlib
import numpy as np
plt.style.use('seaborn')
rc_fonts = {
'lines.markeredgewidth': 1,
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.labelsize':12,
'ytick.labelsize':12,
... | 2,067 | 30.333333 | 124 | py |
P3O | P3O-main/analysis/main_dst.py | import os
import sys
from subprocess import Popen, PIPE, STDOUT, DEVNULL
import time
def run():
curenv = os.environ.copy()
cmds = []
curenv['PYTHONPATH'] = "/home/chenxing/workspace/baselines"
curenv['CUDA_VISIBLE_DEVICES'] = "0,1"
# curenv['LD_LIBRARY_PATH'] = "$LD_LIBRARY_PATH:/home/chenxing/.muj... | 1,507 | 31.085106 | 98 | py |
DeepForcedAligner | DeepForcedAligner-main/scratch_pred.py | import argparse
import numpy as np
import torch
from dfa.audio import Audio
from dfa.duration_extraction import extract_durations_with_dijkstra, extract_durations_beam
from dfa.model import Aligner
from dfa.text import Tokenizer
from dfa.utils import read_metafile
from dfa.utils import read_config
from dfa.paths impo... | 2,103 | 34.661017 | 103 | py |
DeepForcedAligner | DeepForcedAligner-main/extract_durations.py | import argparse
from multiprocessing import cpu_count
from multiprocessing.pool import Pool
from pathlib import Path
from typing import Tuple
import numpy as np
import torch
import tqdm
from dfa.dataset import new_dataloader
from dfa.duration_extraction import extract_durations_with_dijkstra, extract_durations_beam
f... | 4,546 | 45.397959 | 111 | py |
DeepForcedAligner | DeepForcedAligner-main/train.py | import argparse
import torch
from torch import optim
from dfa.model import Aligner
from dfa.paths import Paths
from dfa.utils import read_config, unpickle_binary
from trainer import Trainer
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Preprocessing for DeepForcedAligner.')
parser.a... | 2,128 | 45.282609 | 107 | py |
DeepForcedAligner | DeepForcedAligner-main/preprocess.py | import argparse
from multiprocessing import cpu_count
from multiprocessing.pool import Pool
from pathlib import Path
from typing import Dict, Union
import numpy as np
import tqdm
from dfa.audio import Audio
from dfa.paths import Paths
from dfa.text import Tokenizer
from dfa.utils import get_files, read_config, pickle... | 3,446 | 39.081395 | 105 | py |
DeepForcedAligner | DeepForcedAligner-main/trainer.py | import numpy as np
import torch
import tqdm
from torch.nn import CTCLoss
from torch.optim import Adam
from torch.utils.tensorboard import SummaryWriter
from dfa.dataset import new_dataloader, get_longest_mel_id
from dfa.duration_extraction import extract_durations_with_dijkstra
from dfa.model import Aligner
from dfa.p... | 4,759 | 45.666667 | 113 | py |
DeepForcedAligner | DeepForcedAligner-main/dfa/utils.py | import pickle
import os
from pathlib import Path
from typing import Dict, List, Any, Union
import torch
import yaml
def read_metafile(path: str, folder, dur_path) -> Dict[str, str]:
text_dict = {}
txt_files = []
audio_files = []
print(path)
for filename in os.listdir(folder):
if filename.... | 2,358 | 33.188406 | 93 | py |
DeepForcedAligner | DeepForcedAligner-main/dfa/duration_extraction.py | import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import dijkstra
def to_node_index(i, j, cols):
return cols * i + j
def from_node_index(node_index, cols):
return node_index // cols, node_index % cols
def to_adj_matrix(mat):
rows = mat.shape[0]
cols = mat.shape[1]
... | 3,448 | 30.642202 | 92 | py |
DeepForcedAligner | DeepForcedAligner-main/dfa/audio.py | import librosa
import numpy as np
class Audio:
"""Performs audio processing such as generating mel specs and normalization."""
def __init__(self,
n_mels: int,
sample_rate: int,
hop_length: int,
win_length: int,
n_filters... | 1,783 | 26.875 | 83 | py |
DeepForcedAligner | DeepForcedAligner-main/dfa/model.py | import torch
import torch.nn as nn
class BatchNormConv(nn.Module):
def __init__(self, in_channels: int, out_channels: int, kernel_size: int):
super().__init__()
self.conv = nn.Conv1d(
in_channels, out_channels, kernel_size,
stride=1, padding=kernel_size // 2, bias=False)
... | 1,868 | 29.639344 | 90 | py |
DeepForcedAligner | DeepForcedAligner-main/dfa/dataset.py | from pathlib import Path
from random import Random
from typing import List
import numpy as np
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
from torch.utils.data.sampler import Sampler
from dfa.utils import unpi... | 3,653 | 36.670103 | 93 | py |
DeepForcedAligner | DeepForcedAligner-main/dfa/text.py | from typing import List
class Tokenizer:
def __init__(self, symbols: List[str], pad_token='_') -> None:
self.symbols = symbols
self.pad_token = pad_token
self.idx_to_token = {i: s for i, s in enumerate(symbols, start=1)}
self.idx_to_token[0] = pad_token
self.token_to_idx =... | 693 | 33.7 | 100 | py |
DeepForcedAligner | DeepForcedAligner-main/dfa/__init__.py | 0 | 0 | 0 | py | |
DeepForcedAligner | DeepForcedAligner-main/dfa/paths.py | from pathlib import Path
class Paths:
def __init__(self, data_dir: str, checkpoint_dir: str, dataset_dir: str, precomputed_mels: str, metadata_path: str, actual_dur_path):
self.data_dir = Path(data_dir)
self.dataset_dir = dataset_dir
self.metadata_path = Path(metadata_path)
se... | 1,361 | 37.914286 | 137 | py |
EDGE | EDGE-master/EDGE.py | #######################################################
# #
# Calculation of electron spectra, #
# gamma-ray spectra and electrons #
# flux at the Earth for different #
# initial parameters ... | 58,240 | 51.375 | 270 | py |
EDGE | EDGE-master/tests/test_sample.py | import edge
# Run EDGE tests
| 30 | 6.75 | 16 | py |
EDGE | EDGE-master/Science_paper/EDGE_Science_paper.py | #######################################################
# #
# Calculation of electron spectra, #
# gamma-ray spectra and electrons #
# flux at the Earth for different #
# initial parameters ... | 55,889 | 51.726415 | 270 | py |
DoSA | DoSA-main/generate_annotations.py | import os
print("Warning:Installing tesseract on machine")
os.system('apt-get install tesseract-ocr -y')
print("tesseract should be installed")
import time
from transformers import LayoutLMv3Processor, LayoutLMv3ForTokenClassification, LayoutLMv3FeatureExtractor
from datasets import load_dataset
from PIL import Image,... | 6,655 | 28.065502 | 124 | py |
trx | trx-main/video_reader.py | import torch
from torchvision import datasets, transforms
from PIL import Image
import os
import zipfile
import io
import numpy as np
import random
import re
import pickle
from glob import glob
from videotransforms.video_transforms import Compose, Resize, RandomCrop, RandomRotation, ColorJitter, RandomHorizontalFlip, ... | 12,944 | 36.850877 | 207 | py |
trx | trx-main/utils.py | import torch
import torch.nn.functional as F
import os
import math
from enum import Enum
import sys
class TestAccuracies:
"""
Determines if an evaluation on the validation set is better than the best so far.
In particular, this handles the case for meta-dataset where we validate on multiple datasets and w... | 6,529 | 37.639053 | 126 | py |
trx | trx-main/model.py | import torch
import torch.nn as nn
from collections import OrderedDict
from utils import split_first_dim_linear
import math
from itertools import combinations
from torch.autograd import Variable
import torchvision.models as models
NUM_SAMPLES=1
class PositionalEncoding(nn.Module):
"Implement the PE function."
... | 9,264 | 38.935345 | 140 | py |
trx | trx-main/run.py | import torch
import numpy as np
import argparse
import os
import pickle
from utils import print_and_log, get_log_files, TestAccuracies, loss, aggregate_accuracy, verify_checkpoint_dir, task_confusion
from model import CNN_TRX
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Quiet TensorFlow warnings
import tensorflow as tf
... | 13,447 | 47.901818 | 168 | py |
trx | trx-main/videotransforms/stack_transforms.py | import numpy as np
import PIL
import torch
from videotransforms.utils import images as imageutils
class ToStackedTensor(object):
"""Converts a list of m (H x W x C) numpy.ndarrays in the range [0, 255]
or PIL Images to a torch.FloatTensor of shape (m*C x H x W)
in the range [0, 1.0]
"""
def __in... | 1,699 | 33 | 80 | py |
trx | trx-main/videotransforms/volume_transforms.py | import numpy as np
from PIL import Image
import torch
from videotransforms.utils import images as imageutils
class ClipToTensor(object):
"""Convert a list of m (H x W x C) numpy.ndarrays in the range [0, 255]
to a torch.FloatTensor of shape (C x m x H x W) in the range [0, 1.0]
"""
def __init__(self... | 2,152 | 30.202899 | 81 | py |
trx | trx-main/videotransforms/functional.py | import numbers
#import cv2
import numpy as np
import PIL
#from skimage.transform import resize
import torchvision
def crop_clip(clip, min_h, min_w, h, w):
if isinstance(clip[0], np.ndarray):
cropped = [img[min_h:min_h + h, min_w:min_w + w, :] for img in clip]
elif isinstance(clip[0], PIL.Image.Image... | 2,493 | 32.702703 | 76 | py |
trx | trx-main/videotransforms/video_transforms.py | import numbers
import random
#import cv2
from matplotlib import pyplot as plt
import numpy as np
import PIL
import scipy
import torch
import torchvision
from . import functional as F
class Compose(object):
"""Composes several transforms
Args:
transforms (list of ``Transform`` objects): list of transfor... | 13,108 | 31.44802 | 119 | py |
trx | trx-main/videotransforms/__init__.py | 0 | 0 | 0 | py | |
trx | trx-main/videotransforms/tensor_transforms.py | import random
from videotransforms.utils import functional as F
class Normalize(object):
"""Normalize a tensor image with mean and standard deviation
Given mean: m and std: s
will normalize each channel as channel = (channel - mean) / std
Args:
mean (int): mean value
std (int): std... | 1,671 | 26.866667 | 72 | py |
trx | trx-main/videotransforms/utils/images.py | import numpy as np
def convert_img(img):
"""Converts (H, W, C) numpy.ndarray to (C, W, H) format
"""
if len(img.shape) == 3:
img = img.transpose(2, 0, 1)
if len(img.shape) == 2:
img = np.expand_dims(img, 0)
return img
| 256 | 20.416667 | 59 | py |
trx | trx-main/videotransforms/utils/functional.py | def normalize(tensor, mean, std):
"""
Args:
tensor (Tensor): Tensor to normalize
Returns:
Tensor: Normalized tensor
"""
tensor.sub_(mean).div_(std)
return tensor
| 203 | 17.545455 | 44 | py |
Kitsune-py | Kitsune-py-master/example.py | from Kitsune import Kitsune
import numpy as np
import time
##############################################################################
# Kitsune a lightweight online network intrusion detection system based on an ensemble of autoencoders (kitNET).
# For more information and citation, please see our NDSS'18 paper: K... | 2,948 | 39.958333 | 142 | py |
Kitsune-py | Kitsune-py-master/setup.py | from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize(["*.pyx"])
) | 116 | 18.5 | 38 | py |
Kitsune-py | Kitsune-py-master/FeatureExtractor.py | #Check if cython code has been compiled
import os
import subprocess
use_extrapolation=False #experimental correlation code
if use_extrapolation:
print("Importing AfterImage Cython Library")
if not os.path.isfile("AfterImage.c"): #has not yet been compiled, so try to do so...
cmd = "python setup.py buil... | 8,441 | 37.547945 | 297 | py |
Kitsune-py | Kitsune-py-master/netStat.py | import numpy as np
## Prep AfterImage cython package
import os
import subprocess
import pyximport
pyximport.install()
import AfterImage as af
#import AfterImage_NDSS as af
#
# MIT License
#
# Copyright (c) 2018 Yisroel mirsky
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this so... | 5,834 | 48.449153 | 162 | py |
Kitsune-py | Kitsune-py-master/AfterImage.py | import math
import numpy as np
class incStat:
def __init__(self, Lambda, ID, init_time=0, isTypeDiff=False): # timestamp is creation time
self.ID = ID
self.CF1 = 0 # linear sum
self.CF2 = 0 # sum of squares
self.w = 1e-20 # weight
self.isTypeDiff = isTypeDiff
se... | 16,000 | 35.119639 | 263 | py |
Kitsune-py | Kitsune-py-master/Kitsune.py | from FeatureExtractor import *
from KitNET.KitNET import KitNET
# MIT License
#
# Copyright (c) 2018 Yisroel mirsky
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, inc... | 1,905 | 43.325581 | 143 | py |
Kitsune-py | Kitsune-py-master/KitNET/utils.py |
import numpy
from scipy.stats import norm
numpy.seterr(all='ignore')
def pdf(x,mu,sigma): #normal distribution pdf
x = (x-mu)/sigma
return numpy.exp(-x**2/2)/(numpy.sqrt(2*numpy.pi)*sigma)
def invLogCDF(x,mu,sigma): #normal distribution cdf
x = (x - mu) / sigma
return norm.logcdf(-x) #note: we mutipl... | 1,363 | 22.118644 | 94 | py |
Kitsune-py | Kitsune-py-master/KitNET/dA.py | # Copyright (c) 2017 Yusuke Sugomori
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, mer... | 4,681 | 35.866142 | 123 | py |
Kitsune-py | Kitsune-py-master/KitNET/__init__.py | __all__ = ["corClust", "dA", "KitNET","utils"] | 46 | 46 | 46 | py |
Kitsune-py | Kitsune-py-master/KitNET/corClust.py | import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster, to_tree
# A helper class for KitNET which performs a correlation-based incremental clustering of the dimensions in X
# n: the number of dimensions in the dataset
# For more information and citation, please see our NDSS'18 paper: Kitsune: An Ense... | 3,549 | 46.972973 | 142 | py |
Kitsune-py | Kitsune-py-master/KitNET/KitNET.py | import numpy as np
import KitNET.dA as AE
import KitNET.corClust as CC
# This class represents a KitNET machine learner.
# KitNET is a lightweight online anomaly detection algorithm based on an ensemble of autoencoders.
# For more information and citation, please see our NDSS'18 paper: Kitsune: An Ensemble of Autoenco... | 6,544 | 50.132813 | 154 | py |
DDoS | DDoS-master/analyse_dataset.py | import argparse
import logging
import math
import os
import random
import statistics
import sys
import numpy as np
import pandas as pd
import torch
import torch.autograd.profiler as profiler
import torch.nn.functional as F
from torch.cuda.amp import autocast
from torch.utils.tensorboard import SummaryWriter
from tqdm ... | 18,510 | 58.330128 | 239 | py |
DDoS | DDoS-master/train_DDoS_baseline_nondyn.py | import argparse
import logging
import math
import os
import random
import statistics
import sys
import numpy as np
import torch
import torch.autograd.profiler as profiler
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchio as tio
from torch.cuda.amp import GradScaler, autoc... | 26,386 | 53.972917 | 230 | py |
DDoS | DDoS-master/apply_DDoS_baseline.py | import argparse
import logging
import math
import os
import random
import statistics
import sys
import numpy as np
import pandas as pd
import torch
import torch.autograd.profiler as profiler
import torch.nn.functional as F
from torch.cuda.amp import autocast
from torch.utils.tensorboard import SummaryWriter
from tqdm ... | 20,417 | 59.587537 | 239 | py |
DDoS | DDoS-master/apply_DDoS.py | import argparse
import logging
import math
import os
import random
import statistics
import sys
import numpy as np
import pandas as pd
import torch
import torch.autograd.profiler as profiler
import torch.nn.functional as F
from torch.cuda.amp import autocast
from torch.utils.tensorboard import SummaryWriter
from tqdm ... | 21,258 | 59.566952 | 240 | py |
DDoS | DDoS-master/train_DDoS_baseline.py | import argparse
import logging
import math
import os
import random
import statistics
import sys
import numpy as np
import torch
import torch.autograd.profiler as profiler
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchio as tio
from torch.cuda.amp import GradScaler, autoc... | 26,396 | 53.99375 | 230 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.