code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_action(self, observation):
r"""Get a single action given an observation.
Args:
observation (np.ndarray): Observation from the environment.
Shape is :math:`env_spec.observation_space`.
Returns:
tuple:
* np.ndarray: Predicted action... | Get a single action given an observation.
Args:
observation (np.ndarray): Observation from the environment.
Shape is :math:`env_spec.observation_space`.
Returns:
tuple:
* np.ndarray: Predicted action. Shape is
:math:`env_spec.... | get_action | python | rlworkgroup/garage | src/garage/torch/policies/stochastic_policy.py | https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/stochastic_policy.py | MIT |
def get_actions(self, observations):
r"""Get actions given observations.
Args:
observations (np.ndarray): Observations from the environment.
Shape is :math:`batch_dim \bullet env_spec.observation_space`.
Returns:
tuple:
* np.ndarray: Pred... | Get actions given observations.
Args:
observations (np.ndarray): Observations from the environment.
Shape is :math:`batch_dim \bullet env_spec.observation_space`.
Returns:
tuple:
* np.ndarray: Predicted actions.
:math:`batch_d... | get_actions | python | rlworkgroup/garage | src/garage/torch/policies/stochastic_policy.py | https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/stochastic_policy.py | MIT |
def forward(self, observations):
"""Compute the action distributions from the observations.
Args:
observations (torch.Tensor): Batch of observations on default
torch device.
Returns:
torch.distributions.Distribution: Batch distribution of actions.
... | Compute the action distributions from the observations.
Args:
observations (torch.Tensor): Batch of observations on default
torch device.
Returns:
torch.distributions.Distribution: Batch distribution of actions.
dict[str, torch.Tensor]: Additional ag... | forward | python | rlworkgroup/garage | src/garage/torch/policies/stochastic_policy.py | https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/stochastic_policy.py | MIT |
def forward(self, observations):
"""Compute the action distributions from the observations.
Args:
observations (torch.Tensor): Batch of observations on default
torch device.
Returns:
torch.distributions.Distribution: Batch distribution of actions.
... | Compute the action distributions from the observations.
Args:
observations (torch.Tensor): Batch of observations on default
torch device.
Returns:
torch.distributions.Distribution: Batch distribution of actions.
dict[str, torch.Tensor]: Additional ag... | forward | python | rlworkgroup/garage | src/garage/torch/policies/tanh_gaussian_mlp_policy.py | https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/tanh_gaussian_mlp_policy.py | MIT |
def __init__(self, env_spec, **kwargs):
"""Initialize class with multiple attributes.
Args:
env_spec (EnvSpec): Environment specification.
**kwargs: Keyword arguments.
"""
self._env_spec = env_spec
self._obs_dim = env_spec.observation_space.flat_dim
... | Initialize class with multiple attributes.
Args:
env_spec (EnvSpec): Environment specification.
**kwargs: Keyword arguments.
| __init__ | python | rlworkgroup/garage | src/garage/torch/q_functions/continuous_mlp_q_function.py | https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/q_functions/continuous_mlp_q_function.py | MIT |
def forward(self, observations):
"""Return Q-value(s).
Args:
observations (np.ndarray): observations of shape :math: `(N, O*)`.
Returns:
torch.Tensor: Output value
"""
# We're given flattened observations.
observations = observations.reshape(
... | Return Q-value(s).
Args:
observations (np.ndarray): observations of shape :math: `(N, O*)`.
Returns:
torch.Tensor: Output value
| forward | python | rlworkgroup/garage | src/garage/torch/q_functions/discrete_cnn_q_function.py | https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/q_functions/discrete_cnn_q_function.py | MIT |
def forward(self, observations):
"""Return Q-value(s).
Args:
observations (np.ndarray): observations of shape :math: `(N, O*)`.
Returns:
torch.Tensor: Output value
"""
# We're given flattened observations.
observations = observations.reshape(
... | Return Q-value(s).
Args:
observations (np.ndarray): observations of shape :math: `(N, O*)`.
Returns:
torch.Tensor: Output value
| forward | python | rlworkgroup/garage | src/garage/torch/q_functions/discrete_dueling_cnn_q_function.py | https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/q_functions/discrete_dueling_cnn_q_function.py | MIT |
def compute_loss(self, obs, returns):
r"""Compute mean value of loss.
Args:
obs (torch.Tensor): Observation from the environment
with shape :math:`(N \dot [T], O*)`.
returns (torch.Tensor): Acquired returns with shape :math:`(N, )`.
Returns:
... | Compute mean value of loss.
Args:
obs (torch.Tensor): Observation from the environment
with shape :math:`(N \dot [T], O*)`.
returns (torch.Tensor): Acquired returns with shape :math:`(N, )`.
Returns:
torch.Tensor: Calculated negative mean scalar valu... | compute_loss | python | rlworkgroup/garage | src/garage/torch/value_functions/gaussian_mlp_value_function.py | https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/value_functions/gaussian_mlp_value_function.py | MIT |
def compute_loss(self, obs, returns):
r"""Compute mean value of loss.
Args:
obs (torch.Tensor): Observation from the environment
with shape :math:`(N \dot [T], O*)`.
returns (torch.Tensor): Acquired returns with shape :math:`(N, )`.
Returns:
... | Compute mean value of loss.
Args:
obs (torch.Tensor): Observation from the environment
with shape :math:`(N \dot [T], O*)`.
returns (torch.Tensor): Acquired returns with shape :math:`(N, )`.
Returns:
torch.Tensor: Calculated negative mean scalar valu... | compute_loss | python | rlworkgroup/garage | src/garage/torch/value_functions/value_function.py | https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/value_functions/value_function.py | MIT |
def step_env(env, n=10, visualize=True):
"""Step env helper.
Args:
env (Environment): Input environment.
n (int): Steps.
visualize (bool): Whether visualize the environment.
"""
env.reset()
if visualize and issubclass(type(env), Environment):
env.visualize()
for... | Step env helper.
Args:
env (Environment): Input environment.
n (int): Steps.
visualize (bool): Whether visualize the environment.
| step_env | python | rlworkgroup/garage | tests/helpers.py | https://github.com/rlworkgroup/garage/blob/master/tests/helpers.py | MIT |
def step_env_with_gym_quirks(env,
spec,
n=10,
visualize=True,
serialize_env=False):
"""Step env helper.
Args:
env (Environment): Input environment.
spec (EnvSpec): The environment... | Step env helper.
Args:
env (Environment): Input environment.
spec (EnvSpec): The environment specification.
n (int): Steps.
visualize (bool): Whether to visualize the environment.
serialize_env (bool): Whether to serialize the environment.
| step_env_with_gym_quirks | python | rlworkgroup/garage | tests/helpers.py | https://github.com/rlworkgroup/garage/blob/master/tests/helpers.py | MIT |
def convolve(_input, filter_weights, filter_bias, strides, filters,
in_channels, hidden_nonlinearity):
"""Helper function for performing convolution.
Args:
_input (tf.Tensor): Input tf.Tensor to the CNN.
filter_weights (tuple(tf.Tensor)): The weights of the filters.
filter_... | Helper function for performing convolution.
Args:
_input (tf.Tensor): Input tf.Tensor to the CNN.
filter_weights (tuple(tf.Tensor)): The weights of the filters.
filter_bias (tuple(tf.Tensor)): The bias of the filters.
strides (tuple[int]): The stride of the sliding window. For examp... | convolve | python | rlworkgroup/garage | tests/helpers.py | https://github.com/rlworkgroup/garage/blob/master/tests/helpers.py | MIT |
def recurrent_step_lstm(input_val,
num_units,
step_hidden,
step_cell,
w_x_init,
w_h_init,
b_init,
nonlinearity,
gate_nonlinearit... | Helper function for performing feedforward of a lstm cell.
Args:
input_val (tf.Tensor): Input placeholder.
num_units (int): Hidden dimension for LSTM cell.
step_hidden (tf.Tensor): Place holder for step hidden state.
step_cell (tf.Tensor): Place holder for step cell state.
n... | recurrent_step_lstm | python | rlworkgroup/garage | tests/helpers.py | https://github.com/rlworkgroup/garage/blob/master/tests/helpers.py | MIT |
def recurrent_step_gru(input_val,
num_units,
step_hidden,
w_x_init,
w_h_init,
b_init,
nonlinearity,
gate_nonlinearity,
forget_bias=1.0):... | Helper function for performing feedforward of a GRU cell.
Args:
input_val (tf.Tensor): Input placeholder.
num_units (int): Hidden dimension for GRU cell.
step_hidden (tf.Tensor): Place holder for step hidden state.
nonlinearity (callable): Activation function for intermediate
... | recurrent_step_gru | python | rlworkgroup/garage | tests/helpers.py | https://github.com/rlworkgroup/garage/blob/master/tests/helpers.py | MIT |
def _construct_image_vector(_input, batch, w, h, filter_width, filter_height,
in_shape):
"""Get sliding window of input image.
Args:
_input (tf.Tensor): Input tf.Tensor to the CNN.
batch (int): Batch index.
w (int): Width index.
h (int): Height index.... | Get sliding window of input image.
Args:
_input (tf.Tensor): Input tf.Tensor to the CNN.
batch (int): Batch index.
w (int): Width index.
h (int): Height index.
filter_width (int): Width of the filter.
filter_height (int): Height of the filter.
in_shape (int):... | _construct_image_vector | python | rlworkgroup/garage | tests/helpers.py | https://github.com/rlworkgroup/garage/blob/master/tests/helpers.py | MIT |
def max_pooling(_input, pool_shape, pool_stride, padding='VALID'):
"""Helper function for performing max pooling.
Args:
_input (tf.Tensor): Input tf.Tensor to the CNN.
pool_shape (int): Dimension of the pooling layer.
pool_stride (int): The stride of the pooling layer.
padding (... | Helper function for performing max pooling.
Args:
_input (tf.Tensor): Input tf.Tensor to the CNN.
pool_shape (int): Dimension of the pooling layer.
pool_stride (int): The stride of the pooling layer.
padding (str): The type of padding algorithm to use, either 'SAME'
or '... | max_pooling | python | rlworkgroup/garage | tests/helpers.py | https://github.com/rlworkgroup/garage/blob/master/tests/helpers.py | MIT |
def __init__(self, env=None, env_name='', max_episode_length=100):
"""Create an AutoStepEnv.
Args:
env (gym.Env): Environment to be wrapped.
env_name (str): Name of the environment.
max_episode_length (int): Maximum length of the episode.
"""
if env_n... | Create an AutoStepEnv.
Args:
env (gym.Env): Environment to be wrapped.
env_name (str): Name of the environment.
max_episode_length (int): Maximum length of the episode.
| __init__ | python | rlworkgroup/garage | tests/wrappers.py | https://github.com/rlworkgroup/garage/blob/master/tests/wrappers.py | MIT |
def step(self, action):
"""Step the wrapped environment.
Args:
action (np.ndarray): the action.
Returns:
np.ndarray: Next observation
float: Reward
bool: Termination signal
dict: Environment information
"""
self._episo... | Step the wrapped environment.
Args:
action (np.ndarray): the action.
Returns:
np.ndarray: Next observation
float: Reward
bool: Termination signal
dict: Environment information
| step | python | rlworkgroup/garage | tests/wrappers.py | https://github.com/rlworkgroup/garage/blob/master/tests/wrappers.py | MIT |
def setup_method(self):
"""Setup the Session and default Graph."""
self.graph = tf.Graph()
for c in self.graph.collections:
self.graph.clear_collection(c)
self.graph_manager = self.graph.as_default()
self.graph_manager.__enter__()
self.sess = tf.compat.v1.Sess... | Setup the Session and default Graph. | setup_method | python | rlworkgroup/garage | tests/fixtures/fixtures.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/fixtures.py | MIT |
def teardown_method(self):
"""Teardown the Session and default Graph."""
logger.remove_all()
self.sess.__exit__(None, None, None)
self.sess_manager.__exit__(None, None, None)
self.graph_manager.__exit__(None, None, None)
self.sess.close()
# These del are crucial ... | Teardown the Session and default Graph. | teardown_method | python | rlworkgroup/garage | tests/fixtures/fixtures.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/fixtures.py | MIT |
def train(self, trainer):
"""Obtain samplers and start actual training for each epoch.
See garage.np.algos.RLAlgorithm train().
Args:
trainer (Trainer): Trainer is passed to give algorithm
the access to trainer.step_epochs(), which provides services
... | Obtain samplers and start actual training for each epoch.
See garage.np.algos.RLAlgorithm train().
Args:
trainer (Trainer): Trainer is passed to give algorithm
the access to trainer.step_epochs(), which provides services
such as snapshotting and sampler cont... | train | python | rlworkgroup/garage | tests/fixtures/algos/dummy_algo.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/algos/dummy_algo.py | MIT |
def init_opt(self):
"""Initialize the optimization procedure.
If using tensorflow, this may include declaring all the variables and
compiling functions.
""" | Initialize the optimization procedure.
If using tensorflow, this may include declaring all the variables and
compiling functions.
| init_opt | python | rlworkgroup/garage | tests/fixtures/algos/dummy_tf_algo.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/algos/dummy_tf_algo.py | MIT |
def optimize_policy(self, samples_data):
"""Optimize the policy using the samples.
Args:
samples_data (dict): Processed sample data.
""" | Optimize the policy using the samples.
Args:
samples_data (dict): Processed sample data.
| optimize_policy | python | rlworkgroup/garage | tests/fixtures/algos/dummy_tf_algo.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/algos/dummy_tf_algo.py | MIT |
def render(self, mode='human'):
"""Render.
Args:
mode (str): Render mode.
""" | Render.
Args:
mode (str): Render mode.
| render | python | rlworkgroup/garage | tests/fixtures/envs/dummy/base.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/envs/dummy/base.py | MIT |
def action_space(self):
"""Return an action space.
Returns:
gym.spaces: The action space of the environment.
"""
return akro.Box(low=-5.0,
high=5.0,
shape=self._action_dim,
dtype=np.float32) | Return an action space.
Returns:
gym.spaces: The action space of the environment.
| action_space | python | rlworkgroup/garage | tests/fixtures/envs/dummy/dummy_box_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/envs/dummy/dummy_box_env.py | MIT |
def observation_space(self):
"""Return the observation space.
Returns:
akro.Dict: Observation space.
"""
if self.obs_space_type == 'box':
return gym.spaces.Dict({
'achieved_goal':
gym.spaces.Box(low=-200.,
... | Return the observation space.
Returns:
akro.Dict: Observation space.
| observation_space | python | rlworkgroup/garage | tests/fixtures/envs/dummy/dummy_dict_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/envs/dummy/dummy_dict_env.py | MIT |
def action_space(self):
"""Return the action space.
Returns:
akro.Box: Action space.
"""
if self.act_space_type == 'box':
return akro.Box(low=-5.0, high=5.0, shape=(1, ), dtype=np.float32)
else:
return akro.Discrete(5) | Return the action space.
Returns:
akro.Box: Action space.
| action_space | python | rlworkgroup/garage | tests/fixtures/envs/dummy/dummy_dict_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/envs/dummy/dummy_dict_env.py | MIT |
def compute_reward(self, achieved_goal, goal, info):
"""Function to compute new reward.
Args:
achieved_goal (numpy.ndarray): Achieved goal.
goal (numpy.ndarray): Original desired goal.
info (dict): Extra information.
Returns:
float: New computed ... | Function to compute new reward.
Args:
achieved_goal (numpy.ndarray): Achieved goal.
goal (numpy.ndarray): Original desired goal.
info (dict): Extra information.
Returns:
float: New computed reward.
| compute_reward | python | rlworkgroup/garage | tests/fixtures/envs/dummy/dummy_dict_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/envs/dummy/dummy_dict_env.py | MIT |
def reset(self):
"""Reset the environment.
Returns:
np.ndarray: Environment state.
"""
self.state = np.ones(self._obs_dim, dtype=np.uint8)
self._lives = 5
self.step_called = 0
return self.state | Reset the environment.
Returns:
np.ndarray: Environment state.
| reset | python | rlworkgroup/garage | tests/fixtures/envs/dummy/dummy_discrete_pixel_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/envs/dummy/dummy_discrete_pixel_env.py | MIT |
def step(self, action):
"""Step the environment.
Before gym fixed overflow issue for sample() in
np.uint8 environment, we will handle the sampling here.
We need high=256 since np.random.uniform sample from [low, high)
(includes low, but excludes high).
Args:
... | Step the environment.
Before gym fixed overflow issue for sample() in
np.uint8 environment, we will handle the sampling here.
We need high=256 since np.random.uniform sample from [low, high)
(includes low, but excludes high).
Args:
action (int): Action.
Ret... | step | python | rlworkgroup/garage | tests/fixtures/envs/dummy/dummy_discrete_pixel_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/envs/dummy/dummy_discrete_pixel_env.py | MIT |
def __init__(self, frames):
"""
LazyFrames class from baselines.
Openai baselines use this class for FrameStack environment
wrapper. It is used for testing garage.envs.wrappers.AtariEnv.
garge.envs.wrapper.AtariEnv is used when algorithms are trained
using baselines wrap... |
LazyFrames class from baselines.
Openai baselines use this class for FrameStack environment
wrapper. It is used for testing garage.envs.wrappers.AtariEnv.
garge.envs.wrapper.AtariEnv is used when algorithms are trained
using baselines wrappers, e.g. during benchmarking.
... | __init__ | python | rlworkgroup/garage | tests/fixtures/envs/dummy/dummy_discrete_pixel_env_baselines.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/envs/dummy/dummy_discrete_pixel_env_baselines.py | MIT |
def fixture_exp(snapshot_config, sess):
"""Dummy fixture experiment function.
Args:
snapshot_config (garage.experiment.SnapshotConfig): The snapshot
configuration used by Trainer to create the snapshotter.
If None, it will create one with default settings.
sess (tf.Sessi... | Dummy fixture experiment function.
Args:
snapshot_config (garage.experiment.SnapshotConfig): The snapshot
configuration used by Trainer to create the snapshotter.
If None, it will create one with default settings.
sess (tf.Session): An optional TensorFlow session.
... | fixture_exp | python | rlworkgroup/garage | tests/fixtures/experiment/fixture_experiment.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/experiment/fixture_experiment.py | MIT |
def network_output_spec(self):
"""Network output spec.
Returns:
list[str]: Name of the model outputs, in order.
"""
return [
'all_output', 'step_output', 'step_hidden', 'init_hidden', 'dist'
] | Network output spec.
Returns:
list[str]: Name of the model outputs, in order.
| network_output_spec | python | rlworkgroup/garage | tests/fixtures/models/simple_categorical_gru_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_categorical_gru_model.py | MIT |
def _build(self, obs_input, step_obs_input, step_hidden, name=None):
"""Build model.
Args:
obs_input (tf.Tensor): Entire time-series observation input.
step_obs_input (tf.Tensor): Single timestep observation input.
step_hidden (tf.Tensor): Hidden state for step.
... | Build model.
Args:
obs_input (tf.Tensor): Entire time-series observation input.
step_obs_input (tf.Tensor): Single timestep observation input.
step_hidden (tf.Tensor): Hidden state for step.
name (str): Name of the model, also the name scope.
Returns:
... | _build | python | rlworkgroup/garage | tests/fixtures/models/simple_categorical_gru_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_categorical_gru_model.py | MIT |
def network_output_spec(self):
"""Network output spec.
Returns:
list[str]: Name of the model outputs, in order.
"""
return [
'all_output', 'step_output', 'step_hidden', 'step_cell',
'init_hidden', 'init_cell', 'dist'
] | Network output spec.
Returns:
list[str]: Name of the model outputs, in order.
| network_output_spec | python | rlworkgroup/garage | tests/fixtures/models/simple_categorical_lstm_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_categorical_lstm_model.py | MIT |
def _build(self,
obs_input,
step_obs_input,
step_hidden,
step_cell,
name=None):
"""Build model.
Args:
obs_input (tf.Tensor): Entire time-series observation input.
step_obs_input (tf.Tensor): Single timest... | Build model.
Args:
obs_input (tf.Tensor): Entire time-series observation input.
step_obs_input (tf.Tensor): Single timestep observation input.
step_hidden (tf.Tensor): Hidden state for step.
step_cell (tf.Tensor): Cell state for step.
name (str): Name... | _build | python | rlworkgroup/garage | tests/fixtures/models/simple_categorical_lstm_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_categorical_lstm_model.py | MIT |
def _build(self, obs_input, name=None):
"""Build model.
Args:
obs_input (tf.Tensor): Observation inputs.
name (str): Name of the model, also the name scope.
Returns:
tf.Tensor: Network outputs.
tfp.distributions.OneHotCategorical: Distribution.
... | Build model.
Args:
obs_input (tf.Tensor): Observation inputs.
name (str): Name of the model, also the name scope.
Returns:
tf.Tensor: Network outputs.
tfp.distributions.OneHotCategorical: Distribution.
| _build | python | rlworkgroup/garage | tests/fixtures/models/simple_categorical_mlp_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_categorical_mlp_model.py | MIT |
def _build(self, obs_input, name=None):
"""Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
name (str): Inner model name, also the variable scope of the
inner model, if exist. One example is
garage.tf.mo... | Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
name (str): Inner model name, also the variable scope of the
inner model, if exist. One example is
garage.tf.models.Sequential.
Return:
tf.Te... | _build | python | rlworkgroup/garage | tests/fixtures/models/simple_cnn_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_cnn_model.py | MIT |
def _build(self, obs_input, name=None):
"""Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
name (str): Inner model name, also the variable scope of the
inner model, if exist. One example is
garage.tf.mo... | Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
name (str): Inner model name, also the variable scope of the
inner model, if exist. One example is
garage.tf.models.Sequential.
Return:
tf.Te... | _build | python | rlworkgroup/garage | tests/fixtures/models/simple_cnn_model_with_max_pooling.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_cnn_model_with_max_pooling.py | MIT |
def _build(self, obs_input, step_obs_input, step_hidden, name=None):
"""Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Place holder for entire time-series
inputs.
step_obs_input (tf.Tensor): Place holder for step inputs.
step_hid... | Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Place holder for entire time-series
inputs.
step_obs_input (tf.Tensor): Place holder for step inputs.
step_hidden (tf.Tensor): Place holder for step hidden state.
name (str): Inn... | _build | python | rlworkgroup/garage | tests/fixtures/models/simple_gru_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_gru_model.py | MIT |
def network_input_spec(self):
"""Network input spec.
Return:
list[str]: List of key(str) for the network outputs.
"""
return [
'full_input', 'step_input', 'step_hidden_input', 'step_cell_input'
] | Network input spec.
Return:
list[str]: List of key(str) for the network outputs.
| network_input_spec | python | rlworkgroup/garage | tests/fixtures/models/simple_lstm_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_lstm_model.py | MIT |
def network_output_spec(self):
"""Network output spec.
Return:
list[str]: List of key(str) for the network outputs.
"""
return [
'all_output', 'step_output', 'step_hidden', 'step_cell',
'init_hidden', 'init_cell'
] | Network output spec.
Return:
list[str]: List of key(str) for the network outputs.
| network_output_spec | python | rlworkgroup/garage | tests/fixtures/models/simple_lstm_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_lstm_model.py | MIT |
def _build(self,
obs_input,
step_obs_input,
step_hidden,
step_cell,
name=None):
"""Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Place holder for entire time-series
inputs.
... | Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Place holder for entire time-series
inputs.
step_obs_input (tf.Tensor): Place holder for step inputs.
step_hidden (tf.Tensor): Place holder for step hidden state.
step_cell (tf.T... | _build | python | rlworkgroup/garage | tests/fixtures/models/simple_lstm_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_lstm_model.py | MIT |
def _build(self, obs_input, act_input, name=None):
"""Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
act_input (tf.Tensor): Tensor input for action.
name (str): Inner model name, also the variable scope of the
... | Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
act_input (tf.Tensor): Tensor input for action.
name (str): Inner model name, also the variable scope of the
inner model, if exist. One example is
gar... | _build | python | rlworkgroup/garage | tests/fixtures/models/simple_mlp_merge_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_mlp_merge_model.py | MIT |
def _build(self, obs_input, name=None):
"""Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
name (str): Inner model name, also the variable scope of the
inner model, if exist. One example is
garage.tf.mo... | Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
name (str): Inner model name, also the variable scope of the
inner model, if exist. One example is
garage.tf.models.Sequential.
Return:
tf.Te... | _build | python | rlworkgroup/garage | tests/fixtures/models/simple_mlp_model.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/models/simple_mlp_model.py | MIT |
def get_actions(self, observations):
"""Get multiple actions from this policy for the input observations.
Args:
observations (numpy.ndarray): Observations from environment.
Returns:
numpy.ndarray: Predicted actions.
dict: Distribution parameters.
""... | Get multiple actions from this policy for the input observations.
Args:
observations (numpy.ndarray): Observations from environment.
Returns:
numpy.ndarray: Predicted actions.
dict: Distribution parameters.
| get_actions | python | rlworkgroup/garage | tests/fixtures/policies/dummy_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/policies/dummy_policy.py | MIT |
def __getstate__(self):
"""Object.__getstate__.
Returns:
dict: the state to be pickled for the instance.
"""
new_dict = super().__getstate__()
del new_dict['_q_val']
return new_dict | Object.__getstate__.
Returns:
dict: the state to be pickled for the instance.
| __getstate__ | python | rlworkgroup/garage | tests/fixtures/q_functions/simple_q_function.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/q_functions/simple_q_function.py | MIT |
def ray_local_session_fixture():
"""Initializes Ray and shuts down Ray in local mode.
Yields:
None: Yield is for purposes of pytest module style.
All statements before the yield are apart of module setup, and all
statements after the yield are apart of module teardown.
"""
... | Initializes Ray and shuts down Ray in local mode.
Yields:
None: Yield is for purposes of pytest module style.
All statements before the yield are apart of module setup, and all
statements after the yield are apart of module teardown.
| ray_local_session_fixture | python | rlworkgroup/garage | tests/fixtures/sampler/ray_fixtures.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/sampler/ray_fixtures.py | MIT |
def ray_session_fixture():
"""Initializes Ray and shuts down Ray.
Yields:
None: Yield is for purposes of pytest module style.
All statements before the yield are apart of module setup, and all
statements after the yield are apart of module teardown.
"""
if not ray.is_in... | Initializes Ray and shuts down Ray.
Yields:
None: Yield is for purposes of pytest module style.
All statements before the yield are apart of module setup, and all
statements after the yield are apart of module teardown.
| ray_session_fixture | python | rlworkgroup/garage | tests/fixtures/sampler/ray_fixtures.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/sampler/ray_fixtures.py | MIT |
def train(self, trainer):
"""Obtain samplers and start actual training for each epoch.
Args:
trainer (Trainer): Trainer is passed to give algorithm
the access to trainer.step_epochs(), which provides services
such as snapshotting and sampler control.
... | Obtain samplers and start actual training for each epoch.
Args:
trainer (Trainer): Trainer is passed to give algorithm
the access to trainer.step_epochs(), which provides services
such as snapshotting and sampler control.
| train | python | rlworkgroup/garage | tests/fixtures/tf/algos/dummy_off_policy_algo.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/tf/algos/dummy_off_policy_algo.py | MIT |
def train_once(self, itr, paths):
"""Perform one step of policy optimization given one batch of samples.
Args:
itr (int): Iteration number.
paths (list[dict]): A list of collected paths.
""" | Perform one step of policy optimization given one batch of samples.
Args:
itr (int): Iteration number.
paths (list[dict]): A list of collected paths.
| train_once | python | rlworkgroup/garage | tests/fixtures/tf/algos/dummy_off_policy_algo.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/tf/algos/dummy_off_policy_algo.py | MIT |
def optimize_policy(self, samples_data):
"""Optimize the policy using the samples.
Args:
samples_data (dict): Processed sample data.
""" | Optimize the policy using the samples.
Args:
samples_data (dict): Processed sample data.
| optimize_policy | python | rlworkgroup/garage | tests/fixtures/tf/algos/dummy_off_policy_algo.py | https://github.com/rlworkgroup/garage/blob/master/tests/fixtures/tf/algos/dummy_off_policy_algo.py | MIT |
def test_tf_make_optimizer_with_type(self):
"""Test make_optimizer function with type as first argument."""
optimizer_type = tf.compat.v1.train.AdamOptimizer
lr = 0.123
optimizer = make_optimizer(optimizer_type,
learning_rate=lr,
... | Test make_optimizer function with type as first argument. | test_tf_make_optimizer_with_type | python | rlworkgroup/garage | tests/garage/test_functions.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/test_functions.py | MIT |
def test_tf_make_optimizer_with_tuple(self):
"""Test make_optimizer function with tuple as first argument."""
lr = 0.123
optimizer_type = (tf.compat.v1.train.AdamOptimizer, {
'learning_rate': lr
})
optimizer = make_optimizer(optimizer_type)
# pylint: disable=i... | Test make_optimizer function with tuple as first argument. | test_tf_make_optimizer_with_tuple | python | rlworkgroup/garage | tests/garage/test_functions.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/test_functions.py | MIT |
def test_torch_make_optimizer_with_type(self):
"""Test make_optimizer function with type as first argument."""
optimizer_type = torch.optim.Adam
module = torch.nn.Linear(2, 1)
lr = 0.123
optimizer = make_optimizer(optimizer_type, module=module, lr=lr)
assert isinstance(op... | Test make_optimizer function with type as first argument. | test_torch_make_optimizer_with_type | python | rlworkgroup/garage | tests/garage/test_functions.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/test_functions.py | MIT |
def test_torch_make_optimizer_with_tuple(self):
"""Test make_optimizer function with tuple as first argument."""
optimizer_type = (torch.optim.Adam, {'lr': 0.1})
module = torch.nn.Linear(2, 1)
optimizer = make_optimizer(optimizer_type, module=module)
# pylint: disable=isinstance-... | Test make_optimizer function with tuple as first argument. | test_torch_make_optimizer_with_tuple | python | rlworkgroup/garage | tests/garage/test_functions.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/test_functions.py | MIT |
def _init_multi_env_wrapper(self,
env_names,
sample_strategy=uniform_random_strategy):
"""helper function to initialize multi_env_wrapper
Args:
env_names (list(str)): List of Environment names.
sample_strategy (func... | helper function to initialize multi_env_wrapper
Args:
env_names (list(str)): List of Environment names.
sample_strategy (func): A sampling strategy.
Returns:
garage.envs.multi_env_wrapper: Multi env wrapper.
| _init_multi_env_wrapper | python | rlworkgroup/garage | tests/garage/envs/test_multi_env_wrapper.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/test_multi_env_wrapper.py | MIT |
def test_tasks_from_same_env(self):
"""test init with multiple tasks from same env"""
envs = ['CartPole-v0', 'CartPole-v0']
mt_env = self._init_multi_env_wrapper(envs)
assert mt_env.num_tasks == 2 | test init with multiple tasks from same env | test_tasks_from_same_env | python | rlworkgroup/garage | tests/garage/envs/test_multi_env_wrapper.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/test_multi_env_wrapper.py | MIT |
def test_tasks_from_different_envs(self):
"""test init with multiple tasks from different env"""
envs = ['CartPole-v0', 'CartPole-v1']
mt_env = self._init_multi_env_wrapper(envs)
assert mt_env.num_tasks == 2 | test init with multiple tasks from different env | test_tasks_from_different_envs | python | rlworkgroup/garage | tests/garage/envs/test_multi_env_wrapper.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/test_multi_env_wrapper.py | MIT |
def test_raise_exception_when_different_obs_space(self):
"""test if exception is raised when using tasks with different obs space""" # noqa: E501
envs = ['CartPole-v0', 'Blackjack-v0']
with pytest.raises(ValueError):
_ = self._init_multi_env_wrapper(envs) | test if exception is raised when using tasks with different obs space | test_raise_exception_when_different_obs_space | python | rlworkgroup/garage | tests/garage/envs/test_multi_env_wrapper.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/test_multi_env_wrapper.py | MIT |
def test_raise_exception_when_different_action_space(self):
"""test if exception is raised when using tasks with different action space""" # noqa: E501
envs = ['LunarLander-v2', 'LunarLanderContinuous-v2']
with pytest.raises(ValueError):
_ = self._init_multi_env_wrapper(envs) | test if exception is raised when using tasks with different action space | test_raise_exception_when_different_action_space | python | rlworkgroup/garage | tests/garage/envs/test_multi_env_wrapper.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/test_multi_env_wrapper.py | MIT |
def test_default_active_task_is_none(self):
"""test if default active task is none"""
envs = ['CartPole-v0', 'CartPole-v1']
mt_env = self._init_multi_env_wrapper(
envs, sample_strategy=round_robin_strategy)
assert mt_env._active_task_index is None | test if default active task is none | test_default_active_task_is_none | python | rlworkgroup/garage | tests/garage/envs/test_multi_env_wrapper.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/test_multi_env_wrapper.py | MIT |
def test_one_hot_observation_space(self):
"""test one hot representation of observation space"""
envs = ['CartPole-v0', 'CartPole-v1']
mt_env = self._init_multi_env_wrapper(envs)
cartpole = GymEnv('CartPole-v0')
cartpole_lb, cartpole_ub = cartpole.observation_space.bounds
... | test one hot representation of observation space | test_one_hot_observation_space | python | rlworkgroup/garage | tests/garage/envs/test_multi_env_wrapper.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/test_multi_env_wrapper.py | MIT |
def test_task_remains_same_between_multiple_step_calls(self):
"""test if active_task remains same between multiple step calls"""
envs = ['CartPole-v0', 'CartPole-v1']
mt_env = self._init_multi_env_wrapper(
envs, sample_strategy=round_robin_strategy)
mt_env.reset()
tas... | test if active_task remains same between multiple step calls | test_task_remains_same_between_multiple_step_calls | python | rlworkgroup/garage | tests/garage/envs/test_multi_env_wrapper.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/test_multi_env_wrapper.py | MIT |
def test_one_hot_observation(self):
"""test if output of step function is correct"""
envs = ['CartPole-v0', 'CartPole-v0']
mt_env = self._init_multi_env_wrapper(
envs, sample_strategy=round_robin_strategy)
obs, _ = mt_env.reset()
assert (obs[-2:] == np.array([1., 0.]... | test if output of step function is correct | test_one_hot_observation | python | rlworkgroup/garage | tests/garage/envs/test_multi_env_wrapper.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/test_multi_env_wrapper.py | MIT |
def test_pickleable(env_ids):
"""Test Bullet environments are pickle-able"""
for env_id in env_ids:
# extract id string
env_id = env_id.replace('- ', '')
env = BulletEnv(env_id)
round_trip = pickle.loads(pickle.dumps(env))
assert round_trip
env.close() | Test Bullet environments are pickle-able | test_pickleable | python | rlworkgroup/garage | tests/garage/envs/bullet/test_bullet_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/bullet/test_bullet_env.py | MIT |
def test_pickle_creates_new_server(env_ids):
"""Test pickling a Bullet environment creates a new connection.
If all pickling create new connections, no repetition of client id
should be found.
"""
n_env = 4
for env_id in env_ids:
# extract id string
env_id = env_id.replace('- ',... | Test pickling a Bullet environment creates a new connection.
If all pickling create new connections, no repetition of client id
should be found.
| test_pickle_creates_new_server | python | rlworkgroup/garage | tests/garage/envs/bullet/test_bullet_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/bullet/test_bullet_env.py | MIT |
def test_grayscale_reset(self):
"""
RGB to grayscale conversion using scikit-image.
Weights used for conversion:
Y = 0.2125 R + 0.7154 G + 0.0721 B
Reference:
http://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.rgb2grey
"""
grayscale_ou... |
RGB to grayscale conversion using scikit-image.
Weights used for conversion:
Y = 0.2125 R + 0.7154 G + 0.0721 B
Reference:
http://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.rgb2grey
| test_grayscale_reset | python | rlworkgroup/garage | tests/garage/envs/wrappers/test_grayscale_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/wrappers/test_grayscale_env.py | MIT |
def test_deterministic_tfp_seed_stream():
"""Test deterministic behavior of TFP SeedStream"""
deterministic.set_seed(0)
with tf.compat.v1.Session() as sess:
rand_tensor = sess.run(
tf.random.uniform((5, 5),
seed=deterministic.get_tf_seed_stream(),
... | Test deterministic behavior of TFP SeedStream | test_deterministic_tfp_seed_stream | python | rlworkgroup/garage | tests/garage/experiment/test_deterministic.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/experiment/test_deterministic.py | MIT |
def setup_method(self):
"""Setup method which is called before every test."""
self.env = normalize(GymEnv('InvertedDoublePendulum-v2'))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=torch.tanh,
... | Setup method which is called before every test. | setup_method | python | rlworkgroup/garage | tests/garage/experiment/test_trainer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/experiment/test_trainer.py | MIT |
def test_ddpg_pendulum(self):
"""Test DDPG with Pendulum environment.
This environment has a [-3, 3] action_space bound.
"""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
env = normalize(
GymEnv('InvertedPendulum-v2', max_episode_length=100))
... | Test DDPG with Pendulum environment.
This environment has a [-3, 3] action_space bound.
| test_ddpg_pendulum | python | rlworkgroup/garage | tests/garage/tf/algos/test_ddpg.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ddpg.py | MIT |
def test_ddpg_pendulum_with_decayed_weights(self):
"""Test DDPG with Pendulum environment and decayed weights.
This environment has a [-3, 3] action_space bound.
"""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
env = normalize(
GymEnv('Inverted... | Test DDPG with Pendulum environment and decayed weights.
This environment has a [-3, 3] action_space bound.
| test_ddpg_pendulum_with_decayed_weights | python | rlworkgroup/garage | tests/garage/tf/algos/test_ddpg.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ddpg.py | MIT |
def test_npo_with_unknown_pg_loss(self):
"""Test NPO with unkown pg loss."""
with pytest.raises(ValueError, match='Invalid pg_loss'):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
sampler=self.sampler,... | Test NPO with unkown pg loss. | test_npo_with_unknown_pg_loss | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_npo_with_invalid_entropy_method(self):
"""Test NPO with invalid entropy method."""
with pytest.raises(ValueError, match='Invalid entropy_method'):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
... | Test NPO with invalid entropy method. | test_npo_with_invalid_entropy_method | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_npo_with_max_entropy_and_center_adv(self):
"""Test NPO with max entropy and center_adv."""
with pytest.raises(ValueError):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
sampler=self.sampler,
... | Test NPO with max entropy and center_adv. | test_npo_with_max_entropy_and_center_adv | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_npo_with_max_entropy_and_no_stop_entropy_gradient(self):
"""Test NPO with max entropy and false stop_entropy_gradient."""
with pytest.raises(ValueError):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
... | Test NPO with max entropy and false stop_entropy_gradient. | test_npo_with_max_entropy_and_no_stop_entropy_gradient | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_npo_with_invalid_no_entropy_configuration(self):
"""Test NPO with invalid no entropy configuration."""
with pytest.raises(ValueError):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
sampler=sel... | Test NPO with invalid no entropy configuration. | test_npo_with_invalid_no_entropy_configuration | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_ppo_with_maximum_entropy(self):
"""Test PPO with maxium entropy method."""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = PPO(env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
... | Test PPO with maxium entropy method. | test_ppo_with_maximum_entropy | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_with_neg_log_likeli_entropy_estimation_and_max(self):
"""
Test PPO with negative log likelihood entropy estimation and max
entropy method.
"""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = PPO(env_spec=self.env.spec,
... |
Test PPO with negative log likelihood entropy estimation and max
entropy method.
| test_ppo_with_neg_log_likeli_entropy_estimation_and_max | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_with_neg_log_likeli_entropy_estimation_and_regularized(self):
"""
Test PPO with negative log likelihood entropy estimation and
regularized entropy method.
"""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = PPO(env_spec=self.env.spec,
... |
Test PPO with negative log likelihood entropy estimation and
regularized entropy method.
| test_ppo_with_neg_log_likeli_entropy_estimation_and_regularized | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_with_regularized_entropy(self):
"""Test PPO with regularized entropy method."""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = PPO(env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
... | Test PPO with regularized entropy method. | test_ppo_with_regularized_entropy | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_pendulum_recurrent_continuous_baseline(self):
"""Test PPO with Pendulum environment and recurrent policy."""
with TFTrainer(snapshot_config) as trainer:
env = normalize(
GymEnv('InvertedDoublePendulum-v2', max_episode_length=100))
policy = GaussianLST... | Test PPO with Pendulum environment and recurrent policy. | test_ppo_pendulum_recurrent_continuous_baseline | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_pendulum_lstm(self):
"""Test PPO with Pendulum environment and recurrent policy."""
with TFTrainer(snapshot_config) as trainer:
env = normalize(
GymEnv('InvertedDoublePendulum-v2', max_episode_length=100))
lstm_policy = GaussianLSTMPolicy(env_spec=env... | Test PPO with Pendulum environment and recurrent policy. | test_ppo_pendulum_lstm | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_pendulum_gru(self):
"""Test PPO with Pendulum environment and recurrent policy."""
with TFTrainer(snapshot_config) as trainer:
env = normalize(
GymEnv('InvertedDoublePendulum-v2', max_episode_length=100))
gru_policy = GaussianGRUPolicy(env_spec=env.sp... | Test PPO with Pendulum environment and recurrent policy. | test_ppo_pendulum_gru | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_reps_cartpole(self):
"""Test REPS with gym Cartpole environment."""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
env = GymEnv('CartPole-v0')
policy = CategoricalMLPPolicy(env_spec=env.spec,
hidden_sizes=[32, 32])
... | Test REPS with gym Cartpole environment. | test_reps_cartpole | python | rlworkgroup/garage | tests/garage/tf/algos/test_reps.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_reps.py | MIT |
def circle(r, n):
"""Generate n points on a circle of radius r.
Args:
r (float): Radius of the circle.
n (int): Number of points to generate.
Yields:
tuple(float, float): Coordinate of a point.
"""
for t in np... | Generate n points on a circle of radius r.
Args:
r (float): Radius of the circle.
n (int): Number of points to generate.
Yields:
tuple(float, float): Coordinate of a point.
| circle | python | rlworkgroup/garage | tests/garage/tf/algos/test_te.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_te.py | MIT |
def test_trpo_unknown_kl_constraint(self):
"""Test TRPO with unkown KL constraints."""
with pytest.raises(ValueError, match='Invalid kl_constraint'):
TRPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
samp... | Test TRPO with unkown KL constraints. | test_trpo_unknown_kl_constraint | python | rlworkgroup/garage | tests/garage/tf/algos/test_trpo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_trpo.py | MIT |
def test_trpo_soft_kl_constraint(self):
"""Test TRPO with unkown KL constraints."""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = TRPO(env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
... | Test TRPO with unkown KL constraints. | test_trpo_soft_kl_constraint | python | rlworkgroup/garage | tests/garage/tf/algos/test_trpo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_trpo.py | MIT |
def test_cg(self):
"""Solve Ax = b using Conjugate gradient method."""
a = np.linspace(-np.pi, np.pi, 25).reshape((5, 5))
a = a.T.dot(a) # make sure a is positive semi-definite
b = np.linspace(-np.pi, np.pi, 5)
x = _cg(a.dot, b, cg_iters=5)
assert np.allclose(a.dot(x), b... | Solve Ax = b using Conjugate gradient method. | test_cg | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_pearl_mutter_hvp_1x1(self):
"""Test Hessian-vector product for a function with one variable."""
policy = HelperPolicy(n_vars=1)
x = policy.get_params()[0]
a_val = np.array([5.0])
a = tf.constant([0.0])
f = a * (x**2)
expected_hessian = 2 * a_val
v... | Test Hessian-vector product for a function with one variable. | test_pearl_mutter_hvp_1x1 | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_pearl_mutter_hvp_2x2(self, a_val, b_val, x_val, y_val, vector):
"""Test Hessian-vector product for a function with two variables."""
a_val = [a_val]
b_val = [b_val]
vector = np.array([vector], dtype=np.float32)
policy = HelperPolicy(n_vars=2)
params = policy.get... | Test Hessian-vector product for a function with two variables. | test_pearl_mutter_hvp_2x2 | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_pearl_mutter_hvp_2x2_non_diagonal(self, a_val, b_val, x_val,
y_val, vector):
"""Test Hessian-vector product for a function with two variables whose Hessian
is non-diagonal.
"""
a_val = [a_val]
b_val = [b_val]
vector ... | Test Hessian-vector product for a function with two variables whose Hessian
is non-diagonal.
| test_pearl_mutter_hvp_2x2_non_diagonal | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_finite_difference_hvp(self):
"""Test Hessian-vector product for a function with one variable."""
policy = HelperPolicy(n_vars=1)
x = policy.get_params()[0]
a_val = np.array([5.0])
a = tf.constant([0.0])
f = a * (x**2)
expected_hessian = 2 * a_val
... | Test Hessian-vector product for a function with one variable. | test_finite_difference_hvp | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_finite_difference_hvp_2x2(self, a_val, b_val, x_val, y_val,
vector):
"""Test Hessian-vector product for a function with two variables."""
a_val = [a_val]
b_val = [b_val]
vector = np.array([vector], dtype=np.float32)
policy = Helper... | Test Hessian-vector product for a function with two variables. | test_finite_difference_hvp_2x2 | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_finite_difference_hvp_2x2_non_diagonal(self, a_val, b_val, x_val,
y_val, vector):
"""Test Hessian-vector product for a function with two variables whose Hessian
is non-diagonal.
"""
a_val = [a_val]
b_val = [b_val]
... | Test Hessian-vector product for a function with two variables whose Hessian
is non-diagonal.
| test_finite_difference_hvp_2x2_non_diagonal | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_does_not_support_dict_obs_space(self, filters, strides, padding,
hidden_sizes):
"""Test that policy raises error if passed a dict obs space."""
env = GymEnv(DummyDictEnv(act_space_type='discrete'))
with pytest.raises(ValueError):
... | Test that policy raises error if passed a dict obs space. | test_does_not_support_dict_obs_space | python | rlworkgroup/garage | tests/garage/tf/policies/test_categorical_cnn_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/policies/test_categorical_cnn_policy.py | MIT |
def test_does_not_support_dict_obs_space(self):
"""Test that policy raises error if passed a dict obs space."""
env = GymEnv(DummyDictEnv(act_space_type='discrete'))
with pytest.raises(ValueError):
qf = SimpleQFunction(env.spec,
name='does_not_support... | Test that policy raises error if passed a dict obs space. | test_does_not_support_dict_obs_space | python | rlworkgroup/garage | tests/garage/tf/policies/test_discrete_qf_argmax_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/policies/test_discrete_qf_argmax_policy.py | MIT |
def test_invalid_action_spaces(self):
"""Test that policy raises error if passed a dict obs space."""
env = GymEnv(DummyDictEnv(act_space_type='box'))
with pytest.raises(ValueError):
qf = SimpleQFunction(env.spec)
DiscreteQFArgmaxPolicy(env_spec=env.spec, qf=qf) | Test that policy raises error if passed a dict obs space. | test_invalid_action_spaces | python | rlworkgroup/garage | tests/garage/tf/policies/test_discrete_qf_argmax_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/policies/test_discrete_qf_argmax_policy.py | MIT |
def test_obs_unflattened(self):
"""Test if a flattened image obs is passed to get_action
then it is unflattened.
"""
obs = self.env.observation_space.sample()
action, _ = self.policy.get_action(
self.env.observation_space.flatten(obs))
self.env.step(action) | Test if a flattened image obs is passed to get_action
then it is unflattened.
| test_obs_unflattened | python | rlworkgroup/garage | tests/garage/tf/policies/test_discrete_qf_argmax_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/policies/test_discrete_qf_argmax_policy.py | MIT |
def test_utils_set_gpu_mode():
"""Test setting gpu mode to False to force CPU."""
if torch.cuda.is_available():
set_gpu_mode(mode=True)
assert global_device() == torch.device('cuda:0')
assert tu._USE_GPU
else:
set_gpu_mode(mode=False)
assert global_device() == torch.d... | Test setting gpu mode to False to force CPU. | test_utils_set_gpu_mode | python | rlworkgroup/garage | tests/garage/torch/test_functions.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/test_functions.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.