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 __init__(
self,
input_tensor_spec,
preprocessing_layers=None,
preprocessing_combiner=None,
conv_layer_params=None,
fc_layer_params=(75, 40),
dropout_layer_params=None,
activation_fn=tf.keras.activations.relu,
kernel_initializer=None,
batch_squash=True,
... | Creates an instance of `ValueNetwork`.
Network supports calls with shape outer_rank + observation_spec.shape. Note
outer_rank must be at least 1.
Args:
input_tensor_spec: A `tensor_spec.TensorSpec` or a tuple of specs
representing the input observations.
preprocessing_layers: (Optional... | __init__ | python | tensorflow/agents | tf_agents/networks/value_network.py | https://github.com/tensorflow/agents/blob/master/tf_agents/networks/value_network.py | Apache-2.0 |
def __init__(
self,
input_tensor_spec,
preprocessing_layers=None,
preprocessing_combiner=None,
conv_layer_params=None,
input_fc_layer_params=(75, 40),
input_dropout_layer_params=None,
lstm_size=(40,),
output_fc_layer_params=(75, 40),
activation_fn=tf.keras.act... | Creates an instance of `ValueRnnNetwork`.
Network supports calls with shape outer_rank + input_tensor_shape.shape.
Note outer_rank must be at least 1.
Args:
input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the
input observations.
preprocessing_layers: (Optional.) A ne... | __init__ | python | tensorflow/agents | tf_agents/networks/value_rnn_network.py | https://github.com/tensorflow/agents/blob/master/tf_agents/networks/value_rnn_network.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedTensorSpec,
actor_network: network.Network,
policy_state_spec: types.NestedTensorSpec = (),
info_spec: types.NestedTensorSpec = (),
observation_normalizer: Optional[
tensor_normalizer.TensorNorm... | Builds an Actor Policy given an actor network.
Args:
time_step_spec: A `TimeStep` spec of the expected time_steps.
action_spec: A nest of `BoundedTensorSpec` representing the actions.
actor_network: An instance of a `tf_agents.networks.network.Network` to be
used by the policy. The networ... | __init__ | python | tensorflow/agents | tf_agents/policies/actor_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/actor_policy.py | Apache-2.0 |
def __init__(self, policy_saver: policy_saver_module.PolicySaver):
"""Initialize an AsyncPolicySaver.
Args:
policy_saver: An instance of a `policy_saver.PolicySaver`.
"""
self._policy_saver = policy_saver
self._save_condition_variable = threading.Condition()
# These vars should only be a... | Initialize an AsyncPolicySaver.
Args:
policy_saver: An instance of a `policy_saver.PolicySaver`.
| __init__ | python | tensorflow/agents | tf_agents/policies/async_policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/async_policy_saver.py | Apache-2.0 |
def _save_loop(self):
"""Helper method for the saving thread to wait and execute save requests."""
while True:
with self._save_condition_variable:
while not self._export_dir:
self._save_condition_variable.wait()
if self._join_save_thread:
return
if self._sav... | Helper method for the saving thread to wait and execute save requests. | _save_loop | python | tensorflow/agents | tf_agents/policies/async_policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/async_policy_saver.py | Apache-2.0 |
def _save(self, export_dir, saving_checkpoint, blocking):
"""Helper save method, generalizes over save and save_checkpoint."""
self._assert_save_thread_is_alive()
if blocking:
with self._save_condition_variable:
while self._export_dir:
logging.info("Waiting for AsyncPolicySaver to f... | Helper save method, generalizes over save and save_checkpoint. | _save | python | tensorflow/agents | tf_agents/policies/async_policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/async_policy_saver.py | Apache-2.0 |
def flush(self):
"""Blocks until there is no saving happening."""
with self._save_condition_variable:
while self._export_dir:
logging.info("Waiting for AsyncPolicySaver to finish.")
self._save_condition_variable.wait() | Blocks until there is no saving happening. | flush | python | tensorflow/agents | tf_agents/policies/async_policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/async_policy_saver.py | Apache-2.0 |
def close(self):
"""Blocks until there is no saving happening and kills the save_thread."""
with self._save_condition_variable:
while self._export_dir:
logging.info("Waiting for AsyncPolicySaver to finish.")
self._save_condition_variable.wait()
self._join_save_thread = True
sel... | Blocks until there is no saving happening and kills the save_thread. | close | python | tensorflow/agents | tf_agents/policies/async_policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/async_policy_saver.py | Apache-2.0 |
def __init__(
self, policies: Sequence[py_policy.PyPolicy], multithreading: bool = True
):
"""Batch together multiple (non-batched) py policies.
The policies can be different but must use the same action and
observation specs.
Args:
policies: List python policies (must be non-batched).
... | Batch together multiple (non-batched) py policies.
The policies can be different but must use the same action and
observation specs.
Args:
policies: List python policies (must be non-batched).
multithreading: Python bool describing whether interactions with the given
policies should ha... | __init__ | python | tensorflow/agents | tf_agents/policies/batched_py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/batched_py_policy.py | Apache-2.0 |
def _action(
self,
time_step: ts.TimeStep,
policy_state: types.NestedArray,
seed: Optional[types.Seed] = None,
) -> ps.PolicyStep:
"""Forward a batch of time_step and policy_states to the wrapped policies.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
... | Forward a batch of time_step and policy_states to the wrapped policies.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: An Array, or a nested dict, list or tuple of Arrays
representing the previous policy_state.
seed: Seed value used to initialize a ... | _action | python | tensorflow/agents | tf_agents/policies/batched_py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/batched_py_policy.py | Apache-2.0 |
def _execute_policy(zip_results_element) -> ps.PolicyStep:
"""Called on each element of zip return value, in _action method."""
(policy, time_step, policy_state) = zip_results_element
return policy.action(time_step, policy_state) | Called on each element of zip return value, in _action method. | _execute_policy | python | tensorflow/agents | tf_agents/policies/batched_py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/batched_py_policy.py | Apache-2.0 |
def __init__(
self,
policy: tf_policy.TFPolicy,
temperature: types.FloatOrReturningFloat = 1.0,
name: Optional[Text] = None,
):
"""Builds a BoltzmannPolicy wrapping the given policy.
Args:
policy: A policy implementing the tf_policy.TFPolicy interface, using a
distributi... | Builds a BoltzmannPolicy wrapping the given policy.
Args:
policy: A policy implementing the tf_policy.TFPolicy interface, using a
distribution parameterized by logits.
temperature: Tensor or function that returns the temperature for sampling
when `action` is called. This parameter appli... | __init__ | python | tensorflow/agents | tf_agents/policies/boltzmann_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/boltzmann_policy.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedTensorSpec,
q_network: network.Network,
min_q_value: float,
max_q_value: float,
observation_and_action_constraint_splitter: Optional[
types.Splitter
] = None,
temperature: types.Floa... | Builds a categorical Q-policy given a categorical Q-network.
Args:
time_step_spec: A `TimeStep` spec of the expected time_steps.
action_spec: A `BoundedTensorSpec` representing the actions.
q_network: A network.Network to use for our policy.
min_q_value: A float specifying the minimum Q-val... | __init__ | python | tensorflow/agents | tf_agents/policies/categorical_q_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/categorical_q_policy.py | Apache-2.0 |
def _distribution(self, time_step, policy_state):
"""Generates the distribution over next actions given the time_step.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of Tensors
representing the previous policy... | Generates the distribution over next actions given the time_step.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of Tensors
representing the previous policy_state.
Returns:
A tfp.distributions.Categoric... | _distribution | python | tensorflow/agents | tf_agents/policies/categorical_q_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/categorical_q_policy.py | Apache-2.0 |
def __init__(
self,
policy: tf_policy.TFPolicy,
epsilon: types.FloatOrReturningFloat,
exploration_mask: Optional[Sequence[int]] = None,
info_fields_to_inherit_from_greedy: Sequence[Text] = (),
name: Optional[Text] = None,
):
"""Builds an epsilon-greedy MixturePolicy wrapping th... | Builds an epsilon-greedy MixturePolicy wrapping the given policy.
Args:
policy: A policy implementing the tf_policy.TFPolicy interface.
epsilon: The probability of taking the random action represented as a
float scalar, a scalar Tensor of shape=(), or a callable that returns a
float sca... | __init__ | python | tensorflow/agents | tf_agents/policies/epsilon_greedy_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/epsilon_greedy_policy.py | Apache-2.0 |
def __init__(
self,
wrapped_policy: tf_policy.TFPolicy,
scale: types.Float = 1.0,
clip: bool = True,
name: Optional[Text] = None,
):
"""Builds an GaussianPolicy wrapping wrapped_policy.
Args:
wrapped_policy: A policy to wrap and add OU noise to.
scale: Stddev of the ... | Builds an GaussianPolicy wrapping wrapped_policy.
Args:
wrapped_policy: A policy to wrap and add OU noise to.
scale: Stddev of the Gaussian distribution from which noise is drawn.
clip: Whether to clip actions to spec. Default True.
name: The name of this policy.
| __init__ | python | tensorflow/agents | tf_agents/policies/gaussian_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/gaussian_policy.py | Apache-2.0 |
def __init__(self, policy: tf_policy.TFPolicy, name: Optional[Text] = None):
"""Builds a greedy TFPolicy wrapping the given policy.
Args:
policy: A policy implementing the tf_policy.TFPolicy interface.
name: The name of this policy. All variables in this module will fall
under that name. De... | Builds a greedy TFPolicy wrapping the given policy.
Args:
policy: A policy implementing the tf_policy.TFPolicy interface.
name: The name of this policy. All variables in this module will fall
under that name. Defaults to the class name.
| __init__ | python | tensorflow/agents | tf_agents/policies/greedy_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/greedy_policy.py | Apache-2.0 |
def __init__(
self,
wrapped_policy: tf_policy.TFPolicy,
ou_stddev: types.Float = 1.0,
ou_damping: types.Float = 1.0,
clip: bool = True,
name: Optional[Text] = None,
):
"""Builds an OUNoisePolicy wrapping wrapped_policy.
Args:
wrapped_policy: A policy to wrap and add ... | Builds an OUNoisePolicy wrapping wrapped_policy.
Args:
wrapped_policy: A policy to wrap and add OU noise to.
ou_stddev: stddev for the Ornstein-Uhlenbeck noise.
ou_damping: damping factor for the Ornstein-Uhlenbeck noise.
clip: Whether to clip actions to spec. Default True.
name: The... | __init__ | python | tensorflow/agents | tf_agents/policies/ou_noise_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/ou_noise_policy.py | Apache-2.0 |
def __init__(
self,
policy: tf_policy.TFPolicy,
info_spec: types.NestedTensorSpec,
updater_fn: UpdaterFnType,
name: Optional[Text] = None,
):
"""Builds a TFPolicy wrapping the given policy.
PolicyInfoUpdaterWrapper class updates `policy_info` using a user-defined
updater fun... | Builds a TFPolicy wrapping the given policy.
PolicyInfoUpdaterWrapper class updates `policy_info` using a user-defined
updater function. The main use case of this policy wrapper is to annotate
`policy_info` with some auxiliary information. For example, appending
an identifier to specify which model is ... | __init__ | python | tensorflow/agents | tf_agents/policies/policy_info_updater_wrapper.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_info_updater_wrapper.py | Apache-2.0 |
def load(saved_model_path: Text, checkpoint_path: Optional[Text] = None):
"""Loads a policy.
The argument `saved_model_path` is the path of a directory containing a full
saved model for the policy. The path typically looks like
'/root_dir/policies/policy', it may contain trailing numbers for the
train_step.
... | Loads a policy.
The argument `saved_model_path` is the path of a directory containing a full
saved model for the policy. The path typically looks like
'/root_dir/policies/policy', it may contain trailing numbers for the
train_step.
`saved_model_path` is expected to contain the following files. (There can be... | load | python | tensorflow/agents | tf_agents/policies/policy_loader.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_loader.py | Apache-2.0 |
def materialize_saved_model(
saved_model_path: Text, checkpoint_path: Text, output_path: Text
):
"""Materializes a full saved model for a policy.
Some training processes generate a full saved model only at step 0, and then
generate checkpoints for the model variables at different train steps. In this
case ... | Materializes a full saved model for a policy.
Some training processes generate a full saved model only at step 0, and then
generate checkpoints for the model variables at different train steps. In this
case there are no full saved models available for these train steps and you
must pass both the path to initia... | materialize_saved_model | python | tensorflow/agents | tf_agents/policies/policy_loader.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_loader.py | Apache-2.0 |
def _check_spec(spec):
"""Checks for missing or colliding names in specs."""
spec_names = set()
checked = [
_true_if_missing_or_collision(s, spec_names)
for s in tf.nest.flatten(spec)
]
if any(checked):
raise ValueError(
'Specs contain either a missing name or a name collision.\n '
... | Checks for missing or colliding names in specs. | _check_spec | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def _check_compatible(spec, tensor, ignore_outer_dims=True):
"""Checks if `spec` is compatible with `tensor`, maybe ignoring outer dims."""
if ignore_outer_dims:
tensor = tensor_spec.remove_outer_dims_nest(
tensor, tensor.shape.ndims - spec.shape.ndims
)
if not spec.is_compatible_with(tensor):
... | Checks if `spec` is compatible with `tensor`, maybe ignoring outer dims. | _check_compatible | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def __init__(
self,
policy: tf_policy.TFPolicy,
batch_size: Optional[int] = None,
use_nest_path_signatures: bool = True,
seed: Optional[types.Seed] = None,
train_step: Optional[tf.Variable] = None,
input_fn_and_spec: Optional[InputFnAndSpecType] = None,
metadata: Optional... | Initialize PolicySaver for TF policy `policy`.
Args:
policy: A TF Policy.
batch_size: The number of batch entries the policy will process at a time.
This must be either `None` (unknown batch size) or a python integer.
use_nest_path_signatures: SavedModel spec signatures will be created b... | __init__ | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def distribution_fn(time_step, policy_state):
"""Wrapper for policy.distribution() in the SavedModel."""
try:
time_step = cast(ts.TimeStep, time_step)
outs = policy.distribution(
time_step=time_step, policy_state=policy_state
)
return tf.nest.map_structure(_check_... | Wrapper for policy.distribution() in the SavedModel. | distribution_fn | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def get_train_step(self) -> types.Int:
"""Returns the train step of the policy.
Returns:
An integer.
"""
if tf.executing_eagerly():
return self._train_step.numpy()
else:
return tf.identity(self._train_step) | Returns the train step of the policy.
Returns:
An integer.
| get_train_step | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def get_metadata(self) -> Dict[Text, tf.Variable]:
"""Returns the metadata of the policy.
Returns:
An a dictionary of tf.Variable.
"""
if tf.executing_eagerly():
return {k: self._metadata[k].numpy() for k in self._metadata}
else:
return self._metadata | Returns the metadata of the policy.
Returns:
An a dictionary of tf.Variable.
| get_metadata | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def register_function(
self,
name: str,
fn: InputFnType,
input_spec: types.NestedTensorSpec,
outer_dims: Sequence[Optional[int]] = (None,),
) -> None:
"""Registers a function into the saved model.
Note: There is no easy way to generate polymorphic functions. This pattern
can... | Registers a function into the saved model.
Note: There is no easy way to generate polymorphic functions. This pattern
can be followed and the `get_concerete_function` can be called with named
parameters to register more complex signatures. Those functions can then be
passed to the `register_concrete_fu... | register_function | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def register_concrete_function(
self, name: str, fn: def_function.Function, assets: Optional[Any] = None
) -> None:
"""Registers a function into the saved model.
This gives you the flexibility to register any kind of polymorphic function
by creating the concrete function that you wish to register.
... | Registers a function into the saved model.
This gives you the flexibility to register any kind of polymorphic function
by creating the concrete function that you wish to register.
Args:
name: Name of the attribute to use for the saved fn.
fn: Function to register. Must be a callable following ... | register_concrete_function | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def save(
self,
export_dir: Text,
options: Optional[tf.saved_model.SaveOptions] = None,
):
"""Save the policy to the given `export_dir`.
Args:
export_dir: Directory to save the policy to.
options: Optional `tf.saved_model.SaveOptions` object.
"""
tf.compat.v2.saved_model... | Save the policy to the given `export_dir`.
Args:
export_dir: Directory to save the policy to.
options: Optional `tf.saved_model.SaveOptions` object.
| save | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def save_checkpoint(
self,
export_dir: Text,
options: Optional[tf.train.CheckpointOptions] = None,
):
"""Saves the policy as a checkpoint to the given `export_dir`.
This will only work with checkpoints generated in TF2.x.
For the checkpoint to be useful users should first call `save` t... | Saves the policy as a checkpoint to the given `export_dir`.
This will only work with checkpoints generated in TF2.x.
For the checkpoint to be useful users should first call `save` to generate a
saved_model of the policy. Checkpoints can then be used to update the policy
without having to reload the sa... | save_checkpoint | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def _function_with_flat_signature(
function, input_specs, output_spec, include_batch_dimension, batch_size=None
):
"""Create a tf.function with a given signature for export.
Args:
function: A callable that can be wrapped in tf.function.
input_specs: A tuple nested specs declaring ordered arguments to f... | Create a tf.function with a given signature for export.
Args:
function: A callable that can be wrapped in tf.function.
input_specs: A tuple nested specs declaring ordered arguments to function.
output_spec: The nested spec describing the output of the function.
include_batch_dimension: Python bool, w... | _function_with_flat_signature | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def specs_from_collect_data_spec(
loaded_policy_specs: types.NestedTensorSpec,
) -> Dict[types.NestedSpec, types.NestedSpec]:
"""Creates policy specs from specs loaded from disk.
The PolicySaver saves policy specs next to the saved model as
a `struct.StructuredValue` proto. This recreates the
original spec... | Creates policy specs from specs loaded from disk.
The PolicySaver saves policy specs next to the saved model as
a `struct.StructuredValue` proto. This recreates the
original specs from the proto.
Pass the proto loaded from the file with `tensor_spec.from_pbtxt_file()`
to this function.
Args:
loaded_... | specs_from_collect_data_spec | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def _check_composite_distribution(d):
"""Checks that the tfp Distributions is a CompositeTensor."""
if isinstance(d, tfp.distributions.Distribution):
if not hasattr(d, '_type_spec'):
raise TypeError(f'{d} is not a composite tensor.')
return d | Checks that the tfp Distributions is a CompositeTensor. | _check_composite_distribution | python | tensorflow/agents | tf_agents/policies/policy_saver.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/policy_saver.py | Apache-2.0 |
def __init__(
self,
greedy_policy: py_policy.PyPolicy,
epsilon: types.Float,
random_policy: Optional[random_py_policy.RandomPyPolicy] = None,
epsilon_decay_end_count: Optional[types.Float] = None,
epsilon_decay_end_value: Optional[types.Float] = None,
random_seed: Optional[type... | Initializes the epsilon-greedy policy.
Args:
greedy_policy: An instance of py_policy.PyPolicy to use as the greedy
policy.
epsilon: The probability 0.0 <= epsilon <= 1.0 with which an action will
be selected at random.
random_policy: An instance of random_py_policy.RandomPyPolicy ... | __init__ | python | tensorflow/agents | tf_agents/policies/py_epsilon_greedy_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_epsilon_greedy_policy.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedArraySpec,
policy_state_spec: types.NestedArraySpec = (),
info_spec: types.NestedArraySpec = (),
observation_and_action_constraint_splitter: Optional[
types.Splitter
] = None,
):
"""Initia... | Initialization of PyPolicy class.
Args:
time_step_spec: A `TimeStep` ArraySpec of the expected time_steps. Usually
provided by the user to the subclass.
action_spec: A nest of BoundedArraySpec representing the actions. Usually
provided by the user to the subclass.
policy_state_spe... | __init__ | python | tensorflow/agents | tf_agents/policies/py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_policy.py | Apache-2.0 |
def get_initial_state(
self, batch_size: Optional[int] = None
) -> types.NestedArray:
"""Returns an initial state usable by the policy.
Args:
batch_size: An optional batch size.
Returns:
An initial policy state.
"""
return self._get_initial_state(batch_size) | Returns an initial state usable by the policy.
Args:
batch_size: An optional batch size.
Returns:
An initial policy state.
| get_initial_state | python | tensorflow/agents | tf_agents/policies/py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_policy.py | Apache-2.0 |
def action(
self,
time_step: ts.TimeStep,
policy_state: types.NestedArray = (),
seed: Optional[types.Seed] = None,
) -> policy_step.PolicyStep:
"""Generates next action given the time_step and policy_state.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.... | Generates next action given the time_step and policy_state.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: An optional previous policy_state.
seed: Seed to use if action uses sampling (optional).
Returns:
A PolicyStep named tuple containing:
... | action | python | tensorflow/agents | tf_agents/policies/py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_policy.py | Apache-2.0 |
def _action(
self,
time_step: ts.TimeStep,
policy_state: types.NestedArray,
seed: Optional[types.Seed] = None,
) -> policy_step.PolicyStep:
"""Implementation of `action`.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: An Array, or a ... | Implementation of `action`.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: An Array, or a nested dict, list or tuple of Arrays
representing the previous policy_state.
seed: Seed to use if action uses sampling (optional).
Returns:
A `Polic... | _action | python | tensorflow/agents | tf_agents/policies/py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_policy.py | Apache-2.0 |
def _get_initial_state(self, batch_size: int) -> types.NestedArray:
"""Default implementation of `get_initial_state`.
This implementation returns arrays of all zeros matching `batch_size` and
spec `self.policy_state_spec`.
Args:
batch_size: The batch shape.
Returns:
A nested object of... | Default implementation of `get_initial_state`.
This implementation returns arrays of all zeros matching `batch_size` and
spec `self.policy_state_spec`.
Args:
batch_size: The batch shape.
Returns:
A nested object of type `policy_state` containing properly
initialized Arrays.
| _get_initial_state | python | tensorflow/agents | tf_agents/policies/py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_policy.py | Apache-2.0 |
def __init__(
self,
policy: tf_policy.TFPolicy,
time_step_spec: ts.TimeStep,
action_spec: types.NestedArraySpec,
policy_state_spec: types.NestedArraySpec,
info_spec: types.NestedArraySpec,
use_tf_function: bool = False,
batch_time_steps=True,
):
"""Creates a new ins... | Creates a new instance of the policy.
Args:
policy: `tf_policy.TFPolicy` instance to wrap and expose as a py_policy.
time_step_spec: A `TimeStep` ArraySpec of the expected time_steps. Usually
provided by the user to the subclass.
action_spec: A nest of BoundedArraySpec representing the ac... | __init__ | python | tensorflow/agents | tf_agents/policies/py_tf_eager_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_tf_eager_policy.py | Apache-2.0 |
def __init__(
self,
model_path: Text,
time_step_spec: Optional[ts.TimeStep] = None,
action_spec: Optional[types.NestedTensorSpec] = None,
policy_state_spec: types.NestedTensorSpec = (),
info_spec: types.NestedTensorSpec = (),
load_specs_from_pbtxt: bool = False,
use_tf_fu... | Initializes a PyPolicy from a saved_model.
*Note* (b/151318119): BoundedSpecs are converted to regular specs when saved
into a proto as the `nested_structure_coder` from TF currently doesn't
handle BoundedSpecs. Shape and dtypes will still match the original specs.
Args:
model_path: Path to a sa... | __init__ | python | tensorflow/agents | tf_agents/policies/py_tf_eager_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_tf_eager_policy.py | Apache-2.0 |
def update_from_checkpoint(self, checkpoint_path: Text):
"""Allows users to update saved_model variables directly from a checkpoint.
`checkpoint_path` is a path that was passed to either `PolicySaver.save()`
or `PolicySaver.save_checkpoint()`. The policy looks for set of checkpoint
files with the file ... | Allows users to update saved_model variables directly from a checkpoint.
`checkpoint_path` is a path that was passed to either `PolicySaver.save()`
or `PolicySaver.save_checkpoint()`. The policy looks for set of checkpoint
files with the file prefix `<checkpoint_path>/variables/variables'
Args:
... | update_from_checkpoint | python | tensorflow/agents | tf_agents/policies/py_tf_eager_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_tf_eager_policy.py | Apache-2.0 |
def __init__(
self,
policy: tf_policy.TFPolicy,
batch_size: Optional[int] = None,
seed: Optional[types.Seed] = None,
):
"""Initializes a new `PyTFPolicy`.
Args:
policy: A TF Policy implementing `tf_policy.TFPolicy`.
batch_size: (deprecated)
seed: Seed to use if polic... | Initializes a new `PyTFPolicy`.
Args:
policy: A TF Policy implementing `tf_policy.TFPolicy`.
batch_size: (deprecated)
seed: Seed to use if policy performs random actions (optional).
| __init__ | python | tensorflow/agents | tf_agents/policies/py_tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_tf_policy.py | Apache-2.0 |
def _construct(self, batch_size, graph):
"""Construct the agent graph through placeholders."""
self._batch_size = batch_size
self._batched = batch_size is not None
outer_dims = [self._batch_size] if self._batched else [1]
with graph.as_default():
self._time_step = tensor_spec.to_nest_placeho... | Construct the agent graph through placeholders. | _construct | python | tensorflow/agents | tf_agents/policies/py_tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_tf_policy.py | Apache-2.0 |
def restore(
self,
policy_dir: Text,
graph: Optional[tf.Graph] = None,
assert_consumed: bool = True,
):
"""Restores the policy from the checkpoint.
Args:
policy_dir: Directory with the checkpoint.
graph: A graph, inside which policy the is restored (optional).
assert... | Restores the policy from the checkpoint.
Args:
policy_dir: Directory with the checkpoint.
graph: A graph, inside which policy the is restored (optional).
assert_consumed: If true, contents of the checkpoint will be checked for a
match against graph variables.
Returns:
step: Glo... | restore | python | tensorflow/agents | tf_agents/policies/py_tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/py_tf_policy.py | Apache-2.0 |
def convert_nest_lists_to_np_array(
nested_list: types.NestedTensorOrArray,
) -> Union[Tuple[Any], np.ndarray]:
"""Convert nest lists to numpy array.
Args:
nested_list: A nested strucutre of lists.
Raises:
ValueError: If the input is not
collections_abc.Mapping/tuple/list/np.ndarray.
Return... | Convert nest lists to numpy array.
Args:
nested_list: A nested strucutre of lists.
Raises:
ValueError: If the input is not
collections_abc.Mapping/tuple/list/np.ndarray.
Returns:
A nested structure of numpy arrays.
| convert_nest_lists_to_np_array | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy.py | Apache-2.0 |
def _initial_params(
self, batch_size: tf.Tensor
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Returns initial mean and variance tensors.
Broadcasts the initial mean and variance to the requested batch_size.
Args:
batch_size: The requested batch_size.
Returns:
mean: A [B, A] sized tensors ... | Returns initial mean and variance tensors.
Broadcasts the initial mean and variance to the requested batch_size.
Args:
batch_size: The requested batch_size.
Returns:
mean: A [B, A] sized tensors where each row is the initial_mean.
var: A [B, A] sized tensors where each row is the initia... | _initial_params | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy.py | Apache-2.0 |
def actor_func(
self,
observation: types.NestedTensorOrArray,
step_type: Optional[tf.Tensor],
policy_state: Sequence[tf.Tensor],
) -> Tuple[types.NestedTensor, types.NestedTensor, Sequence[tf.Tensor]]:
"""Returns an action to perform using CEM given the q network.
Args:
observat... | Returns an action to perform using CEM given the q network.
Args:
observation: Observation for which we need to find a CEM based action.
step_type: A `StepType` enum value.
policy_state: A Tensor, or a nested dict, list or tuple of Tensors
representing the previous policy_state.
Retu... | actor_func | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy.py | Apache-2.0 |
def body(
mean, var, i, iters, best_actions, best_scores, best_next_policy_state
):
"""Defines the body of the while loop in graph.
Args:
mean: A [B, A] sized tensor, where, a is the size of the action space,
indicating the mean value of the sample distribution var : [B, A]
... | Defines the body of the while loop in graph.
Args:
mean: A [B, A] sized tensor, where, a is the size of the action space,
indicating the mean value of the sample distribution var : [B, A]
sized tensor, where, a is the size of the action space, indicating the
variance value o... | body | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy.py | Apache-2.0 |
def _score(
self, observation, sample_actions, step_type=None, policy_state=()
) -> Tuple[tf.Tensor, Sequence[tf.Tensor]]:
"""Scores the sample actions internally as part of CEM.
Args:
observation: A batch of observation tensors or NamedTuples, whatever the
q_func will handle. CEM is agno... | Scores the sample actions internally as part of CEM.
Args:
observation: A batch of observation tensors or NamedTuples, whatever the
q_func will handle. CEM is agnostic to it.
sample_actions: A [B, N, A] sized tensor, where batch is the batch size, N
is the sample size for the CEM, a is ... | _score | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy.py | Apache-2.0 |
def _score_with_time(
self,
observation: types.NestedTensorOrArray,
sample_actions: types.NestedTensorOrArray,
step_type: Optional[tf.Tensor],
policy_state: Sequence[tf.Tensor],
seq_size: tf.Tensor,
) -> Tuple[tf.Tensor, Sequence[tf.Tensor]]:
"""Scores the sample actions intern... | Scores the sample actions internally as part of CEM.
Args:
observation: A batch of state tensors or NamedTuples, whatever the q_func
will handle. CEM is agnostic to it.
sample_actions: A [BxT, N, A] sized tensor, where batch is the batch size,
N is the sample size for the CEM, a is the ... | _score_with_time | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy.py | Apache-2.0 |
def _distribution(
self, time_step: ts.TimeStep, policy_state: Sequence[tf.Tensor]
) -> policy_step.PolicyStep:
"""Generates the distribution over next actions given the time_step.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested d... | Generates the distribution over next actions given the time_step.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of Tensors
representing the previous policy_state.
Returns:
A `PolicyStep` named tuple co... | _distribution | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy.py | Apache-2.0 |
def __init__(
self,
input_tensor_spec,
sampler_type=None,
anchor_point=0.0,
dist=DIST_BIMODAL,
categorical_action_returns=None,
):
"""Defines a DummyNet class as a simple continuous dist function.
It has a clear maximum at the specified anchor_point. By default, all
ac... | Defines a DummyNet class as a simple continuous dist function.
It has a clear maximum at the specified anchor_point. By default, all
action dimensions for all batches must be near the anchor point.
Args:
input_tensor_spec: Input Tensor Spec.
sampler_type: One of 'continuous', 'continuous_and_o... | __init__ | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy_test.py | Apache-2.0 |
def test_actor_func(
self,
sampler_type=None,
anchor_point=0.0,
dist=DIST_BIMODAL,
categorical_action_returns=None,
num_iters=5,
): # pylint: disable=g-doc-args
"""Helper function to run the tests.
Creates the right q_func and tests for correctness. See the _create_q_func... | Helper function to run the tests.
Creates the right q_func and tests for correctness. See the _create_q_func
documentation to understand the various arguments.
| test_actor_func | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy_test.py | Apache-2.0 |
def _score_with_map_fn(self, observation, sample_actions, q_network):
"""Scores the sample actions using map_fn as part of CEM while loop.
Args:
observation: A batch of observation tensors or NamedTuples, whatever the
q_func will handle. CEM is agnostic to it.
sample_actions: A [N, B, A] si... | Scores the sample actions using map_fn as part of CEM while loop.
Args:
observation: A batch of observation tensors or NamedTuples, whatever the
q_func will handle. CEM is agnostic to it.
sample_actions: A [N, B, A] sized tensor, where batch is the batch size, N
is the sample size for t... | _score_with_map_fn | python | tensorflow/agents | tf_agents/policies/qtopt_cem_policy_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/qtopt_cem_policy_test.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedArraySpec,
policy_state_spec: types.NestedArraySpec = (),
info_spec: types.NestedArraySpec = (),
seed: Optional[types.Seed] = None,
outer_dims: Optional[Sequence[int]] = None,
observation_and_action... | Initializes the RandomPyPolicy.
Args:
time_step_spec: Reference `time_step_spec`. If not None and outer_dims is
not provided this is used to infer the outer_dims required for the given
time_step when action is called.
action_spec: A nest of BoundedArraySpec representing the actions to s... | __init__ | python | tensorflow/agents | tf_agents/policies/random_py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/random_py_policy.py | Apache-2.0 |
def _calculate_log_probability(outer_dims, action_spec):
"""Helper function for calculating log prob of a uniform distribution.
Each item in the returned tensor will be equal to:
|action_spec.shape| * log_prob_of_each_component_of_action_spec.
Note that this method expects the same value for all outer_dims be... | Helper function for calculating log prob of a uniform distribution.
Each item in the returned tensor will be equal to:
|action_spec.shape| * log_prob_of_each_component_of_action_spec.
Note that this method expects the same value for all outer_dims because
we're sampling uniformly from the same distribution fo... | _calculate_log_probability | python | tensorflow/agents | tf_agents/policies/random_tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/random_tf_policy.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedArraySpec,
action_script: Sequence[Tuple[int, types.NestedArray]],
):
"""Instantiates the scripted policy.
The Action script can be configured through gin. e.g:
ScriptedPyPolicy.action_script = [
(... | Instantiates the scripted policy.
The Action script can be configured through gin. e.g:
ScriptedPyPolicy.action_script = [
(1, { "action1": [[5, 2], [1, 3]],
"action2": [[4, 6]]},),
(0, { "action1": [[8, 1], [9, 2]],
"action2": [[1, 2]]},),
(2, { "acti... | __init__ | python | tensorflow/agents | tf_agents/policies/scripted_py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/scripted_py_policy.py | Apache-2.0 |
def __init__(
self,
policy: tf_policy.TFPolicy,
smoothing_coefficient: float,
name: Optional[Text] = None,
):
"""Adds TemporalActionSmoothing to the given policy.
smoothed_action = previous_action * smoothing_coefficient +
action * (1.0 - smoothing_coefficient))
... | Adds TemporalActionSmoothing to the given policy.
smoothed_action = previous_action * smoothing_coefficient +
action * (1.0 - smoothing_coefficient))
Args:
policy: A policy implementing the tf_policy.TFPolicy interface.
smoothing_coefficient: Coefficient used for smoothing ac... | __init__ | python | tensorflow/agents | tf_agents/policies/temporal_action_smoothing.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/temporal_action_smoothing.py | Apache-2.0 |
def _get_initial_state(self, batch_size):
"""Creates zero state tuple with wrapped initial state and smoothing vars.
Args:
batch_size: The batch shape.
Returns:
A tuple of (wrapped_policy_initial_state, initial_smoothing_state)
"""
wrapped_initial_state = self._wrapped_policy.get_initi... | Creates zero state tuple with wrapped initial state and smoothing vars.
Args:
batch_size: The batch shape.
Returns:
A tuple of (wrapped_policy_initial_state, initial_smoothing_state)
| _get_initial_state | python | tensorflow/agents | tf_agents/policies/temporal_action_smoothing.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/temporal_action_smoothing.py | Apache-2.0 |
def variables(self) -> Sequence[tf.Variable]:
"""Returns the list of Variables that belong to the policy."""
# Ignore self._variables() in favor of using tf.Module's tracking.
return super(TFPolicy, self).variables | Returns the list of Variables that belong to the policy. | variables | python | tensorflow/agents | tf_agents/policies/tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_policy.py | Apache-2.0 |
def get_initial_state(
self, batch_size: Optional[types.Int]
) -> types.NestedTensor:
"""Returns an initial state usable by the policy.
Args:
batch_size: Tensor or constant: size of the batch dimension. Can be None
in which case no dimensions gets added.
Returns:
A nested objec... | Returns an initial state usable by the policy.
Args:
batch_size: Tensor or constant: size of the batch dimension. Can be None
in which case no dimensions gets added.
Returns:
A nested object of type `policy_state` containing properly
initialized Tensors.
| get_initial_state | python | tensorflow/agents | tf_agents/policies/tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_policy.py | Apache-2.0 |
def action(
self,
time_step: ts.TimeStep,
policy_state: types.NestedTensor = (),
seed: Optional[types.Seed] = None,
) -> policy_step.PolicyStep:
"""Generates next action given the time_step and policy_state.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`... | Generates next action given the time_step and policy_state.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of Tensors
representing the previous policy_state.
seed: Seed to use if action performs sampling (op... | action | python | tensorflow/agents | tf_agents/policies/tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_policy.py | Apache-2.0 |
def distribution(
self, time_step: ts.TimeStep, policy_state: types.NestedTensor = ()
) -> policy_step.PolicyStep:
"""Generates the distribution over next actions given the time_step.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a neste... | Generates the distribution over next actions given the time_step.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of Tensors
representing the previous policy_state.
Returns:
A `PolicyStep` named tuple co... | distribution | python | tensorflow/agents | tf_agents/policies/tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_policy.py | Apache-2.0 |
def update(
self,
policy,
tau: float = 1.0,
tau_non_trainable: Optional[float] = None,
sort_variables_by_name: bool = False,
) -> tf.Operation:
"""Update the current policy with another policy.
This would include copying the variables from the other policy.
Args:
poli... | Update the current policy with another policy.
This would include copying the variables from the other policy.
Args:
policy: Another policy it can update from.
tau: A float scalar in [0, 1]. When tau is 1.0 (the default), we do a hard
update. This is used for trainable variables.
tau... | update | python | tensorflow/agents | tf_agents/policies/tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_policy.py | Apache-2.0 |
def _action(
self,
time_step: ts.TimeStep,
policy_state: types.NestedTensor,
seed: Optional[types.Seed] = None,
) -> policy_step.PolicyStep:
"""Implementation of `action`.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a... | Implementation of `action`.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of Tensors
representing the previous policy_state.
seed: Seed to use if action performs sampling (optional).
Returns:
A `... | _action | python | tensorflow/agents | tf_agents/policies/tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_policy.py | Apache-2.0 |
def _distribution(
self, time_step: ts.TimeStep, policy_state: types.NestedTensorSpec
) -> policy_step.PolicyStep:
"""Implementation of `distribution`.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of Tensors... | Implementation of `distribution`.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of Tensors
representing the previous policy_state.
Returns:
A `PolicyStep` named tuple containing:
`action`: A (o... | _distribution | python | tensorflow/agents | tf_agents/policies/tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_policy.py | Apache-2.0 |
def _get_initial_state(self, batch_size: int) -> types.NestedTensor:
"""Returns the initial state of the policy network.
Args:
batch_size: A constant or Tensor holding the batch size. Can be None, in
which case the state will not have a batch dimension added.
Returns:
A nest of zero te... | Returns the initial state of the policy network.
Args:
batch_size: A constant or Tensor holding the batch size. Can be None, in
which case the state will not have a batch dimension added.
Returns:
A nest of zero tensors matching the spec of the policy network state.
| _get_initial_state | python | tensorflow/agents | tf_agents/policies/tf_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_policy.py | Apache-2.0 |
def __init__(self, init_var_value, var_scope, name=None):
"""Initializes policy containing variables with specified value.
Args:
init_var_value: A scalar specifies the initial value of all variables.
var_scope: A String defines variable scope.
name: The name of this policy. All variables in t... | Initializes policy containing variables with specified value.
Args:
init_var_value: A scalar specifies the initial value of all variables.
var_scope: A String defines variable scope.
name: The name of this policy. All variables in this module will fall
under that name. Defaults to the cla... | __init__ | python | tensorflow/agents | tf_agents/policies/tf_policy_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_policy_test.py | Apache-2.0 |
def __init__(
self,
policy: py_policy.PyPolicy,
py_policy_is_batched: bool = False,
name: Optional[Text] = None,
):
"""Initializes a new `TFPyPolicy` instance with an Pyton policy .
Args:
policy: Python policy implementing `py_policy.PyPolicy`.
py_policy_is_batched: If Fal... | Initializes a new `TFPyPolicy` instance with an Pyton policy .
Args:
policy: Python policy implementing `py_policy.PyPolicy`.
py_policy_is_batched: If False, time_steps will be unbatched before
passing to py_policy.action(), and a batch dimension will be added to
the returned action. Th... | __init__ | python | tensorflow/agents | tf_agents/policies/tf_py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_py_policy.py | Apache-2.0 |
def _get_initial_state(self, batch_size):
"""Invokes python policy reset through numpy_function.
Args:
batch_size: Batch size for the get_initial_state tensor(s).
Returns:
A tuple of (policy_state, reset_op).
policy_state: Tensor, or a nested dict, list or tuple of Tensors,
repres... | Invokes python policy reset through numpy_function.
Args:
batch_size: Batch size for the get_initial_state tensor(s).
Returns:
A tuple of (policy_state, reset_op).
policy_state: Tensor, or a nested dict, list or tuple of Tensors,
representing the new policy state.
reset_op: a li... | _get_initial_state | python | tensorflow/agents | tf_agents/policies/tf_py_policy.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/tf_py_policy.py | Apache-2.0 |
def get_num_actions_from_tensor_spec(
action_spec: types.BoundedTensorSpec,
) -> int:
"""Validates `action_spec` and returns number of actions.
`action_spec` must specify a scalar int32 or int64 with minimum zero.
Args:
action_spec: a `BoundedTensorSpec`.
Returns:
The number of actions described ... | Validates `action_spec` and returns number of actions.
`action_spec` must specify a scalar int32 or int64 with minimum zero.
Args:
action_spec: a `BoundedTensorSpec`.
Returns:
The number of actions described by `action_spec`.
Raises:
ValueError: if `action_spec` is not an bounded scalar int32 or... | get_num_actions_from_tensor_spec | python | tensorflow/agents | tf_agents/policies/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/utils.py | Apache-2.0 |
def create_bandit_policy_type_tensor_spec(
shape: types.Shape,
) -> types.BoundedTensorSpec:
"""Create tensor spec for bandit policy type."""
return tensor_spec.BoundedTensorSpec(
shape=shape,
dtype=tf.int32,
minimum=BanditPolicyType.UNKNOWN,
maximum=BanditPolicyType.FALCON,
) | Create tensor spec for bandit policy type. | create_bandit_policy_type_tensor_spec | python | tensorflow/agents | tf_agents/policies/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/utils.py | Apache-2.0 |
def masked_argmax(
input_tensor: types.Tensor,
mask: types.Tensor,
output_type: tf.DType = tf.int32,
) -> types.Tensor:
"""Computes the argmax where the allowed elements are given by a mask.
If a row of `mask` contains all zeros, then this method will return -1 for the
corresponding row of `input_ten... | Computes the argmax where the allowed elements are given by a mask.
If a row of `mask` contains all zeros, then this method will return -1 for the
corresponding row of `input_tensor`.
Args:
input_tensor: Rank-2 Tensor of floats.
mask: 0-1 valued Tensor of the same shape as input.
output_type: Intege... | masked_argmax | python | tensorflow/agents | tf_agents/policies/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/utils.py | Apache-2.0 |
def has_bandit_policy_type(
info: Optional[Union[PolicyInfo, PerArmPolicyInfo]],
check_for_tensor: bool = False,
) -> bool:
"""Check if policy info has `bandit_policy_type` field/tensor."""
if not info:
return False
fields = getattr(info, '_fields', None)
has_field = fields is not None and InfoField... | Check if policy info has `bandit_policy_type` field/tensor. | has_bandit_policy_type | python | tensorflow/agents | tf_agents/policies/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/utils.py | Apache-2.0 |
def has_chosen_arm_features(
info: Optional[Union[PolicyInfo, PerArmPolicyInfo]],
check_for_tensor: bool = False,
) -> bool:
"""Check if policy info has `chosen_arm_features` field/tensor."""
if not info:
return False
fields = getattr(info, '_fields', None)
has_field = fields is not None and InfoFie... | Check if policy info has `chosen_arm_features` field/tensor. | has_chosen_arm_features | python | tensorflow/agents | tf_agents/policies/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/utils.py | Apache-2.0 |
def set_bandit_policy_type(
info: Optional[Union[PolicyInfo, PerArmPolicyInfo]],
bandit_policy_type: types.Tensor,
) -> Union[PolicyInfo, PerArmPolicyInfo]:
"""Sets the InfoFields.BANDIT_POLICY_TYPE on info to bandit_policy_type.
If policy `info` does not support InfoFields.BANDIT_POLICY_TYPE, this method
... | Sets the InfoFields.BANDIT_POLICY_TYPE on info to bandit_policy_type.
If policy `info` does not support InfoFields.BANDIT_POLICY_TYPE, this method
returns `info` as-is (without any modification).
Args:
info: Policy info on which to set bandit policy type.
bandit_policy_type: Tensor containing BanditPoli... | set_bandit_policy_type | python | tensorflow/agents | tf_agents/policies/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/utils.py | Apache-2.0 |
def bandit_policy_uniform_mask(
values: types.Tensor, mask: types.Tensor
) -> types.Tensor:
"""Set bandit policy type tensor to BanditPolicyType.UNIFORM based on mask.
Set bandit policy type `values` to BanditPolicyType.UNIFORM; returns tensor
where output[i] is BanditPolicyType.UNIFORM if mask[i] is True, o... | Set bandit policy type tensor to BanditPolicyType.UNIFORM based on mask.
Set bandit policy type `values` to BanditPolicyType.UNIFORM; returns tensor
where output[i] is BanditPolicyType.UNIFORM if mask[i] is True, otherwise it
is left as values[i].
Args:
values: Tensor containing `BanditPolicyType` enumera... | bandit_policy_uniform_mask | python | tensorflow/agents | tf_agents/policies/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/utils.py | Apache-2.0 |
def create_chosen_arm_features_info_spec(
observation_spec: types.NestedTensorSpec,
) -> types.NestedTensorSpec:
"""Creates the chosen arm features info spec from the arm observation spec."""
arm_spec = observation_spec[bandit_spec_utils.PER_ARM_FEATURE_KEY]
return tensor_spec.remove_outer_dims_nest(arm_spec,... | Creates the chosen arm features info spec from the arm observation spec. | create_chosen_arm_features_info_spec | python | tensorflow/agents | tf_agents/policies/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/utils.py | Apache-2.0 |
def __init__(self, action_spec, sample_clippers=None, sample_rejecters=None):
"""Creates an ActionsSampler.
Args:
action_spec: A nest of BoundedTensorSpec representing the actions.
sample_clippers: A list of callables that are applied to the generated
samples. These callables take in a nest... | Creates an ActionsSampler.
Args:
action_spec: A nest of BoundedTensorSpec representing the actions.
sample_clippers: A list of callables that are applied to the generated
samples. These callables take in a nested structure matching the
action_spec and must return a matching structure.
... | __init__ | python | tensorflow/agents | tf_agents/policies/samplers/qtopt_cem_actions_sampler.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/samplers/qtopt_cem_actions_sampler.py | Apache-2.0 |
def refit_distribution_to(self, target_sample_indices, samples):
"""Refits distribution according to actions with index of ind.
Args:
target_sample_indices: A [B, M] sized tensor indicating the index
samples: A nested structure corresponding to action_spec. Each action is a
[B, N, A] sized ... | Refits distribution according to actions with index of ind.
Args:
target_sample_indices: A [B, M] sized tensor indicating the index
samples: A nested structure corresponding to action_spec. Each action is a
[B, N, A] sized tensor.
Returns:
mean: A nested structure containing [B, A] s... | refit_distribution_to | python | tensorflow/agents | tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous.py | Apache-2.0 |
def sample_batch_and_clip(self, num_samples, mean, var, state=None):
"""Samples and clips a batch of actions [B, N, A] with mean and var.
Args:
num_samples: Number of actions to sample each round.
mean: A nested structure containing [B, A] shaped tensor representing the
mean of the actions ... | Samples and clips a batch of actions [B, N, A] with mean and var.
Args:
num_samples: Number of actions to sample each round.
mean: A nested structure containing [B, A] shaped tensor representing the
mean of the actions to be sampled.
var: A nested structure containing [B, A] shaped tensor... | sample_batch_and_clip | python | tensorflow/agents | tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous.py | Apache-2.0 |
def __init__(
self,
action_spec,
sample_clippers=None,
sub_actions_fields=None,
sample_rejecters=None,
max_rejection_iterations=10,
):
"""Builds a GaussianActionsSampler.
Args:
action_spec: A dict of BoundedTensorSpec representing the actions.
sample_clippers: ... | Builds a GaussianActionsSampler.
Args:
action_spec: A dict of BoundedTensorSpec representing the actions.
sample_clippers: A list of list of sample clipper functions. The function
takes a dict of Tensors of actions and a dict of Tensors of the state,
output a dict of Tensors of clipped ... | __init__ | python | tensorflow/agents | tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous_and_one_hot.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous_and_one_hot.py | Apache-2.0 |
def refit_distribution_to(self, target_sample_indices, samples):
"""Refits distribution according to actions with index of ind.
Args:
target_sample_indices: A [B, M] sized tensor indicating the index
samples: A dict corresponding to action_spec. Each action is a [B, N, A]
sized tensor.
... | Refits distribution according to actions with index of ind.
Args:
target_sample_indices: A [B, M] sized tensor indicating the index
samples: A dict corresponding to action_spec. Each action is a [B, N, A]
sized tensor.
Returns:
mean: A dict containing [B, A] sized tensors where each ... | refit_distribution_to | python | tensorflow/agents | tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous_and_one_hot.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous_and_one_hot.py | Apache-2.0 |
def sample_batch_and_clip(self, num_samples, mean, var, state=None):
"""Samples and clips a batch of actions [B, N, A] with mean and var.
Args:
num_samples: Number of actions to sample each round.
mean: A dict containing [B, A] shaped tensor representing the mean of the
actions to be sample... | Samples and clips a batch of actions [B, N, A] with mean and var.
Args:
num_samples: Number of actions to sample each round.
mean: A dict containing [B, A] shaped tensor representing the mean of the
actions to be sampled.
var: A dict containing [B, A] shaped tensor representing the varian... | sample_batch_and_clip | python | tensorflow/agents | tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous_and_one_hot.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/samplers/qtopt_cem_actions_sampler_continuous_and_one_hot.py | Apache-2.0 |
def refit_distribution_to(self, target_sample_indices, samples):
"""Refits distribution according to actions with index of ind.
Args:
target_sample_indices: A [B, M] sized tensor indicating the index
samples: A nested structure corresponding to action_spec. Each action is a
[B, N, A] sized ... | Refits distribution according to actions with index of ind.
Args:
target_sample_indices: A [B, M] sized tensor indicating the index
samples: A nested structure corresponding to action_spec. Each action is a
[B, N, A] sized tensor.
Returns:
mean: A nested structure containing [B, A] s... | refit_distribution_to | python | tensorflow/agents | tf_agents/policies/samplers/qtopt_cem_actions_sampler_hybrid.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/samplers/qtopt_cem_actions_sampler_hybrid.py | Apache-2.0 |
def sample_batch_and_clip(self, num_samples, mean, var, state=None):
"""Samples and clips a batch of actions [B, N, A] with mean and var.
Args:
num_samples: Number of actions to sample each round.
mean: A nested structure containing [B, A] shaped tensor representing the
mean of the actions ... | Samples and clips a batch of actions [B, N, A] with mean and var.
Args:
num_samples: Number of actions to sample each round.
mean: A nested structure containing [B, A] shaped tensor representing the
mean of the actions to be sampled.
var: A nested structure containing [B, A] shaped tensor... | sample_batch_and_clip | python | tensorflow/agents | tf_agents/policies/samplers/qtopt_cem_actions_sampler_hybrid.py | https://github.com/tensorflow/agents/blob/master/tf_agents/policies/samplers/qtopt_cem_actions_sampler_hybrid.py | Apache-2.0 |
def __init__(
self,
data_spec,
capacity=1000,
completed_only=False,
buffer_size=8,
name_prefix='EpisodicReplayBuffer',
device='cpu:*',
seed=None,
begin_episode_fn=None,
end_episode_fn=None,
dataset_drop_remainder=False,
dataset_window_shift=None,
... | Creates an EpisodicReplayBuffer.
This class receives a dataspec and capacity and creates a replay buffer
supporting read/write operations, organized into episodes.
This uses an underlying EpisodicTable with capacity equal to
capacity. Each row in the table can have an episode of unbounded
length.
... | __init__ | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def create_episode_ids(self, num_episodes=None):
"""Returns a new tensor containing initial invalid episode ID(s).
This tensor is meant to be passed to methods like `add_batch` and
`extend_episodes`; those methods will return an updated set of episode id
values in their output. To keep track of update... | Returns a new tensor containing initial invalid episode ID(s).
This tensor is meant to be passed to methods like `add_batch` and
`extend_episodes`; those methods will return an updated set of episode id
values in their output. To keep track of updated episode IDs across
multiple TF1 session run calls,... | create_episode_ids | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def add_sequence(self, items, episode_id):
"""Adds a sequence of items to the replay buffer for the selected episode.
Args:
items: A sequence of items to be added to the buffer. Items will have the
same structure as the data_spec of this class, but the tensors in items
will have an outer ... | Adds a sequence of items to the replay buffer for the selected episode.
Args:
items: A sequence of items to be added to the buffer. Items will have the
same structure as the data_spec of this class, but the tensors in items
will have an outer sequence dimension in addition to the correspondin... | add_sequence | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _add_steps():
"""Add sequence of items to the buffer."""
inc_episode_length = self._increment_episode_length_locked(
episode_location, num_steps
)
write_data_op = self._data_table.append(episode_location, items)
with tf.control_dependencies([inc_episod... | Add sequence of items to the buffer. | _add_steps | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def add_batch(self, items, episode_ids):
"""Adds a batch of single steps for the corresponding episodes IDs.
Args:
items: A batch of items to be added to the buffer. Items will have the
same structure as the data_spec of this class, but the tensors in items
will have an extra outer dimens... | Adds a batch of single steps for the corresponding episodes IDs.
Args:
items: A batch of items to be added to the buffer. Items will have the
same structure as the data_spec of this class, but the tensors in items
will have an extra outer dimension `(num_episodes, ...)` in addition to
... | add_batch | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _get_next(
self, sample_batch_size=None, num_steps=None, time_stacked=None
):
"""Returns an episode sampled uniformly from the buffer.
Args:
sample_batch_size: Not used
num_steps: Not used
time_stacked: Not used
Returns:
A 2-tuple containing:
- An episode sampl... | Returns an episode sampled uniformly from the buffer.
Args:
sample_batch_size: Not used
num_steps: Not used
time_stacked: Not used
Returns:
A 2-tuple containing:
- An episode sampled uniformly from the buffer.
- BufferInfo NamedTuple, containing the episode id.
| _get_next | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _as_dataset(
self,
sample_batch_size=None,
num_steps=None,
sequence_preprocess_fn=None,
num_parallel_calls=tf.data.experimental.AUTOTUNE,
):
"""Creates a dataset that returns episodes entries from the buffer.
The dataset behaves differently depending on if `num_steps` is pro... | Creates a dataset that returns episodes entries from the buffer.
The dataset behaves differently depending on if `num_steps` is provided or
not. If `num_steps = None`, then entire episodes are sampled uniformly at
random from the buffer. If `num_steps != None`, then we attempt to sample
uniformly acr... | _as_dataset | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _get_episode_locations(_):
"""Sample episode ids according to value of num_steps."""
if num_steps is None:
# Just want to get a uniform sampling of episodes.
episode_ids = self._sample_episode_ids(
shape=[episode_id_buffer_size], seed=self._seed
)
else:
... | Sample episode ids according to value of num_steps. | _get_episode_locations | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _read_tensor_list_and_id(row):
"""Read the TensorLists out of the table row, get id and num_frames."""
# Return a flattened tensor list
flat_tensor_lists = tuple(
tf.nest.flatten(self._data_table.get_episode_lists(row))
)
# Due to race conditions, not all entries ... | Read the TensorLists out of the table row, get id and num_frames. | _read_tensor_list_and_id | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _random_slice(flat_tensor_lists, id_, num_frames):
"""Take a random slice from the episode, of length num_steps."""
# Sample uniformly between [0, num_frames - num_steps]
start_slice = tf.random.uniform(
(),
minval=0,
maxval=num_frames - num_steps + 1,
... | Take a random slice from the episode, of length num_steps. | _random_slice | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _single_deterministic_pass_dataset(
self,
sample_batch_size=None,
num_steps=None,
sequence_preprocess_fn=None,
num_parallel_calls=tf.data.experimental.AUTOTUNE,
):
"""Creates a dataset that returns entries from the buffer in fixed order.
Args:
sample_batch_size: (Optio... | Creates a dataset that returns entries from the buffer in fixed order.
Args:
sample_batch_size: (Optional.) An optional batch_size to specify the
number of items to return. See as_dataset() documentation. **NOTE** This
argument may only be provided when `num_steps is not None`. Otherwise
... | _single_deterministic_pass_dataset | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _gather_all(self):
"""Returns all the items currently in the buffer.
Returns:
A tuple containing two entries:
- All the items currently in the buffer (nested).
- The items ids.
Raises:
ValueError: If the data spec contains lists that must be converted to
tuples.
... | Returns all the items currently in the buffer.
Returns:
A tuple containing two entries:
- All the items currently in the buffer (nested).
- The items ids.
Raises:
ValueError: If the data spec contains lists that must be converted to
tuples.
| _gather_all | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
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 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.