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 |
|---|---|---|---|---|---|---|
baselines | baselines-master/baselines/deepq/experiments/train_pong.py | from baselines import deepq
from baselines import bench
from baselines import logger
from baselines.common.atari_wrappers import make_atari
def main():
logger.configure()
env = make_atari('PongNoFrameskip-v4')
env = bench.Monitor(env, logger.get_dir())
env = deepq.wrap_atari_dqn(env)
model = deep... | 817 | 22.371429 | 54 | py |
baselines | baselines-master/baselines/deepq/experiments/enjoy_cartpole.py | import gym
from baselines import deepq
def main():
env = gym.make("CartPole-v0")
act = deepq.learn(env, network='mlp', total_timesteps=0, load_path="cartpole_model.pkl")
while True:
obs, done = env.reset(), False
episode_rew = 0
while not done:
env.render()
... | 486 | 21.136364 | 92 | py |
baselines | baselines-master/baselines/deepq/experiments/__init__.py | 0 | 0 | 0 | py | |
baselines | baselines-master/baselines/deepq/experiments/custom_cartpole.py | import gym
import itertools
import numpy as np
import tensorflow as tf
import tensorflow.contrib.layers as layers
import baselines.common.tf_util as U
from baselines import logger
from baselines import deepq
from baselines.deepq.replay_buffer import ReplayBuffer
from baselines.deepq.utils import ObservationInput
from... | 3,358 | 40.9875 | 105 | py |
baselines | baselines-master/baselines/trpo_mpi/defaults.py | from baselines.common.models import mlp, cnn_small
def atari():
return dict(
network = cnn_small(),
timesteps_per_batch=512,
max_kl=0.001,
cg_iters=10,
cg_damping=1e-3,
gamma=0.98,
lam=1.0,
vf_iters=3,
vf_stepsize=1e-4,
entcoeff=0.00,... | 638 | 19.612903 | 51 | py |
baselines | baselines-master/baselines/trpo_mpi/__init__.py | 0 | 0 | 0 | py | |
baselines | baselines-master/baselines/trpo_mpi/trpo_mpi.py | from baselines.common import explained_variance, zipsame, dataset
from baselines import logger
import baselines.common.tf_util as U
import tensorflow as tf, numpy as np
import time
from baselines.common import colorize
from collections import deque
from baselines.common import set_global_seeds
from baselines.common.mpi... | 15,098 | 35.91687 | 170 | py |
baselines | baselines-master/baselines/common/mpi_adam.py | import baselines.common.tf_util as U
import tensorflow as tf
import numpy as np
try:
from mpi4py import MPI
except ImportError:
MPI = None
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
... | 3,296 | 30.701923 | 112 | py |
baselines | baselines-master/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... | 897 | 24.657143 | 88 | py |
baselines | baselines-master/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 |
baselines | baselines-master/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):
... | 13,595 | 37.191011 | 217 | py |
baselines | baselines-master/baselines/common/mpi_util.py | from collections import defaultdict
import os, numpy as np
import platform
import shutil
import subprocess
import warnings
import sys
try:
from mpi4py import MPI
except ImportError:
MPI = None
def sync_from_root(sess, variables, comm=None):
"""
Send the root node's parameters to every worker.
Arg... | 4,259 | 30.791045 | 108 | py |
baselines | baselines-master/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 |
baselines | baselines-master/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)
from .wrappers import TimeLimit
class NoopResetEnv(gym.Wrapper):
def __init__(self, env, noop_max=30):
"""Sample initial states by taking ra... | 9,686 | 32.28866 | 130 | py |
baselines | baselines-master/baselines/common/mpi_running_mean_std.py | try:
from mpi4py import MPI
except ImportError:
MPI = None
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.... | 3,706 | 31.80531 | 126 | py |
baselines | baselines-master/baselines/common/test_mpi_util.py | from baselines.common import mpi_util
from baselines import logger
from baselines.common.tests.test_with_mpi import with_mpi
try:
from mpi4py import MPI
except ImportError:
MPI = None
@with_mpi()
def test_mpi_weighted_mean():
comm = MPI.COMM_WORLD
with logger.scoped_configure(comm=comm):
if com... | 986 | 31.9 | 68 | py |
baselines | baselines-master/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)
class EzPickle(object):
"""Objects that are pickled and unpickled via their constructor
argument... | 7,166 | 28.372951 | 97 | py |
baselines | baselines-master/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(
... | 667 | 26.833333 | 66 | py |
baselines | baselines-master/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 |
baselines | baselines-master/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,094 | 23.360465 | 75 | py |
baselines | baselines-master/baselines/common/tf_util.py | 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 both `then_expres... | 16,969 | 37.220721 | 144 | py |
baselines | baselines-master/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 |
baselines | baselines-master/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,081 | 31.351064 | 142 | py |
baselines | baselines-master/baselines/common/retro_wrappers.py | from collections import deque
import cv2
cv2.ocl.setUseOpenCL(False)
from .atari_wrappers import WarpFrame, ClipRewardEnv, FrameStack, ScaledFloatFrame
from .wrappers import TimeLimit
import numpy as np
import gym
class StochasticFrameSkip(gym.Wrapper):
def __init__(self, env, n, stickprob):
gym.Wrapper._... | 9,752 | 33.708185 | 107 | py |
baselines | baselines-master/baselines/common/wrappers.py | 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, ac):
observation, reward, done, info = self.env.step(ac)
sel... | 946 | 30.566667 | 79 | py |
baselines | baselines-master/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 |
baselines | baselines-master/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,652 | 34.57754 | 137 | py |
baselines | baselines-master/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
mapping = {}
def register(name):
def _thunk(func):
mapping[name] = func
retur... | 8,557 | 30.007246 | 140 | py |
baselines | baselines-master/baselines/common/mpi_adam_optimizer.py | import numpy as np
import tensorflow as tf
from baselines.common import tf_util as U
from baselines.common.tests.test_with_mpi import with_mpi
from baselines import logger
try:
from mpi4py import MPI
except ImportError:
MPI = None
class MpiAdamOptimizer(tf.train.AdamOptimizer):
"""Adam optimizer that avera... | 3,976 | 42.703297 | 117 | py |
baselines | baselines-master/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 |
baselines | baselines-master/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... | 2,018 | 31.564516 | 101 | py |
baselines | baselines-master/baselines/common/console_util.py | from __future__ import print_function
from contextlib import contextmanager
import numpy as np
import time
import shlex
import subprocess
# ================================================================
# Misc
# ================================================================
def fmt_row(width, row, header=False):
... | 2,179 | 25.91358 | 104 | py |
baselines | baselines-master/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 FlattenObservation, FilterObservation
from baselines import logger
from baselines.bench import Monitor
from baselines.common import set_global_seeds
from base... | 7,922 | 37.275362 | 204 | py |
baselines | baselines-master/baselines/common/input.py | import numpy as np
import tensorflow as tf
from gym.spaces import Discrete, Box, MultiDiscrete
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.... | 2,071 | 30.876923 | 121 | py |
baselines | baselines-master/baselines/common/plot_util.py | import matplotlib.pyplot as plt
import os.path as osp
import json
import os
import numpy as np
import pandas
from collections import defaultdict, namedtuple
from baselines.bench import monitor
from baselines.logger import read_json, read_csv
def smooth(y, radius, mode='two_sided', valid_only=False):
'''
Smooth... | 18,930 | 42.51954 | 174 | py |
baselines | baselines-master/baselines/common/tests/test_env_after_learn.py | import pytest
import gym
import tensorflow as tf
from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv
from baselines.run import get_learn_function
from baselines.common.tf_util import make_session
algos = ['a2c', 'acer', 'acktr', 'deepq', 'ppo2', 'trpo_mpi']
@pytest.mark.parametrize('algo', algos)
def ... | 865 | 29.928571 | 96 | py |
baselines | baselines-master/baselines/common/tests/test_fetchreach.py | import pytest
import gym
from baselines.run import get_learn_function
from baselines.common.tests.util import reward_per_episode_test
from baselines.common.tests import mark_slow
pytest.importorskip('mujoco_py')
common_kwargs = dict(
network='mlp',
seed=0,
)
learn_kwargs = {
'her': dict(total_timesteps=... | 860 | 20 | 65 | py |
baselines | baselines-master/baselines/common/tests/test_with_mpi.py | import os
import sys
import subprocess
import cloudpickle
import base64
import pytest
from functools import wraps
try:
from mpi4py import MPI
except ImportError:
MPI = None
def with_mpi(nproc=2, timeout=30, skip_if_no_mpi=True):
def outer_thunk(fn):
@wraps(fn)
def thunk(*args, **kwargs):
... | 997 | 24.589744 | 92 | py |
baselines | baselines-master/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,072 | 23.953488 | 55 | py |
baselines | baselines-master/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 |
baselines | baselines-master/baselines/common/tests/test_identity.py | import pytest
from baselines.common.tests.envs.identity_env import DiscreteIdentityEnv, BoxIdentityEnv, MultiDiscreteIdentityEnv
from baselines.run import get_learn_function
from baselines.common.tests.util import simple_test
from baselines.common.tests import mark_slow
common_kwargs = dict(
total_timesteps=30000,... | 2,304 | 28.935065 | 114 | py |
baselines | baselines-master/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 |
baselines | baselines-master/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
from baselines.common.tests import mark_slow
# TODO investigate a2c and ppo2 failures - is it due t... | 1,515 | 29.32 | 104 | py |
baselines | baselines-master/baselines/common/tests/util.py | import tensorflow as tf
import numpy as np
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
N_TRIALS = 10000
N_EPISODES = 100
_sess_config = tf.ConfigProto(
allow_soft_placement=True,
intra_op_parallelism_threads=1,
inter_op_parallelism_threads=1
)
def simple_test(env_fn, learn_fn, min_rewa... | 3,181 | 33.215054 | 127 | py |
baselines | baselines-master/baselines/common/tests/test_plot_util.py | # smoke tests of plot_util
from baselines.common import plot_util as pu
from baselines.common.tests.util import smoketest
def test_plot_util():
nruns = 4
logdirs = [smoketest('--alg=ppo2 --env=CartPole-v0 --num_timesteps=10000') for _ in range(nruns)]
data = pu.load_results(logdirs)
assert len(data) =... | 717 | 38.888889 | 101 | py |
baselines | baselines-master/baselines/common/tests/__init__.py | import os, pytest
mark_slow = pytest.mark.skipif(not os.getenv('RUNSLOW'), reason='slow') | 89 | 44 | 71 | py |
baselines | baselines-master/baselines/common/tests/test_doc_examples.py | import pytest
try:
import mujoco_py
_mujoco_present = True
except BaseException:
mujoco_py = None
_mujoco_present = False
@pytest.mark.skipif(
not _mujoco_present,
reason='error loading mujoco - either mujoco / mujoco key not present, or LD_LIBRARY_PATH is not pointing to mujoco library'
)
def... | 1,351 | 26.591837 | 128 | py |
baselines | baselines-master/baselines/common/tests/test_serialization.py | import os
import gym
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_ses... | 4,273 | 29.528571 | 105 | py |
baselines | baselines-master/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
from baselines.common.tests import mark_slow
common_kwargs = dict(
total_timesteps=30000,
network='mlp',
gamma=1.0,
seed=0,
)
learn_kwargs = {
'a2c' : dict(nsteps=... | 1,098 | 22.891304 | 67 | py |
baselines | baselines-master/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
from baselines.common.tests import mark_slow
common_kwargs = dict(
seed=0,
total_timesteps=50000,
)
learn_kwargs = {
... | 1,389 | 25.226415 | 165 | py |
baselines | baselines-master/baselines/common/tests/envs/mnist_env.py | import os.path as osp
import numpy as np
import tempfile
from gym import Env
from gym.spaces import Discrete, Box
class MnistEnv(Env):
def __init__(
self,
episode_len=None,
no_images=None
):
import filelock
from tensorflow.examples.tutorials.mnist import in... | 2,110 | 28.319444 | 101 | py |
baselines | baselines-master/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,
episode_len=100
):
self.action_space = Discrete(n_actions)
self.observation_space = Discrete(1)
self.np_random = np.... | 1,054 | 22.977273 | 71 | py |
baselines | baselines-master/baselines/common/tests/envs/identity_env.py | import numpy as np
from abc import abstractmethod
from gym import Env
from gym.spaces import MultiDiscrete, Discrete, Box
from collections import deque
class IdentityEnv(Env):
def __init__(
self,
episode_len=None,
delay=0,
zero_first_rewards=True
):
self... | 2,444 | 25.868132 | 101 | py |
baselines | baselines-master/baselines/common/tests/envs/__init__.py | 0 | 0 | 0 | py | |
baselines | baselines-master/baselines/common/tests/envs/identity_env_test.py | from baselines.common.tests.envs.identity_env import DiscreteIdentityEnv
def test_discrete_nodelay():
nsteps = 100
eplen = 50
env = DiscreteIdentityEnv(10, episode_len=eplen)
ob = env.reset()
for t in range(nsteps):
action = env.action_space.sample()
next_ob, rew, done, info = env.... | 1,034 | 26.972973 | 72 | py |
baselines | baselines-master/baselines/common/vec_env/vec_video_recorder.py | import os
from baselines import logger
from baselines.common.vec_env import VecEnvWrapper
from gym.wrappers.monitoring import video_recorder
class VecVideoRecorder(VecEnvWrapper):
"""
Wrap VecEnv to record rendered image as mp4 video.
"""
def __init__(self, venv, directory, record_video_trigger, vide... | 2,746 | 29.522222 | 130 | py |
baselines | baselines-master/baselines/common/vec_env/vec_normalize.py | from . import VecEnvWrapper
import numpy as np
class VecNormalize(VecEnvWrapper):
"""
A vectorized wrapper that normalizes the observations
and returns from an environment.
"""
def __init__(self, venv, ob=True, ret=True, clipob=10., cliprew=10., gamma=0.99, epsilon=1e-8, use_tf=False):
Vec... | 1,854 | 37.645833 | 120 | py |
baselines | baselines-master/baselines/common/vec_env/test_vec_env.py | """
Tests for asynchronous vectorized environments.
"""
import gym
import numpy as np
import pytest
from .dummy_vec_env import DummyVecEnv
from .shmem_vec_env import ShmemVecEnv
from .subproc_vec_env import SubprocVecEnv
from baselines.common.tests.test_with_mpi import with_mpi
def assert_venvs_equal(venv1, venv2, n... | 5,162 | 31.471698 | 92 | py |
baselines | baselines-master/baselines/common/vec_env/vec_env.py | import contextlib
import os
from abc import ABC, abstractmethod
from baselines.common.tile_images import tile_images
class AlreadySteppingError(Exception):
"""
Raised when an asynchronous step is running while
step_async() is called again.
"""
def __init__(self):
msg = 'already running an... | 6,195 | 26.660714 | 219 | py |
baselines | baselines-master/baselines/common/vec_env/vec_monitor.py | from . import VecEnvWrapper
from baselines.bench.monitor import ResultsWriter
import numpy as np
import time
from collections import deque
class VecMonitor(VecEnvWrapper):
def __init__(self, venv, filename=None, keep_buf=0, info_keywords=()):
VecEnvWrapper.__init__(self, venv)
self.eprets = None
... | 1,971 | 34.214286 | 90 | py |
baselines | baselines-master/baselines/common/vec_env/dummy_vec_env.py | import numpy as np
from .vec_env import VecEnv
from .util import copy_obs_dict, dict_to_obs, obs_space_info
class DummyVecEnv(VecEnv):
"""
VecEnv that does runs multiple environments sequentially, that is,
the step and reset commands are send to one environment at a time.
Useful when debugging and when... | 2,923 | 34.658537 | 157 | py |
baselines | baselines-master/baselines/common/vec_env/util.py | """
Helpers for dealing with vectorized environments.
"""
from collections import OrderedDict
import gym
import numpy as np
def copy_obs_dict(obs):
"""
Deep-copy an observation dict.
"""
return {k: np.copy(v) for k, v in obs.items()}
def dict_to_obs(obs_dict):
"""
Convert an observation di... | 1,513 | 23.031746 | 82 | py |
baselines | baselines-master/baselines/common/vec_env/__init__.py | from .vec_env import AlreadySteppingError, NotSteppingError, VecEnv, VecEnvWrapper, VecEnvObservationWrapper, CloudpickleWrapper
from .dummy_vec_env import DummyVecEnv
from .shmem_vec_env import ShmemVecEnv
from .subproc_vec_env import SubprocVecEnv
from .vec_frame_stack import VecFrameStack
from .vec_monitor import Ve... | 668 | 59.818182 | 246 | py |
baselines | baselines-master/baselines/common/vec_env/subproc_vec_env.py | import multiprocessing as mp
import numpy as np
from .vec_env import VecEnv, CloudpickleWrapper, clear_mpi_env_vars
def worker(remote, parent_remote, env_fn_wrappers):
def step_env(env, action):
ob, reward, done, info = env.step(action)
if done:
ob = env.reset()
return ob, rew... | 5,069 | 35.47482 | 128 | py |
baselines | baselines-master/baselines/common/vec_env/test_video_recorder.py | """
Tests for asynchronous vectorized environments.
"""
import gym
import pytest
import os
import glob
import tempfile
from .dummy_vec_env import DummyVecEnv
from .shmem_vec_env import ShmemVecEnv
from .subproc_vec_env import SubprocVecEnv
from .vec_video_recorder import VecVideoRecorder
@pytest.mark.parametrize('kl... | 1,467 | 28.36 | 130 | py |
baselines | baselines-master/baselines/common/vec_env/shmem_vec_env.py | """
An interface for asynchronous vectorized environments.
"""
import multiprocessing as mp
import numpy as np
from .vec_env import VecEnv, CloudpickleWrapper, clear_mpi_env_vars
import ctypes
from baselines import logger
from .util import dict_to_obs, obs_space_info, obs_to_dict
_NP_TO_CT = {np.float32: ctypes.c_fl... | 5,178 | 35.471831 | 129 | py |
baselines | baselines-master/baselines/common/vec_env/vec_frame_stack.py | from .vec_env import VecEnvWrapper
import numpy as np
from gym import spaces
class VecFrameStack(VecEnvWrapper):
def __init__(self, venv, nstack):
self.venv = venv
self.nstack = nstack
wos = venv.observation_space # wrapped ob space
low = np.repeat(wos.low, self.nstack, axis=-1)
... | 1,150 | 36.129032 | 94 | py |
baselines | baselines-master/baselines/common/vec_env/vec_remove_dict_obs.py | from .vec_env import VecEnvObservationWrapper
class VecExtractDictObs(VecEnvObservationWrapper):
def __init__(self, venv, key):
self.key = key
super().__init__(venv=venv,
observation_space=venv.observation_space.spaces[self.key])
def process(self, obs):
return obs[self.key]... | 321 | 28.272727 | 70 | py |
baselines | baselines-master/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,229 | 44.466667 | 184 | py |
baselines | baselines-master/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 |
baselines | baselines-master/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 |
baselines | baselines-master/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,054 | 36.84375 | 114 | py |
baselines | baselines-master/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... | 518 | 18.961538 | 59 | py |
baselines | baselines-master/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 |
baselines | baselines-master/baselines/ppo2/__init__.py | 0 | 0 | 0 | py | |
baselines | baselines-master/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 |
baselines | baselines-master/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 |
baselines | baselines-master/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 |
baselines | baselines-master/baselines/a2c/__init__.py | 0 | 0 | 0 | py | |
baselines | baselines-master/baselines/gail/behavior_clone.py | '''
The code is used to train BC imitator, or pretrained GAIL imitator
'''
import argparse
import tempfile
import os.path as osp
import gym
import logging
from tqdm import tqdm
import tensorflow as tf
from baselines.gail import mlp_policy
from baselines import bench
from baselines import logger
from baselines.common... | 5,195 | 40.568 | 116 | py |
baselines | baselines-master/baselines/gail/adversary.py | '''
Reference: https://github.com/openai/imitation
I follow the architecture from the official repository
'''
import tensorflow as tf
import numpy as np
from baselines.common.mpi_running_mean_std import RunningMeanStd
from baselines.common import tf_util as U
def logsigmoid(a):
'''Equivalent to tf.log(tf.sigmoid(... | 4,674 | 52.125 | 129 | py |
baselines | baselines-master/baselines/gail/run_mujoco.py | '''
Disclaimer: this code is highly based on trpo_mpi at @openai/baselines and @openai/imitation
'''
import argparse
import os.path as osp
import logging
from mpi4py import MPI
from tqdm import tqdm
import numpy as np
import gym
from baselines.gail import mlp_policy
from baselines.common import set_global_seeds, tf_... | 9,366 | 38.029167 | 119 | py |
baselines | baselines-master/baselines/gail/gail-eval.py | '''
This code is used to evalaute the imitators trained with different number of trajectories
and plot the results in the same figure for easy comparison.
'''
import argparse
import os
import glob
import gym
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from baselines.gail import run_muj... | 5,886 | 38.777027 | 116 | py |
baselines | baselines-master/baselines/gail/mlp_policy.py | '''
from baselines/ppo1/mlp_policy.py and add simple modification
(1) add reuse argument
(2) cache the `stochastic` placeholder
'''
import tensorflow as tf
import gym
import baselines.common.tf_util as U
from baselines.common.mpi_running_mean_std import RunningMeanStd
from baselines.common.distributions import make_pd... | 2,930 | 37.565789 | 126 | py |
baselines | baselines-master/baselines/gail/statistics.py | '''
This code is highly based on https://github.com/carpedm20/deep-rl-tensorflow/blob/master/agents/statistic.py
'''
import tensorflow as tf
import numpy as np
import baselines.common.tf_util as U
class stats():
def __init__(self, scalar_keys=[], histogram_keys=[]):
self.scalar_keys = scalar_keys
... | 1,802 | 38.195652 | 108 | py |
baselines | baselines-master/baselines/gail/__init__.py | 0 | 0 | 0 | py | |
baselines | baselines-master/baselines/gail/trpo_mpi.py | '''
Disclaimer: The trpo part highly rely on trpo_mpi at @openai/baselines
'''
import time
import os
from contextlib import contextmanager
from mpi4py import MPI
from collections import deque
import tensorflow as tf
import numpy as np
import baselines.common.tf_util as U
from baselines.common import explained_varian... | 14,662 | 40.304225 | 124 | py |
baselines | baselines-master/baselines/gail/dataset/mujoco_dset.py | '''
Data structure of the input .npz:
the data is save in python dictionary format with keys: 'acs', 'ep_rets', 'rews', 'obs'
the values of each item is a list storing the expert trajectory sequentially
a transition can be: (data['obs'][t], data['acs'][t], data['obs'][t+1]) and get reward data['rews'][t]
'''
from base... | 4,448 | 37.686957 | 104 | py |
baselines | baselines-master/baselines/gail/dataset/__init__.py | 0 | 0 | 0 | py | |
baselines | baselines-master/baselines/ddpg/ddpg.py | import os
import time
from collections import deque
import pickle
from baselines.ddpg.ddpg_learner import DDPG
from baselines.ddpg.models import Actor, Critic
from baselines.ddpg.memory import Memory
from baselines.ddpg.noise import AdaptiveParamNoiseSpec, NormalActionNoise, OrnsteinUhlenbeckActionNoise
from baselines... | 11,283 | 39.884058 | 188 | py |
baselines | baselines-master/baselines/ddpg/memory.py | import numpy as np
class RingBuffer(object):
def __init__(self, maxlen, shape, dtype='float32'):
self.maxlen = maxlen
self.start = 0
self.length = 0
self.data = np.zeros((maxlen,) + shape).astype(dtype)
def __len__(self):
return self.length
def __getitem__(self, i... | 2,708 | 31.25 | 76 | py |
baselines | baselines-master/baselines/ddpg/ddpg_learner.py | from copy import copy
from functools import reduce
import numpy as np
import tensorflow as tf
import tensorflow.contrib as tc
from baselines import logger
from baselines.common.mpi_adam import MpiAdam
import baselines.common.tf_util as U
from baselines.common.mpi_running_mean_std import RunningMeanStd
try:
from m... | 17,731 | 43.664987 | 161 | py |
baselines | baselines-master/baselines/ddpg/noise.py | import numpy as np
class AdaptiveParamNoiseSpec(object):
def __init__(self, initial_stddev=0.1, desired_action_stddev=0.1, adoption_coefficient=1.01):
self.initial_stddev = initial_stddev
self.desired_action_stddev = desired_action_stddev
self.adoption_coefficient = adoption_coefficient
... | 2,162 | 30.808824 | 143 | py |
baselines | baselines-master/baselines/ddpg/test_smoke.py | from baselines.common.tests.util import smoketest
def _run(argstr):
smoketest('--alg=ddpg --env=Pendulum-v0 --num_timesteps=0 ' + argstr)
def test_popart():
_run('--normalize_returns=True --popart=True')
def test_noise_normal():
_run('--noise_type=normal_0.1')
def test_noise_ou():
_run('--noise_type=... | 413 | 23.352941 | 73 | py |
baselines | baselines-master/baselines/ddpg/models.py | import tensorflow as tf
from baselines.common.models import get_network_builder
class Model(object):
def __init__(self, name, network='mlp', **network_kwargs):
self.name = name
self.network_builder = get_network_builder(network)(**network_kwargs)
@property
def vars(self):
return t... | 1,941 | 36.346154 | 129 | py |
baselines | baselines-master/baselines/ddpg/__init__.py | 0 | 0 | 0 | py | |
baselines | baselines-master/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,037 | 43.264151 | 131 | py |
baselines | baselines-master/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 |
baselines | baselines-master/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 |
baselines | baselines-master/baselines/acktr/defaults.py | def mujoco():
return dict(
nsteps=2500,
value_network='copy'
)
| 87 | 13.666667 | 28 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.