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 |
|---|---|---|---|---|---|---|
pairwiseMKL | pairwiseMKL-master/pairwisemkl/learner/compute_M__arrayjob.py | #
# The MIT License (MIT)
#
# This file is part of pairwiseMKL
#
# Copyright (c) 2018 Anna Cichonska
#
# 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 l... | 4,090 | 37.233645 | 108 | py |
pairwiseMKL | pairwiseMKL-master/pairwisemkl/learner/kron_decomp.py | #
# The MIT License (MIT)
#
# This file is part of pairwiseMKL
#
# Copyright (c) 2018 Anna Cichonska, Sandor Szedmak
#
# 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... | 4,003 | 37.873786 | 84 | py |
pairwiseMKL | pairwiseMKL-master/pairwisemkl/learner/optimize_kernel_weights.py | #
# The MIT License (MIT)
#
# This file is part of pairwiseMKL
#
# Copyright (c) 2018 Anna Cichonska
#
# 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 l... | 2,248 | 35.274194 | 86 | py |
GAMMA | GAMMA-master/bin/Tools/plotting_scripts.py | # -*- coding: utf-8 -*-
# @Author: eliotayache
# @Date: 2020-05-14 16:24:48
# @Last Modified by: Eliot Ayache
# @Last Modified time: 2022-03-22 16:22:32
'''
This file contains functions used to print GAMMA outputs. These functions
should be run from the ./bin/Tools directory.
This can be run from a jupyter or iPy... | 8,273 | 25.266667 | 100 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/naf_pendulum.py | import argparse
import collections
import pandas
import numpy as np
import os
import gym
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Flatten, Input, Concatenate
from keras.optimizers import Adam
import tensorflow as tf
from rl.agents import NAFAgent
from rl.memory import Seq... | 6,696 | 43.059211 | 122 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/dqn_cartpole.py | import argparse
import collections
import pandas
import numpy as np
import os
import gym
from keras.layers import Activation, Dense, Flatten
from keras.models import Sequential
from keras.optimizers import Adam
import tensorflow as tf
from rl.agents.dqn import DQNAgent
from rl.core import Processor
from rl.memory imp... | 6,113 | 42.056338 | 133 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/duel_dqn_cartpole.py | import argparse
import collections
import pandas
import numpy as np
import os
import gym
from keras.layers import Activation, Dense, Flatten
from keras.models import Sequential
from keras.optimizers import Adam
import tensorflow as tf
from rl.agents.dqn import DQNAgent
from rl.core import Processor
from rl.memory imp... | 6,413 | 43.541667 | 138 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/collect.py | import argparse
import glob
import os
parser = argparse.ArgumentParser()
parser.add_argument('--log_dir', default='logs/ddpg_pendulum/norm_one',
help='Log dir [default: logs/ddpg_pendulum/norm_one]')
parser.add_argument('--save_dir', default='docs/ddpg_pendulum/norm_one',
help=... | 1,009 | 29.606061 | 93 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/utils.py | def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.') | 241 | 33.571429 | 67 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/sarsa_cartpole.py | import argparse
import collections
import pandas
import numpy as np
import os
import gym
from keras.layers import Activation, Dense, Flatten
from keras.models import Sequential
from keras.optimizers import Adam
import tensorflow as tf
from rl.agents import SARSAAgent
from rl.core import Processor
from rl.policy impor... | 5,869 | 39.482759 | 137 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/qlearn_cartpole.py | import argparse
import collections
import os
import random
import numpy as np
import gym
import pandas
from utils import *
parser = argparse.ArgumentParser()
parser.add_argument('--error_positive', type=float, default=0.2,
help='Error positive rate [default: 0.2]')
parser.add_argument('--error_ne... | 13,444 | 34.288714 | 107 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/ddpg_pendulum.py | import argparse
import pandas
import numpy as np
import os
import gym
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Flatten, Input, Concatenate
from keras.optimizers import Adam
import tensorflow as tf
from rl.agents import DDPGAgent
from rl.core import Processor
from rl.memor... | 6,589 | 44.763889 | 124 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/noise_estimator.py | import collections
import pandas
import numpy as np
from rl.core import Processor
def build_state(features):
return int("".join(map(lambda feature: str(int(feature)), features)))
def to_bin(value, bins):
return np.digitize(x=[value], bins=bins)[0]
def is_invertible(a):
return a.shape[0] == a.shape[1] ... | 14,761 | 33.816038 | 120 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/cem_cartpole.py | import argparse
import collections
import pandas
import numpy as np
import os
import gym
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
import tensorflow as tf
from rl.agents.cem import CEMAgent
from rl.memory import EpisodeParameterMemory
from noise_estimator import CartpoleP... | 5,860 | 39.42069 | 122 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/plot.py | import argparse
import pandas
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
sns.set_color_codes()
parser = argparse.ArgumentParser()
parser.add_argument('--log_dir', type=str, default="logs/dqn_cartpole",
help='The path of log directory [default: logs... | 20,248 | 53.727027 | 152 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/callbacks.py | from __future__ import division
from __future__ import print_function
import warnings
import timeit
import json
from tempfile import mkdtemp
import numpy as np
from keras import __version__ as KERAS_VERSION
from keras.callbacks import Callback as KerasCallback, CallbackList as KerasCallbackList
from keras.utils.gener... | 16,229 | 40.829897 | 423 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/core.py | # -*- coding: utf-8 -*-
import warnings
from copy import deepcopy
import numpy as np
from keras.callbacks import History
from rl.callbacks import (
CallbackList,
TestLogger,
TrainEpisodeLogger,
TrainIntervalLogger,
Visualizer
)
class Agent(object):
"""Abstract base class for all implemented ... | 29,790 | 41.018336 | 202 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/memory.py | from __future__ import absolute_import
from collections import deque, namedtuple
import warnings
import random
import numpy as np
# This is to be understood as a transition: Given `state0`, performing `action`
# yields `reward` and results in `state1`, which might be `terminal`.
Experience = namedtuple('Experience',... | 14,004 | 38.450704 | 136 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/policy.py | from __future__ import division
import numpy as np
from rl.util import *
class Policy(object):
"""Abstract base class for all implemented policies.
Each policy helps with selection of action to take on an environment.
Do not use this abstract base class directly but instead use one of the concrete poli... | 10,299 | 29.563798 | 106 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/random.py | from __future__ import division
import numpy as np
class RandomProcess(object):
def reset_states(self):
pass
class AnnealedGaussianProcess(RandomProcess):
def __init__(self, mu, sigma, sigma_min, n_steps_annealing):
self.mu = mu
self.sigma = sigma
self.n_steps = 0
if... | 2,040 | 33.59322 | 147 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/processors.py | import random
import numpy as np
from rl.core import Processor
from rl.util import WhiteningNormalizer
class MultiInputProcessor(Processor):
"""Converts observations from an environment with multiple observations for use in a neural network
policy.
In some cases, you have environments that return multi... | 2,639 | 43.745763 | 125 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/util.py | import numpy as np
from keras.models import model_from_config, Sequential, Model, model_from_config
import keras.optimizers as optimizers
import keras.backend as K
def clone_model(model, custom_objects={}):
# Requires Keras 1.0.7 since get_config has breaking changes.
config = {
'class_name': model._... | 4,476 | 32.410448 | 116 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/__init__.py | 0 | 0 | 0 | py | |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/agents/ddpg.py | from __future__ import division
from collections import deque
import os
import warnings
import numpy as np
import keras.backend as K
import keras.optimizers as optimizers
from rl.core import Agent
from rl.random import OrnsteinUhlenbeckProcess
from rl.util import *
def mean_q(y_true, y_pred):
return K.mean(K.ma... | 14,524 | 44.820189 | 195 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/agents/sarsa.py | import collections
import numpy as np
from keras.callbacks import History
from keras.models import Model
from keras.layers import Input, Lambda
import keras.backend as K
from rl.core import Agent
from rl.agents.dqn import mean_q
from rl.util import huber_loss
from rl.policy import EpsGreedyQPolicy, GreedyQPolicy
fro... | 9,668 | 40.320513 | 121 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/agents/dqn.py | from __future__ import division
import warnings
import keras.backend as K
from keras.models import Model
from keras.layers import Lambda, Input, Layer, Dense
from rl.core import Agent
from rl.policy import EpsGreedyQPolicy, GreedyQPolicy
from rl.util import *
def mean_q(y_true, y_pred):
return K.mean(K.max(y_pr... | 33,631 | 44.204301 | 250 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/agents/__init__.py | from __future__ import absolute_import
from .dqn import DQNAgent, NAFAgent, ContinuousDQNAgent
from .ddpg import DDPGAgent
from .cem import CEMAgent
from .sarsa import SarsaAgent, SARSAAgent
| 191 | 31 | 55 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-control/rl/agents/cem.py | from __future__ import division
from collections import deque
from copy import deepcopy
import numpy as np
import keras.backend as K
from keras.models import Model
from rl.core import Agent
from rl.util import *
class CEMAgent(Agent):
"""Write me
"""
def __init__(self, model, nb_actions, memory, batch_si... | 6,679 | 36.740113 | 136 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/setup.py | from setuptools import setup, find_packages
import sys
if sys.version_info.major != 3:
print('This Python is only compatible with Python 3, but you are running '
'Python {}. The installation will likely fail.'.format(sys.version_info.major))
setup(name='baselines',
packages=[package for package i... | 1,035 | 27.777778 | 104 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/results_plotter.py | import numpy as np
import matplotlib
matplotlib.use('TkAgg') # Can change to 'Agg' for non-interactive mode
import matplotlib.pyplot as plt
plt.rcParams['svg.fonttype'] = 'none'
from baselines.bench.monitor import load_results
X_TIMESTEPS = 'timesteps'
X_EPISODES = 'episodes'
X_WALLTIME = 'walltime_hrs'
POSSIBLE_X_A... | 4,381 | 35.516667 | 115 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/logger.py | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
from collections import defaultdict
DEBUG = 10
INFO = 20
WARN = 30
ERROR = 40
DISABLED = 50
class KVWriter(object):
def writekvs(self, kvs):
raise NotImplementedError
class SeqWriter(object):... | 14,390 | 28.918919 | 122 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/results_compare.py | import numpy as np
import matplotlib
matplotlib.use('TkAgg') # Can change to 'Agg' for non-interactive mode
import matplotlib.pyplot as plt
plt.rcParams['svg.fonttype'] = 'none'
from baselines.bench.monitor import load_results
X_TIMESTEPS = 'timesteps'
X_EPISODES = 'episodes'
X_WALLTIME = 'walltime_hrs'
POSSIBLE_X_A... | 6,613 | 35.340659 | 115 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/run.py | import sys
import multiprocessing
import os
import os.path as osp
import gym
from collections import defaultdict
import tensorflow as tf
from baselines.common.vec_env.vec_frame_stack import VecFrameStack
from baselines.common.cmd_util import common_arg_parser, parse_unknown_args, make_mujoco_env, make_atari_env
from b... | 7,705 | 30.325203 | 154 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/results_single.py | import argparse
import os
import glob
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
sns.set_color_codes()
from baselines.bench.monitor import load_results
matplotlib.rcParams.update({'font.size': 30})
X_TIMESTEPS = 'timesteps'
X_EPISODES = 'episodes'
X_WALLTIME ... | 3,709 | 35.372549 | 111 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/noisy_reward.py | import numpy as np
import collections
def is_invertible(a):
return a.shape[0] == a.shape[1] and np.linalg.matrix_rank(a) == a.shape[0]
def disarrange(a, axis=-1):
"""
Shuffle `a` in-place along the given axis.
Apply numpy.random.shuffle to the given axis of `a`.
Each one-dimensional slice is shuf... | 10,368 | 29.952239 | 113 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/__init__.py | 0 | 0 | 0 | py | |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/mpi_adam.py | from mpi4py import MPI
import baselines.common.tf_util as U
import tensorflow as tf
import numpy as np
class MpiAdam(object):
def __init__(self, var_list, *, beta1=0.9, beta2=0.999, epsilon=1e-08, scale_grad_by_procs=True, comm=None):
self.var_list = var_list
self.beta1 = beta1
self.beta2 =... | 2,786 | 34.278481 | 112 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/cg.py | import numpy as np
def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10):
"""
Demmel p 312
"""
p = b.copy()
r = b.copy()
x = np.zeros_like(b)
rdotr = r.dot(r)
fmtstr = "%10i %10.3g %10.3g"
titlestr = "%10s %10s %10s"
if verbose: print(titlestr % ("iter... | 896 | 25.382353 | 88 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/runners.py | import numpy as np
from abc import ABC, abstractmethod
class AbstractEnvRunner(ABC):
def __init__(self, *, env, model, nsteps):
self.env = env
self.model = model
self.nenv = nenv = env.num_envs if hasattr(env, 'num_envs') else 1
self.batch_ob_shape = (nenv*nsteps,) + env.observation... | 670 | 32.55 | 106 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/distributions.py | import tensorflow as tf
import numpy as np
import baselines.common.tf_util as U
from baselines.a2c.utils import fc
from tensorflow.python.ops import math_ops
class Pd(object):
"""
A particular probability distribution
"""
def flatparam(self):
raise NotImplementedError
def mode(self):
... | 11,896 | 37.254019 | 217 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/mpi_util.py | from collections import defaultdict
from mpi4py import MPI
import os, numpy as np
import platform
import shutil
import subprocess
def sync_from_root(sess, variables, comm=None):
"""
Send the root node's parameters to every worker.
Arguments:
sess: the TensorFlow session.
variables: all paramete... | 3,116 | 29.558824 | 101 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/schedules.py | """This file is used for specifying various schedules that evolve over
time throughout the execution of the algorithm, such as:
- learning rate for the optimizer
- exploration epsilon for the epsilon greedy exploration strategy
- beta parameter for beta parameter in prioritized replay
Each schedule has a function `... | 3,702 | 36.03 | 90 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/atari_wrappers.py | import numpy as np
import os
os.environ.setdefault('PATH', '')
from collections import deque
import gym
from gym import spaces
import cv2
cv2.ocl.setUseOpenCL(False)
class NoopResetEnv(gym.Wrapper):
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset.
... | 8,216 | 33.380753 | 131 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/mpi_running_mean_std.py | from mpi4py import MPI
import tensorflow as tf, baselines.common.tf_util as U, numpy as np
class RunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def __init__(self, epsilon=1e-2, shape=()):
self._sum = tf.get_variable(
dtype=tf.... | 3,629 | 32.611111 | 126 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/misc_util.py | import gym
import numpy as np
import os
import pickle
import random
import tempfile
import zipfile
def zipsame(*seqs):
L = len(seqs[0])
assert all(len(seq) == L for seq in seqs[1:])
return zip(*seqs)
def unpack(seq, sizes):
"""
Unpack 'seq' into a sequence of lists, with lengths specified by 'si... | 7,776 | 28.236842 | 110 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/mpi_fork.py | import os, subprocess, sys
def mpi_fork(n, bind_to_core=False):
"""Re-launches the current script with workers
Returns "parent" for original parent, "child" for MPI children
"""
if n<=1:
return "child"
if os.getenv("IN_MPI") is None:
env = os.environ.copy()
env.update(
... | 668 | 26.875 | 66 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/dataset.py | import numpy as np
class Dataset(object):
def __init__(self, data_map, deterministic=False, shuffle=True):
self.data_map = data_map
self.deterministic = deterministic
self.enable_shuffle = shuffle
self.n = next(iter(data_map.values())).shape[0]
self._next_id = 0
self... | 2,132 | 33.967213 | 110 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/math_util.py | import numpy as np
import scipy.signal
def discount(x, gamma):
"""
computes discounted sums along 0th dimension of x.
inputs
------
x: ndarray
gamma: float
outputs
-------
y: ndarray with same shape as x, satisfying
y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gam... | 2,093 | 23.635294 | 75 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tf_util.py | import joblib
import numpy as np
import tensorflow as tf # pylint: ignore-module
import copy
import os
import functools
import collections
import multiprocessing
def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scalar value (int or bool).
Note that bot... | 15,157 | 36.334975 | 171 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tile_images.py | import numpy as np
def tile_images(img_nhwc):
"""
Tile N images into one big PxQ image
(P,Q) are chosen to be as close as possible, and if N
is square, then P=Q.
input: img_nhwc, list or array of images, ndim=4 once turned into array
n = batch index, h = height, w = width, c = channel
... | 763 | 30.833333 | 80 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/running_mean_std.py | import tensorflow as tf
import numpy as np
from baselines.common.tf_util import get_session
class RunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def __init__(self, epsilon=1e-4, shape=()):
self.mean = np.zeros(shape, 'float64')
sel... | 6,200 | 31.984043 | 142 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/retro_wrappers.py | # flake8: noqa F403, F405
from .atari_wrappers import *
import numpy as np
import gym
class TimeLimit(gym.Wrapper):
def __init__(self, env, max_episode_steps=None):
super(TimeLimit, self).__init__(env)
self._max_episode_steps = max_episode_steps
self._elapsed_steps = 0
def step(self, ... | 10,238 | 33.826531 | 107 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/running_stat.py | import numpy as np
# http://www.johndcook.com/blog/standard_deviation/
class RunningStat(object):
def __init__(self, shape):
self._n = 0
self._M = np.zeros(shape)
self._S = np.zeros(shape)
def push(self, x):
x = np.asarray(x)
assert x.shape == self._M.shape
self.... | 1,320 | 27.106383 | 78 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/segment_tree.py | import operator
class SegmentTree(object):
def __init__(self, capacity, operation, neutral_element):
"""Build a Segment Tree data structure.
https://en.wikipedia.org/wiki/Segment_tree
Can be used as regular array, but with two
important differences:
a) setting item's... | 4,899 | 32.561644 | 109 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/policies.py | import tensorflow as tf
from baselines.common import tf_util
from baselines.a2c.utils import fc
from baselines.common.distributions import make_pdtype
from baselines.common.input import observation_placeholder, encode_observation
from baselines.common.tf_util import adjust_shape
from baselines.common.mpi_running_mean_s... | 6,337 | 34.211111 | 137 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/models.py | import numpy as np
import tensorflow as tf
from baselines.a2c import utils
from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch
from baselines.common.mpi_running_mean_std import RunningMeanStd
import tensorflow.contrib.layers as layers
def nature_cnn(unscaled_images, **conv_kwargs):
""... | 5,749 | 31.303371 | 133 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/mpi_adam_optimizer.py | import numpy as np
import tensorflow as tf
from mpi4py import MPI
class MpiAdamOptimizer(tf.train.AdamOptimizer):
"""Adam optimizer that averages gradients across mpi processes."""
def __init__(self, comm, **kwargs):
self.comm = comm
tf.train.AdamOptimizer.__init__(self, **kwargs)
def compu... | 1,358 | 41.46875 | 97 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/identity_env.py | from gym import Env
from gym.spaces import Discrete
class IdentityEnv(Env):
def __init__(
self,
dim,
ep_length=100,
):
self.action_space = Discrete(dim)
self.reset()
def reset(self):
self._choose_next_state()
self.observation_space = se... | 678 | 20.903226 | 50 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/__init__.py | # flake8: noqa F403
from baselines.common.console_util import *
from baselines.common.dataset import Dataset
from baselines.common.math_util import *
from baselines.common.misc_util import *
| 191 | 31 | 44 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/mpi_moments.py | from mpi4py import MPI
import numpy as np
from baselines.common import zipsame
def mpi_mean(x, axis=0, comm=None, keepdims=False):
x = np.asarray(x)
assert x.ndim > 0
if comm is None: comm = MPI.COMM_WORLD
xsum = x.sum(axis=axis, keepdims=keepdims)
n = xsum.size
localsum = np.zeros(n+1, x.dtyp... | 1,963 | 31.196721 | 101 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/filters.py | from .running_stat import RunningStat
from collections import deque
import numpy as np
class Filter(object):
def __call__(self, x, update=True):
raise NotImplementedError
def reset(self):
pass
class IdentityFilter(Filter):
def __call__(self, x, update=True):
return x
class Composi... | 2,742 | 26.707071 | 84 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/console_util.py | from __future__ import print_function
from contextlib import contextmanager
import numpy as np
import time
# ================================================================
# Misc
# ================================================================
def fmt_row(width, row, header=False):
out = " | ".join(fmt_item(x... | 1,504 | 24.083333 | 104 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/cmd_util.py | """
Helpers for scripts like run_atari.py.
"""
import os
try:
from mpi4py import MPI
except ImportError:
MPI = None
import gym
from gym.wrappers import FlattenDictWrapper
from baselines import logger
from baselines.bench import Monitor
from baselines.common import set_global_seeds
from baselines.common.atari_... | 5,142 | 36 | 193 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/input.py | import tensorflow as tf
from gym.spaces import Discrete, Box
def observation_placeholder(ob_space, batch_size=None, name='Ob'):
'''
Create placeholder to feed observations into of the size appropriate to the observation space
Parameters:
----------
ob_space: gym.Space observation space
... | 1,686 | 28.596491 | 113 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/test_tf_util.py | # tests for tf_util
import tensorflow as tf
from baselines.common.tf_util import (
function,
initialize,
single_threaded_session
)
def test_function():
with tf.Graph().as_default():
x = tf.placeholder(tf.int32, (), name="x")
y = tf.placeholder(tf.int32, (), name="y")
z = 3 * x ... | 1,000 | 23.414634 | 55 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/test_schedules.py | import numpy as np
from baselines.common.schedules import ConstantSchedule, PiecewiseSchedule
def test_piecewise_schedule():
ps = PiecewiseSchedule([(-5, 100), (5, 200), (10, 50), (100, 50), (200, -50)], outside_value=500)
assert np.isclose(ps.value(-10), 500)
assert np.isclose(ps.value(0), 150)
ass... | 823 | 29.518519 | 101 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/test_identity.py | import pytest
from baselines.common.tests.envs.identity_env import DiscreteIdentityEnv, BoxIdentityEnv
from baselines.run import get_learn_function
from baselines.common.tests.util import simple_test
common_kwargs = dict(
total_timesteps=30000,
network='mlp',
gamma=0.9,
seed=0,
)
learn_kwargs = {
... | 1,583 | 27.285714 | 91 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/test_segment_tree.py | import numpy as np
from baselines.common.segment_tree import SumSegmentTree, MinSegmentTree
def test_tree_set():
tree = SumSegmentTree(4)
tree[2] = 1.0
tree[3] = 3.0
assert np.isclose(tree.sum(), 4.0)
assert np.isclose(tree.sum(0, 2), 0.0)
assert np.isclose(tree.sum(0, 3), 1.0)
assert n... | 2,691 | 24.884615 | 72 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/test_mnist.py | import pytest
# from baselines.acer import acer_simple as acer
from baselines.common.tests.envs.mnist_env import MnistEnv
from baselines.common.tests.util import simple_test
from baselines.run import get_learn_function
# TODO investigate a2c and ppo2 failures - is it due to bad hyperparameters for this problem?
# ... | 1,591 | 30.215686 | 104 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/util.py | import tensorflow as tf
import numpy as np
from gym.spaces import np_random
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
N_TRIALS = 10000
N_EPISODES = 100
def simple_test(env_fn, learn_fn, min_reward_fraction, n_trials=N_TRIALS):
np.random.seed(0)
np_random.seed(0)
env = DummyVecEnv([en... | 2,676 | 28.097826 | 127 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/__init__.py | 0 | 0 | 0 | py | |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/test_serialization.py | import os
import tempfile
import pytest
import tensorflow as tf
import numpy as np
from baselines.common.tests.envs.mnist_env import MnistEnv
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
from baselines.run import get_learn_function
from baselines.common.tf_util import make_session, get_session
from ... | 2,955 | 29.163265 | 105 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/test_cartpole.py | import pytest
import gym
from baselines.run import get_learn_function
from baselines.common.tests.util import reward_per_episode_test
common_kwargs = dict(
total_timesteps=30000,
network='mlp',
gamma=1.0,
seed=0,
)
learn_kwargs = {
'a2c' : dict(nsteps=32, value_network='copy', lr=0.05),
'a... | 937 | 21.878049 | 65 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/test_fixed_sequence.py | import pytest
from baselines.common.tests.envs.fixed_sequence_env import FixedSequenceEnv
from baselines.common.tests.util import simple_test
from baselines.run import get_learn_function
common_kwargs = dict(
seed=0,
total_timesteps=50000,
)
learn_kwargs = {
'a2c': {},
'ppo2': dict(nsteps=10, ent... | 1,379 | 25.538462 | 165 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/envs/mnist_env.py | import os.path as osp
import numpy as np
import tempfile
import filelock
from gym import Env
from gym.spaces import Discrete, Box
class MnistEnv(Env):
def __init__(
self,
seed=0,
episode_len=None,
no_images=None
):
from tensorflow.examples.tutorials.mni... | 2,099 | 28.577465 | 101 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/envs/fixed_sequence_env.py | import numpy as np
from gym import Env
from gym.spaces import Discrete
class FixedSequenceEnv(Env):
def __init__(
self,
n_actions=10,
seed=0,
episode_len=100
):
self.np_random = np.random.RandomState()
self.np_random.seed(seed)
self.seque... | 1,066 | 22.711111 | 92 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/envs/identity_env.py | import numpy as np
from abc import abstractmethod
from gym import Env
from gym.spaces import Discrete, Box
class IdentityEnv(Env):
def __init__(
self,
episode_len=None
):
self.episode_len = episode_len
self.time = 0
self.reset()
def reset(self):
se... | 1,608 | 21.661972 | 64 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/tests/envs/__init__.py | 0 | 0 | 0 | py | |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/vec_env/vec_normalize.py | from baselines.common.vec_env import VecEnvWrapper
from baselines.common.running_mean_std import RunningMeanStd
import numpy as np
class VecNormalize(VecEnvWrapper):
"""
Vectorized environment base class
"""
def __init__(self, venv, ob=True, ret=True, clipob=10., cliprew=10., gamma=0.99, epsilon=1e-8):... | 1,910 | 37.22 | 129 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/vec_env/dummy_vec_env.py | import numpy as np
from gym import spaces
from collections import OrderedDict
from . import VecEnv
class DummyVecEnv(VecEnv):
def __init__(self, env_fns):
self.envs = [fn() for fn in env_fns]
env = self.envs[0]
VecEnv.__init__(self, len(env_fns), env.observation_space, env.action_space)
... | 2,772 | 32.409639 | 157 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/vec_env/__init__.py | from abc import ABC, abstractmethod
from baselines import logger
class AlreadySteppingError(Exception):
"""
Raised when an asynchronous step is running while
step_async() is called again.
"""
def __init__(self):
msg = 'already running an async step'
Exception.__init__(self, msg)
cl... | 3,392 | 25.716535 | 90 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/vec_env/subproc_vec_env.py | import numpy as np
from multiprocessing import Process, Pipe
from baselines.common.vec_env import VecEnv, CloudpickleWrapper
from baselines.common.tile_images import tile_images
def worker(remote, parent_remote, env_fn_wrapper):
parent_remote.close()
env = env_fn_wrapper.x()
try:
while True:
... | 3,553 | 34.188119 | 97 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/common/vec_env/vec_frame_stack.py | from baselines.common.vec_env import VecEnvWrapper
import numpy as np
from gym import spaces
class VecFrameStack(VecEnvWrapper):
"""
Vectorized environment base class
"""
def __init__(self, venv, nstack):
self.venv = venv
self.nstack = nstack
wos = venv.observation_space # wrapp... | 1,319 | 32.846154 | 94 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/ppo2/ppo2.py | import os
import time
import functools
import numpy as np
import os.path as osp
import tensorflow as tf
from baselines import logger
from collections import deque
from baselines.common import explained_variance, set_global_seeds
from baselines.common.policies import build_policy
from baselines.common.runners import Abs... | 15,257 | 46.53271 | 184 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/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=1... | 500 | 20.782609 | 59 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/ppo2/__init__.py | 0 | 0 | 0 | py | |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/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... | 7,571 | 41.301676 | 186 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/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 |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/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):
def __init__(self, env, model, nsteps=5, gamma=0.99):
super().__init__(env=env, model=model, nsteps=nsteps)
self.gamma = gamma
self... | 2,727 | 43 | 112 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/a2c/__init__.py | 0 | 0 | 0 | py | |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/bench/benchmarks.py | import re
import os.path as osp
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 = []
remov... | 5,598 | 35.835526 | 129 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/bench/monitor.py | __all__ = ['Monitor', 'get_monitor_files', 'load_results']
import gym
from gym.core import Wrapper
import time
from glob import glob
import csv
import os.path as osp
import json
import numpy as np
class Monitor(Wrapper):
EXT = "monitor.csv"
f = None
def __init__(self, env, filename, allow_early_resets=Fa... | 5,848 | 34.664634 | 174 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/baselines/baselines/bench/__init__.py | from baselines.bench.benchmarks import *
from baselines.bench.monitor import * | 78 | 38.5 | 40 | py |
rl-perturbed-reward | rl-perturbed-reward-master/gym-atari/scripts/visualize.py | import argparse
import os
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
parser = argparse.ArgumentParser()
parser.add_argu... | 2,552 | 38.276923 | 88 | py |
text-classification-cnn-rnn | text-classification-cnn-rnn-master/rnn_model.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
class TRNNConfig(object):
"""RNN配置参数"""
# 模型参数
embedding_dim = 64 # 词向量维度
seq_length = 600 # 序列长度
num_classes = 10 # 类别数
vocab_size = 5000 # 词汇表达小
num_layers= 2 # 隐藏层层数
hidden_dim = 1... | 3,168 | 33.824176 | 108 | py |
text-classification-cnn-rnn | text-classification-cnn-rnn-master/cnn_model.py | # coding: utf-8
import tensorflow as tf
class TCNNConfig(object):
"""CNN配置参数"""
embedding_dim = 64 # 词向量维度
seq_length = 600 # 序列长度
num_classes = 10 # 类别数
num_filters = 256 # 卷积核数目
kernel_size = 5 # 卷积核尺寸
vocab_size = 5000 # 词汇表达小
hidden_dim = 128 # 全连接层神经元
dropout_keep_p... | 2,493 | 32.253333 | 116 | py |
text-classification-cnn-rnn | text-classification-cnn-rnn-master/run_cnn.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import time
from datetime import timedelta
import numpy as np
import tensorflow as tf
from sklearn import metrics
from cnn_model import TCNNConfig, TextCNN
from data.cnews_loader import read_vocab, read_category, ba... | 6,689 | 32.118812 | 112 | py |
text-classification-cnn-rnn | text-classification-cnn-rnn-master/predict.py | # coding: utf-8
from __future__ import print_function
import os
import tensorflow as tf
import tensorflow.contrib.keras as kr
from cnn_model import TCNNConfig, TextCNN
from data.cnews_loader import read_category, read_vocab
try:
bool(type(unicode))
except NameError:
unicode = str
base_dir = 'data/cnews'
vo... | 1,694 | 28.736842 | 104 | py |
text-classification-cnn-rnn | text-classification-cnn-rnn-master/run_rnn.py | # coding: utf-8
from __future__ import print_function
import os
import sys
import time
from datetime import timedelta
import numpy as np
import tensorflow as tf
from sklearn import metrics
from rnn_model import TRNNConfig, TextRNN
from data.cnews_loader import read_vocab, read_category, batch_iter, process_file, bu... | 6,675 | 32.21393 | 112 | py |
text-classification-cnn-rnn | text-classification-cnn-rnn-master/helper/cnews_group.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
将文本整合到 train、test、val 三个文件中
"""
import os
def _read_file(filename):
"""读取一个文件并转换为一行"""
with open(filename, 'r', encoding='utf-8') as f:
return f.read().replace('\n', '').replace('\t', '').replace('\u3000', '')
def save_file(dirname):
"""
将多个文件整合并... | 1,629 | 29.754717 | 85 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.