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 _loss(
self,
experience: types.NestedTensor,
weights: Optional[types.Tensor] = None,
training: bool = False,
):
"""Returns the loss of the provided experience.
This method is only used at test time!
Args:
experience: A time-stacked trajectory object.
weights: Opti... | Returns the loss of the provided experience.
This method is only used at test time!
Args:
experience: A time-stacked trajectory object.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights.
training: Whether this loss is being calculated as part of training.
... | _loss | python | tensorflow/agents | tf_agents/agents/sac/sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py | Apache-2.0 |
def _get_target_updater(self, tau=1.0, period=1):
"""Performs a soft update of the target network parameters.
For each weight w_s in the original network, and its corresponding
weight w_t in the target network, a soft update is:
w_t = (1- tau) x w_t + tau x ws
Args:
tau: A float scalar in [0... | Performs a soft update of the target network parameters.
For each weight w_s in the original network, and its corresponding
weight w_t in the target network, a soft update is:
w_t = (1- tau) x w_t + tau x ws
Args:
tau: A float scalar in [0, 1]. Default `tau=1.0` means hard update.
period: ... | _get_target_updater | python | tensorflow/agents | tf_agents/agents/sac/sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py | Apache-2.0 |
def _actions_and_log_probs(self, time_steps, training=False):
"""Get actions and corresponding log probabilities from policy."""
# Get raw action distribution from policy, and initialize bijectors list.
batch_size = nest_utils.get_outer_shape(time_steps, self._time_step_spec)[0]
policy_state = self._tra... | Get actions and corresponding log probabilities from policy. | _actions_and_log_probs | python | tensorflow/agents | tf_agents/agents/sac/sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py | Apache-2.0 |
def critic_loss(
self,
time_steps: ts.TimeStep,
actions: types.Tensor,
next_time_steps: ts.TimeStep,
td_errors_loss_fn: types.LossFn,
gamma: types.Float = 1.0,
reward_scale_factor: types.Float = 1.0,
weights: Optional[types.Tensor] = None,
training: bool = False,
... | Computes the critic loss for SAC training.
Args:
time_steps: A batch of timesteps.
actions: A batch of actions.
next_time_steps: A batch of next timesteps.
td_errors_loss_fn: A function(td_targets, predictions) to compute
elementwise (per-batch-entry) loss.
gamma: Discount for... | critic_loss | python | tensorflow/agents | tf_agents/agents/sac/sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py | Apache-2.0 |
def actor_loss(
self,
time_steps: ts.TimeStep,
weights: Optional[types.Tensor] = None,
training: Optional[bool] = True,
) -> types.Tensor:
"""Computes the actor_loss for SAC training.
Args:
time_steps: A batch of timesteps.
weights: Optional scalar or elementwise (per-batc... | Computes the actor_loss for SAC training.
Args:
time_steps: A batch of timesteps.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights.
training: Whether training should be applied.
Returns:
actor_loss: A scalar actor loss.
| actor_loss | python | tensorflow/agents | tf_agents/agents/sac/sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py | Apache-2.0 |
def alpha_loss(
self,
time_steps: ts.TimeStep,
weights: Optional[types.Tensor] = None,
training: bool = False,
) -> types.Tensor:
"""Computes the alpha_loss for EC-SAC training.
Args:
time_steps: A batch of timesteps.
weights: Optional scalar or elementwise (per-batch-entr... | Computes the alpha_loss for EC-SAC training.
Args:
time_steps: A batch of timesteps.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights.
training: Whether this loss is being used during training.
Returns:
alpha_loss: A scalar alpha loss.
| alpha_loss | python | tensorflow/agents | tf_agents/agents/sac/sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py | Apache-2.0 |
def __init__(
self,
sample_spec: types.TensorSpec,
activation_fn: Optional[Callable[[types.Tensor], types.Tensor]] = None,
std_transform: Optional[Callable[[types.Tensor], types.Tensor]] = tf.exp,
name: Text = 'TanhNormalProjectionNetwork',
):
"""Creates an instance of TanhNormalProj... | Creates an instance of TanhNormalProjectionNetwork.
Args:
sample_spec: A `tensor_spec.BoundedTensorSpec` detailing the shape and
dtypes of samples pulled from the output distribution.
activation_fn: Activation function to use in dense layer.
std_transform: Transformation function to apply... | __init__ | python | tensorflow/agents | tf_agents/agents/sac/tanh_normal_projection_network.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/tanh_normal_projection_network.py | Apache-2.0 |
def train_eval(
root_dir,
env_name='HalfCheetah-v2',
eval_env_name=None,
env_load_fn=suite_mujoco.load,
# The SAC paper reported:
# Hopper and Cartpole results up to 1000000 iters,
# Humanoid results up to 10000000 iters,
# Other mujoco tasks up to 3000000 iters.
num_iterations=30000... | A simple train and eval for SAC. | train_eval | python | tensorflow/agents | tf_agents/agents/sac/examples/v2/train_eval.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/examples/v2/train_eval.py | Apache-2.0 |
def train_eval(
root_dir,
env_name='cartpole',
task_name='balance',
observations_allowlist='position',
eval_env_name=None,
num_iterations=1000000,
# Params for networks.
actor_fc_layers=(400, 300),
actor_output_fc_layers=(100,),
actor_lstm_size=(40,),
critic_obs_fc_layers=Non... | A simple train and eval for RNN SAC on DM control. | train_eval | python | tensorflow/agents | tf_agents/agents/sac/examples/v2/train_eval_rnn.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/examples/v2/train_eval_rnn.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedTensor,
actor_network: network.Network,
critic_network: network.Network,
actor_optimizer: types.Optimizer,
critic_optimizer: types.Optimizer,
exploration_noise_std: types.Float = 0.1,
critic_n... | Creates a Td3Agent Agent.
Args:
time_step_spec: A `TimeStep` spec of the expected time_steps.
action_spec: A nest of BoundedTensorSpec representing the actions.
actor_network: A tf_agents.network.Network to be used by the agent. The
network will be called with call(observation, step_type)... | __init__ | python | tensorflow/agents | tf_agents/agents/td3/td3_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py | Apache-2.0 |
def _initialize(self):
"""Initialize the agent.
Copies weights from the actor and critic networks to the respective
target actor and critic networks.
"""
common.soft_variables_update(
self._critic_network_1.variables,
self._target_critic_network_1.variables,
tau=1.0,
)
... | Initialize the agent.
Copies weights from the actor and critic networks to the respective
target actor and critic networks.
| _initialize | python | tensorflow/agents | tf_agents/agents/td3/td3_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py | Apache-2.0 |
def _get_target_updater(self, tau=1.0, period=1):
"""Performs a soft update of the target network parameters.
For each weight w_s in the original network, and its corresponding
weight w_t in the target network, a soft update is:
w_t = (1- tau) x w_t + tau x ws
Args:
tau: A float scalar in [0... | Performs a soft update of the target network parameters.
For each weight w_s in the original network, and its corresponding
weight w_t in the target network, a soft update is:
w_t = (1- tau) x w_t + tau x ws
Args:
tau: A float scalar in [0, 1]. Default `tau=1.0` means hard update.
period: ... | _get_target_updater | python | tensorflow/agents | tf_agents/agents/td3/td3_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py | Apache-2.0 |
def critic_loss(
self,
time_steps: ts.TimeStep,
actions: types.Tensor,
next_time_steps: ts.TimeStep,
weights: Optional[types.Tensor] = None,
training: bool = False,
) -> types.Tensor:
"""Computes the critic loss for TD3 training.
Args:
time_steps: A batch of timestep... | Computes the critic loss for TD3 training.
Args:
time_steps: A batch of timesteps.
actions: A batch of actions.
next_time_steps: A batch of next timesteps.
weights: Optional scalar or element-wise (per-batch-entry) importance
weights.
training: Whether this loss is being used ... | critic_loss | python | tensorflow/agents | tf_agents/agents/td3/td3_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py | Apache-2.0 |
def actor_loss(
self,
time_steps: ts.TimeStep,
weights: Optional[types.Tensor] = None,
training: bool = False,
) -> types.Tensor:
"""Computes the actor_loss for TD3 training.
Args:
time_steps: A batch of timesteps.
weights: Optional scalar or element-wise (per-batch-entry)... | Computes the actor_loss for TD3 training.
Args:
time_steps: A batch of timesteps.
weights: Optional scalar or element-wise (per-batch-entry) importance
weights.
training: Whether this loss is being used for training.
Returns:
actor_loss: A scalar actor loss.
| actor_loss | python | tensorflow/agents | tf_agents/agents/td3/td3_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py | Apache-2.0 |
def __init__(
self,
num_actions: int,
dtype: tf.DType = tf.float32,
name: Optional[Text] = None,
):
"""Initializes an instance of `BernoulliBanditVariableCollection`.
It creates all the variables needed for `BernoulliThompsonSamplingAgent`.
For each action, the agent maintains the... | Initializes an instance of `BernoulliBanditVariableCollection`.
It creates all the variables needed for `BernoulliThompsonSamplingAgent`.
For each action, the agent maintains the `alpha` and `beta` parameters of
the beta distribution.
Args:
num_actions: (int) The number of actions.
dtype: ... | __init__ | python | tensorflow/agents | tf_agents/bandits/agents/bernoulli_thompson_sampling_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/bernoulli_thompson_sampling_agent.py | Apache-2.0 |
def selective_sum(
values: types.Tensor, partitions: types.Int, num_partitions: int
) -> types.Tensor:
"""Sums entries in `values`, partitioned using `partitions`.
For example,
```python
# Returns `[0 + 4 + 5, 2 + 3 + 4]` i.e. `[9, 6]`.
selective_sum(values=[0, 1, 2, 3, 4, 5],
p... | Sums entries in `values`, partitioned using `partitions`.
For example,
```python
# Returns `[0 + 4 + 5, 2 + 3 + 4]` i.e. `[9, 6]`.
selective_sum(values=[0, 1, 2, 3, 4, 5],
partitions=[0, 1, 1, 1, 0, 0]),
num_partitions=2)
```
Args:
values: a `Tensor` with n... | selective_sum | python | tensorflow/agents | tf_agents/bandits/agents/exp3_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_agent.py | Apache-2.0 |
def __init__(
self,
time_step_spec: types.TimeStep,
action_spec: types.BoundedTensorSpec,
learning_rate: float,
name: Optional[Text] = None,
):
"""Initialize an instance of `Exp3Agent`.
Args:
time_step_spec: A `TimeStep` spec describing the expected `TimeStep`s.
acti... | Initialize an instance of `Exp3Agent`.
Args:
time_step_spec: A `TimeStep` spec describing the expected `TimeStep`s.
action_spec: A scalar `BoundedTensorSpec` with `int32` or `int64` dtype
describing the number of actions for this agent.
learning_rate: A float valued scalar. A higher value... | __init__ | python | tensorflow/agents | tf_agents/bandits/agents/exp3_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_agent.py | Apache-2.0 |
def _train(self, experience, weights=None):
"""Updates the policy based on the data in `experience`.
Note that `experience` should only contain data points that this agent has
not previously seen. If `experience` comes from a replay buffer, this buffer
should be cleared between each call to `train`.
... | Updates the policy based on the data in `experience`.
Note that `experience` should only contain data points that this agent has
not previously seen. If `experience` comes from a replay buffer, this buffer
should be cleared between each call to `train`.
Args:
experience: A batch of experience da... | _train | python | tensorflow/agents | tf_agents/bandits/agents/exp3_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_agent.py | Apache-2.0 |
def testExp3Update(
self,
observation_shape,
num_actions,
action,
log_prob,
reward,
learning_rate,
):
"""Check EXP3 updates for specified actions and rewards."""
# Compute expected update for each action.
expected_update_value = exp3_agent.exp3_update_value(rewar... | Check EXP3 updates for specified actions and rewards. | testExp3Update | python | tensorflow/agents | tf_agents/bandits/agents/exp3_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_agent_test.py | Apache-2.0 |
def __init__(
self,
num_agents: int,
reward_aggregates: Optional[List[float]] = None,
inverse_temperature: float = 0.0,
):
"""Initializes an instace of 'Exp3MixtureVariableCollection'.
Args:
num_agents: (int) the number of agents mixed by the mixture agent.
reward_aggregat... | Initializes an instace of 'Exp3MixtureVariableCollection'.
Args:
num_agents: (int) the number of agents mixed by the mixture agent.
reward_aggregates: A list of floats containing the reward aggregates for
each agent. If not set, the initial values will be 0.
inverse_temperature: The initi... | __init__ | python | tensorflow/agents | tf_agents/bandits/agents/exp3_mixture_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_mixture_agent.py | Apache-2.0 |
def __init__(
self,
agents: List[tf_agent.TFAgent],
variable_collection: Optional[Exp3MixtureVariableCollection] = None,
forgetting: float = 0.999,
max_inverse_temperature: float = 1000.0,
name: Optional[Text] = None,
):
"""Initializes an instance of `Exp3MixtureAgent`.
Ar... | Initializes an instance of `Exp3MixtureAgent`.
Args:
agents: List of TF-Agents agents that this mixture agent trains.
variable_collection: An instance of `Exp3VariableCollection`. If not set,
A default one will be created. It contains all the variables that are
needed to restore the mix... | __init__ | python | tensorflow/agents | tf_agents/bandits/agents/exp3_mixture_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_mixture_agent.py | Apache-2.0 |
def _single_objective_loss(
self,
objective_idx: int,
observations: tf.Tensor,
actions: tf.Tensor,
single_objective_values: tf.Tensor,
weights: types.Tensor = None,
training: bool = False,
) -> tf.Tensor:
"""Computes loss for a single objective.
Args:
objective... | Computes loss for a single objective.
Args:
objective_idx: The index into `self._objective_networks` for a specific
objective network.
observations: A batch of observations.
actions: A batch of actions.
single_objective_values: A batch of objective values shaped as
[batch_si... | _single_objective_loss | python | tensorflow/agents | tf_agents/bandits/agents/greedy_multi_objective_neural_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_multi_objective_neural_agent.py | Apache-2.0 |
def _loss(
self,
experience: types.NestedTensor,
weights: types.Tensor = None,
training: bool = False,
) -> tf_agent.LossInfo:
"""Computes loss for training the objective networks.
Args:
experience: A batch of experience data in the form of a `Trajectory` or
`Transition`... | Computes loss for training the objective networks.
Args:
experience: A batch of experience data in the form of a `Trajectory` or
`Transition`.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights. The output batch loss will be scaled by these weights, and the
... | _loss | python | tensorflow/agents | tf_agents/bandits/agents/greedy_multi_objective_neural_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_multi_objective_neural_agent.py | Apache-2.0 |
def __init__(
self,
observation_spec: types.NestedTensorSpec,
kernel_weights: np.ndarray,
bias: np.ndarray,
):
"""A simple linear network.
Args:
observation_spec: The observation specification.
kernel_weights: A 2-d numpy array of shape [input_size, output_size].
bia... | A simple linear network.
Args:
observation_spec: The observation specification.
kernel_weights: A 2-d numpy array of shape [input_size, output_size].
bias: A 1-d numpy array of shape [output_size].
| __init__ | python | tensorflow/agents | tf_agents/bandits/agents/greedy_multi_objective_neural_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_multi_objective_neural_agent_test.py | Apache-2.0 |
def __init__(self, kernel_weights: np.ndarray, bias: np.ndarray):
"""A simple linear heteroscedastic network.
Args:
kernel_weights: A 2-d numpy array of shape [input_size, output_size].
bias: A 1-d numpy array of shape [output_size].
"""
assert len(kernel_weights.shape) == 2
assert len(... | A simple linear heteroscedastic network.
Args:
kernel_weights: A 2-d numpy array of shape [input_size, output_size].
bias: A 1-d numpy array of shape [output_size].
| __init__ | python | tensorflow/agents | tf_agents/bandits/agents/greedy_multi_objective_neural_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_multi_objective_neural_agent_test.py | Apache-2.0 |
def per_example_reward_loss(
self,
observations: types.NestedTensor,
actions: types.Tensor,
rewards: types.Tensor,
weights: Optional[types.Float] = None,
training: bool = False,
) -> types.Tensor:
"""Computes loss for reward prediction training.
Args:
observations: A... | Computes loss for reward prediction training.
Args:
observations: A batch of observations.
actions: A batch of actions.
rewards: A batch of rewards.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights. The output batch loss will be scaled by these weights, ... | per_example_reward_loss | python | tensorflow/agents | tf_agents/bandits/agents/greedy_reward_prediction_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_reward_prediction_agent.py | Apache-2.0 |
def _loss(
self,
experience: types.NestedTensor,
weights: Optional[types.Float] = None,
training: bool = False,
) -> tf_agent.LossInfo:
"""Computes loss for training the reward and constraint networks.
Args:
experience: A batch of experience data in the form of a `Trajectory` or... | Computes loss for training the reward and constraint networks.
Args:
experience: A batch of experience data in the form of a `Trajectory` or
`Transition`.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights. The output batch loss will be scaled by these weights... | _loss | python | tensorflow/agents | tf_agents/bandits/agents/greedy_reward_prediction_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_reward_prediction_agent.py | Apache-2.0 |
def __init__(
self,
context_dim: int,
num_models: int,
use_eigendecomp: bool = False,
dtype: tf.DType = tf.float32,
name: Optional[Text] = None,
):
"""Initializes an instance of `LinearBanditVariableCollection`.
It creates all the variables needed for `LinearBanditAgent`.
... | Initializes an instance of `LinearBanditVariableCollection`.
It creates all the variables needed for `LinearBanditAgent`.
Args:
context_dim: (int) The context dimension of the bandit environment the
agent will be used on.
num_models: (int) The number of models maintained by the agent. This... | __init__ | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py | Apache-2.0 |
def update_a_and_b_with_forgetting(
a_prev: types.Tensor,
b_prev: types.Tensor,
r: types.Tensor,
x: types.Tensor,
gamma: float,
) -> Tuple[types.Tensor, types.Tensor]:
r"""Update the covariance matrix `a` and the weighted sum of rewards `b`.
This function updates the covariance matrix `a` and t... | Update the covariance matrix `a` and the weighted sum of rewards `b`.
This function updates the covariance matrix `a` and the sum of weighted
rewards `b` using a forgetting factor `gamma`.
Args:
a_prev: previous estimate of `a`.
b_prev: previous estimate of `b`.
r: a `Tensor` of shape [`batch_size`]... | update_a_and_b_with_forgetting | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py | Apache-2.0 |
def theta(self):
"""Returns the matrix of per-arm feature weights.
The returned matrix has shape (num_actions, context_dim).
It's equivalent to a stacking of theta vectors from the paper.
"""
thetas = []
for k in range(self._num_models):
if self._use_eigendecomp:
model_index = pol... | Returns the matrix of per-arm feature weights.
The returned matrix has shape (num_actions, context_dim).
It's equivalent to a stacking of theta vectors from the paper.
| theta | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py | Apache-2.0 |
def _process_experience(self, experience):
"""Given an experience, returns reward, action, observation, and batch size."""
if self._accepts_per_arm_features:
return self._process_experience_per_arm(experience)
else:
return self._process_experience_global(experience) | Given an experience, returns reward, action, observation, and batch size. | _process_experience | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py | Apache-2.0 |
def _process_experience_per_arm(self, experience):
"""Processes the experience in case the agent accepts per-arm features.
In the experience coming from the replay buffer, the reward (and all other
elements) have two batch dimensions `batch_size` and `time_steps`, where
`time_steps` is the number of dr... | Processes the experience in case the agent accepts per-arm features.
In the experience coming from the replay buffer, the reward (and all other
elements) have two batch dimensions `batch_size` and `time_steps`, where
`time_steps` is the number of driver steps executed in each training loop.
We flatten ... | _process_experience_per_arm | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py | Apache-2.0 |
def _process_experience_global(self, experience):
"""Processes the experience in case the agent accepts only global features.
In the experience coming from the replay buffer, the reward (and all other
elements) have two batch dimensions `batch_size` and `time_steps`, where
`time_steps` is the number of... | Processes the experience in case the agent accepts only global features.
In the experience coming from the replay buffer, the reward (and all other
elements) have two batch dimensions `batch_size` and `time_steps`, where
`time_steps` is the number of driver steps executed in each training loop.
We flat... | _process_experience_global | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py | Apache-2.0 |
def _maybe_apply_per_example_weight(
self,
observation: tf.Tensor,
reward: tf.Tensor,
weights: Optional[tf.Tensor],
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Optionally applies per-example weight to observation and rewards."""
if weights is None:
return (observation, reward)
else:... | Optionally applies per-example weight to observation and rewards. | _maybe_apply_per_example_weight | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py | Apache-2.0 |
def _distributed_train_step(self, experience, weights=None):
"""Distributed train fn to be passed as input to run()."""
experience_reward, action, experience_observation, batch_size = (
self._process_experience(experience)
)
self._train_step_counter.assign_add(batch_size)
observation, reward... | Distributed train fn to be passed as input to run(). | _distributed_train_step | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py | Apache-2.0 |
def _train(self, experience, weights=None):
"""Updates the policy based on the data in `experience`.
Note that `experience` should only contain data points that this agent has
not previously seen. If `experience` comes from a replay buffer, this buffer
should be cleared between each call to `train`.
... | Updates the policy based on the data in `experience`.
Note that `experience` should only contain data points that this agent has
not previously seen. If `experience` comes from a replay buffer, this buffer
should be cleared between each call to `train`.
Args:
experience: A batch of experience da... | _train | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py | Apache-2.0 |
def testLinearAgentUpdate(
self,
batch_size,
context_dim,
exploration_policy,
dtype,
use_eigendecomp=False,
set_example_weights=False,
):
"""Check that the agent updates for specified actions and rewards."""
# Construct a `Trajectory` for the given action, observatio... | Check that the agent updates for specified actions and rewards. | testLinearAgentUpdate | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent_test.py | Apache-2.0 |
def testLinearAgentUpdatePerArmFeatures(
self,
batch_size,
context_dim,
exploration_policy,
dtype,
use_eigendecomp=False,
set_example_weights=False,
):
"""Check that the agent updates for specified actions and rewards."""
# Construct a `Trajectory` for the given acti... | Check that the agent updates for specified actions and rewards. | testLinearAgentUpdatePerArmFeatures | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent_test.py | Apache-2.0 |
def testLinearAgentUpdateWithBias(
self,
batch_size,
context_dim,
exploration_policy,
dtype,
use_eigendecomp=False,
set_example_weights=False,
):
"""Check that the agent updates for specified actions and rewards."""
# Construct a `Trajectory` for the given action, ob... | Check that the agent updates for specified actions and rewards. | testLinearAgentUpdateWithBias | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent_test.py | Apache-2.0 |
def testLinearAgentUpdateWithMaskedActions(
self,
batch_size,
context_dim,
exploration_policy,
dtype,
use_eigendecomp=False,
set_example_weights=False,
):
"""Check that the agent updates for specified actions and rewards."""
del use_eigendecomp # Unused in this test... | Check that the agent updates for specified actions and rewards. | testLinearAgentUpdateWithMaskedActions | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent_test.py | Apache-2.0 |
def testLinearAgentUpdateWithForgetting(
self,
batch_size,
context_dim,
exploration_policy,
dtype,
use_eigendecomp=False,
set_example_weights=False,
):
"""Check that the agent updates for specified actions and rewards."""
# We should rewrite this test as it currently ... | Check that the agent updates for specified actions and rewards. | testLinearAgentUpdateWithForgetting | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent_test.py | Apache-2.0 |
def testDistributedLinearAgentUpdate(
self,
batch_size,
context_dim,
exploration_policy,
dtype,
use_eigendecomp=False,
set_example_weights=False,
):
"""Same as above, but uses the distributed train function of the agent."""
del use_eigendecomp # Unused in this test.
... | Same as above, but uses the distributed train function of the agent. | testDistributedLinearAgentUpdate | python | tensorflow/agents | tf_agents/bandits/agents/linear_bandit_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent_test.py | Apache-2.0 |
def _dynamic_partition_of_nested_tensors(
nested_tensor: types.NestedTensor,
partitions: types.Int,
num_partitions: int,
) -> List[types.NestedTensor]:
"""This function takes a nested structure and partitions every element of it.
Specifically it outputs a list of nest that all have the same structure a... | This function takes a nested structure and partitions every element of it.
Specifically it outputs a list of nest that all have the same structure as the
original, and every element of the list is a nest that contains a dynamic
partition of the corresponding original tensors.
Note that this function uses tf.d... | _dynamic_partition_of_nested_tensors | python | tensorflow/agents | tf_agents/bandits/agents/mixture_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/mixture_agent.py | Apache-2.0 |
def __init__(
self,
mixture_distribution: types.Distribution,
agents: Sequence[tf_agent.TFAgent],
name: Optional[Text] = None,
):
"""Initializes an instance of `MixtureAgent`.
Args:
mixture_distribution: An instance of `tfd.Categorical` distribution. This
distribution is... | Initializes an instance of `MixtureAgent`.
Args:
mixture_distribution: An instance of `tfd.Categorical` distribution. This
distribution is used to draw sub-policies by the mixture policy. The
parameters of the distribution is trained by the mixture agent.
agents: List of instances of TF... | __init__ | python | tensorflow/agents | tf_agents/bandits/agents/mixture_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/mixture_agent.py | Apache-2.0 |
def _update_mixture_distribution(self, experience):
"""This function updates the mixture weights given training experience."""
raise NotImplementedError(
'`_update_mixture_distribution` should be '
'implemented by subclasses of `MixtureAgent`.'
) | This function updates the mixture weights given training experience. | _update_mixture_distribution | python | tensorflow/agents | tf_agents/bandits/agents/mixture_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/mixture_agent.py | Apache-2.0 |
def __init__(
self,
num_actions: int,
encoding_dim: int,
dtype: tf.DType = tf.float64,
name: Optional[Text] = None,
):
"""Initializes an instance of `NeuralLinUCBVariableCollection`.
Args:
num_actions: (int) number of actions the agent acts on.
encoding_dim: (int) Th... | Initializes an instance of `NeuralLinUCBVariableCollection`.
Args:
num_actions: (int) number of actions the agent acts on.
encoding_dim: (int) The dimensionality of the output of the encoding
network.
dtype: The type of the variables. Should be one of `tf.float32` and
`tf.float64`... | __init__ | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent.py | Apache-2.0 |
def _loss_using_reward_layer(
self,
observations: types.NestedTensor,
actions: types.Tensor,
rewards: types.Tensor,
weights: Optional[types.Float] = None,
training: bool = False,
) -> tf_agent.LossInfo:
"""Computes loss for reward prediction training.
Args:
observati... | Computes loss for reward prediction training.
Args:
observations: A batch of observations.
actions: A batch of actions.
rewards: A batch of rewards.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights. The output batch loss will be scaled by these weights, ... | _loss_using_reward_layer | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent.py | Apache-2.0 |
def compute_loss_using_reward_layer(
self,
observation: types.NestedTensor,
action: types.Tensor,
reward: types.Tensor,
weights: Optional[types.Float] = None,
training: bool = False,
) -> tf_agent.LossInfo:
"""Computes loss using the reward layer.
Args:
observation: ... | Computes loss using the reward layer.
Args:
observation: A batch of observations.
action: A batch of actions.
reward: A batch of rewards.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights. The output batch loss will be scaled by these weights, and the
... | compute_loss_using_reward_layer | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent.py | Apache-2.0 |
def compute_loss_using_linucb(
self,
observation: types.NestedTensor,
action: types.Tensor,
reward: types.Tensor,
weights: Optional[types.Float] = None,
training: bool = False,
) -> tf_agent.LossInfo:
"""Computes the loss using LinUCB.
Args:
observation: A batch of o... | Computes the loss using LinUCB.
Args:
observation: A batch of observations.
action: A batch of actions.
reward: A batch of rewards.
weights: unused weights.
training: Whether the loss is being used to train.
Returns:
loss: A `LossInfo` containing the loss for the training s... | compute_loss_using_linucb | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent.py | Apache-2.0 |
def compute_loss_using_linucb_distributed(
self,
observation: types.NestedTensor,
action: types.Tensor,
reward: types.Tensor,
weights: Optional[types.Float] = None,
training: bool = False,
) -> tf_agent.LossInfo:
"""Computes the loss using LinUCB distributively.
Args:
... | Computes the loss using LinUCB distributively.
Args:
observation: A batch of observations.
action: A batch of actions.
reward: A batch of rewards.
weights: unused weights.
training: Whether the loss is being used to train.
Returns:
loss: A `LossInfo` containing the loss for... | compute_loss_using_linucb_distributed | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent.py | Apache-2.0 |
def _train(self, experience, weights=None):
"""Updates the policy based on the data in `experience`.
Note that `experience` should only contain data points that this agent has
not previously seen. If `experience` comes from a replay buffer, this buffer
should be cleared between each call to `train`.
... | Updates the policy based on the data in `experience`.
Note that `experience` should only contain data points that this agent has
not previously seen. If `experience` comes from a replay buffer, this buffer
should be cleared between each call to `train`.
Args:
experience: A batch of experience da... | _train | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent.py | Apache-2.0 |
def testNeuralLinUCBUpdateNumTrainSteps0(self, batch_size=1, context_dim=10):
"""Check NeuralLinUCBAgent updates when behaving like LinUCB."""
# Construct a `Trajectory` for the given action, observation, reward.
num_actions = 5
initial_step, final_step = _get_initial_and_final_steps(
batch_siz... | Check NeuralLinUCBAgent updates when behaving like LinUCB. | testNeuralLinUCBUpdateNumTrainSteps0 | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent_test.py | Apache-2.0 |
def testNeuralLinUCBUpdateDistributed(self, batch_size=1, context_dim=10):
"""Same as above but with distributed LinUCB updates."""
# Construct a `Trajectory` for the given action, observation, reward.
num_actions = 5
initial_step, final_step = _get_initial_and_final_steps(
batch_size, context_... | Same as above but with distributed LinUCB updates. | testNeuralLinUCBUpdateDistributed | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent_test.py | Apache-2.0 |
def testNeuralLinUCBUpdateNumTrainSteps10(self, batch_size=1, context_dim=10):
"""Check NeuralLinUCBAgent updates when behaving like eps-greedy."""
# Construct a `Trajectory` for the given action, observation, reward.
num_actions = 5
initial_step, final_step = _get_initial_and_final_steps(
batc... | Check NeuralLinUCBAgent updates when behaving like eps-greedy. | testNeuralLinUCBUpdateNumTrainSteps10 | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent_test.py | Apache-2.0 |
def testNeuralLinUCBUpdateNumTrainSteps10MaskedActions(
self, batch_size=1, context_dim=10
):
"""Check updates when behaving like eps-greedy and using masked actions."""
# Construct a `Trajectory` for the given action, observation, reward.
num_actions = 5
initial_step, final_step = _get_initial... | Check updates when behaving like eps-greedy and using masked actions. | testNeuralLinUCBUpdateNumTrainSteps10MaskedActions | python | tensorflow/agents | tf_agents/bandits/agents/neural_linucb_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent_test.py | Apache-2.0 |
def compute_score_tensor_for_cascading(
chosen_index: types.Int,
chosen_value: types.Float,
num_slots: int,
non_click_score: float = -1.0,
) -> types.Float:
"""Gives scores for all items in a batch.
The score of items that are before the chosen index is `-1`, the score of
the chosen values are gi... | Gives scores for all items in a batch.
The score of items that are before the chosen index is `-1`, the score of
the chosen values are given by `chosen_value`. The rest of the items receive
a score of `0`. TODO(b/206685896): Normalize theses scores or let the user
selected the negative feedback reward.
Args... | compute_score_tensor_for_cascading | python | tensorflow/agents | tf_agents/bandits/agents/ranking_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/ranking_agent.py | Apache-2.0 |
def __init__(
self,
time_step_spec: types.TimeStep,
action_spec: types.BoundedTensorSpec,
scoring_network: types.Network,
optimizer: types.Optimizer,
policy_type: RankingPolicyType = RankingPolicyType.COSINE_DISTANCE,
error_loss_fn: types.LossFn = tf.compat.v1.losses.mean_squar... | Initializes an instance of RankingAgent.
Args:
time_step_spec: A `TimeStep` spec of the expected time_steps.
action_spec: A nest of `BoundedTensorSpec` representing the actions.
scoring_network: The network that outputs scores for items.
optimizer: The optimizer for the agent.
policy_... | __init__ | python | tensorflow/agents | tf_agents/bandits/agents/ranking_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/ranking_agent.py | Apache-2.0 |
def _loss(
self,
experience: types.NestedTensor,
weights: Optional[types.Tensor] = None,
training: bool = False,
) -> tf_agent.LossInfo:
"""Computes loss for training the reward and constraint networks.
Args:
experience: A batch of experience data in the form of a `Trajectory` o... | Computes loss for training the reward and constraint networks.
Args:
experience: A batch of experience data in the form of a `Trajectory` or
`Transition`.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights. The output batch loss will be scaled by these weights... | _loss | python | tensorflow/agents | tf_agents/bandits/agents/ranking_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/ranking_agent.py | Apache-2.0 |
def _construct_sample_weights(self, reward, observation, weights):
"""Returns the training weights based on all the necessary information.
The input weights might be `None` or of shape `[1]`, or [`batch_size`]. The
shape of the output shape is always `[batch_size, num_slots]`.
Args:
reward: The ... | Returns the training weights based on all the necessary information.
The input weights might be `None` or of shape `[1]`, or [`batch_size`]. The
shape of the output shape is always `[batch_size, num_slots]`.
Args:
reward: The reward tensor or nest. Its structure depends on the feedback
model... | _construct_sample_weights | python | tensorflow/agents | tf_agents/bandits/agents/ranking_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/ranking_agent.py | Apache-2.0 |
def sum_reward_weighted_observations(
r: types.Tensor, x: types.Tensor
) -> types.Tensor:
"""Calculates an update used by some Bandit algorithms.
Given an observation `x` and corresponding reward `r`, the weigthed
observations vector (denoted `b` here) should be updated as `b = b + r * x`.
This function ca... | Calculates an update used by some Bandit algorithms.
Given an observation `x` and corresponding reward `r`, the weigthed
observations vector (denoted `b` here) should be updated as `b = b + r * x`.
This function calculates the sum of weighted rewards for batched
observations `x`.
Args:
r: a `Tensor` of ... | sum_reward_weighted_observations | python | tensorflow/agents | tf_agents/bandits/agents/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/utils.py | Apache-2.0 |
def build_laplacian_over_ordinal_integer_actions(
action_spec: types.BoundedTensorSpec,
) -> types.Tensor:
"""Build the unnormalized Laplacian matrix over ordinal integer actions.
Assuming integer actions, this functions builds the (unnormalized) Laplacian
matrix of the graph implied over the action space. T... | Build the unnormalized Laplacian matrix over ordinal integer actions.
Assuming integer actions, this functions builds the (unnormalized) Laplacian
matrix of the graph implied over the action space. The graph vertices are the
integers {0...action_spec.maximum - 1}. Two vertices are adjacent if they
correspond t... | build_laplacian_over_ordinal_integer_actions | python | tensorflow/agents | tf_agents/bandits/agents/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/utils.py | Apache-2.0 |
def compute_pairwise_distances(input_vecs: types.Tensor) -> types.Tensor:
"""Compute the pairwise distances matrix.
Given input embedding vectors, this utility computes the (squared) pairwise
distances matrix.
Args:
input_vecs: a `Tensor`. Input embedding vectors (one per row).
Returns:
The (square... | Compute the pairwise distances matrix.
Given input embedding vectors, this utility computes the (squared) pairwise
distances matrix.
Args:
input_vecs: a `Tensor`. Input embedding vectors (one per row).
Returns:
The (squared) pairwise distances matrix. A dense float `Tensor` of shape
[`num_vectors... | compute_pairwise_distances | python | tensorflow/agents | tf_agents/bandits/agents/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/utils.py | Apache-2.0 |
def build_laplacian_nearest_neighbor_graph(
input_vecs: types.Tensor, k: int = 1
) -> types.Tensor:
"""Build the Laplacian matrix of a nearest neighbor graph.
Given input embedding vectors, this utility returns the Laplacian matrix of
the induced k-nearest-neighbor graph.
Args:
input_vecs: a `Tensor`.... | Build the Laplacian matrix of a nearest neighbor graph.
Given input embedding vectors, this utility returns the Laplacian matrix of
the induced k-nearest-neighbor graph.
Args:
input_vecs: a `Tensor`. Input embedding vectors (one per row). Shaped
`[num_vectors, ...]`.
k: an integer. Number of neare... | build_laplacian_nearest_neighbor_graph | python | tensorflow/agents | tf_agents/bandits/agents/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/utils.py | Apache-2.0 |
def process_experience_for_neural_agents(
experience: types.NestedTensor,
accepts_per_arm_features: bool,
training_data_spec: types.NestedTensorSpec,
) -> Tuple[types.NestedTensor, types.Tensor, types.Tensor]:
"""Processes the experience and prepares it for the network of the agent.
First the reward, t... | Processes the experience and prepares it for the network of the agent.
First the reward, the action, and the observation are flattened to have only
one batch dimension. Then, if the experience includes chosen action features
in the policy info, it gets copied in place of the per-arm observation.
Args:
exp... | process_experience_for_neural_agents | python | tensorflow/agents | tf_agents/bandits/agents/utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/utils.py | Apache-2.0 |
def _get_replay_buffer(
data_spec, batch_size, steps_per_loop, async_steps_per_loop
):
"""Return a `TFUniformReplayBuffer` for the given `agent`."""
return bandit_replay_buffer.BanditReplayBuffer(
data_spec=data_spec,
batch_size=batch_size,
max_length=steps_per_loop * async_steps_per_loop,
) | Return a `TFUniformReplayBuffer` for the given `agent`. | _get_replay_buffer | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/trainer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/trainer.py | Apache-2.0 |
def _get_training_loop(
driver, replay_buffer, agent, steps, async_steps_per_loop
):
"""Returns a `tf.function` that runs the driver and training loops.
Args:
driver: an instance of `Driver`.
replay_buffer: an instance of `ReplayBuffer`.
agent: an instance of `TFAgent`.
steps: an integer indica... | Returns a `tf.function` that runs the driver and training loops.
Args:
driver: an instance of `Driver`.
replay_buffer: an instance of `ReplayBuffer`.
agent: an instance of `TFAgent`.
steps: an integer indicating how many driver steps should be executed and
presented to the trainer during each t... | _get_training_loop | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/trainer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/trainer.py | Apache-2.0 |
def training_loop(train_step, metrics):
"""Returns a function that runs a single training loop and logs metrics."""
for batch_id in range(async_steps_per_loop):
driver.run()
_export_metrics_and_summaries(
step=train_step * async_steps_per_loop + batch_id, metrics=metrics
)
batch_... | Returns a function that runs a single training loop and logs metrics. | training_loop | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/trainer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/trainer.py | Apache-2.0 |
def restore_and_get_checkpoint_manager(root_dir, agent, metrics, step_metric):
"""Restores from `root_dir` and returns a function that writes checkpoints."""
trackable_objects = {metric.name: metric for metric in metrics}
trackable_objects[AGENT_CHECKPOINT_NAME] = agent
trackable_objects[STEP_CHECKPOINT_NAME] =... | Restores from `root_dir` and returns a function that writes checkpoints. | restore_and_get_checkpoint_manager | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/trainer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/trainer.py | Apache-2.0 |
def train(
root_dir,
agent,
environment,
training_loops,
steps_per_loop,
async_steps_per_loop=None,
additional_metrics=(),
get_replay_buffer_fn=None,
get_training_loop_fn=None,
training_data_spec_transformation_fn=None,
save_policy=True,
resume_training_loops=False,
):
... | Perform `training_loops` iterations of training.
Checkpoint results.
If one or more baseline_reward_fns are provided, the regret is computed
against each one of them. Here is example baseline_reward_fn:
def baseline_reward_fn(observation, per_action_reward_fns):
rewards = ... # compute reward for each arm... | train | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/trainer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/trainer.py | Apache-2.0 |
def get_bounded_reward_random_environment(
observation_shape, action_shape, batch_size, num_actions
):
"""Returns a RandomBanditEnvironment with U(0, 1) observation and reward."""
overall_shape = [batch_size] + observation_shape
observation_distribution = tfd.Independent(
tfd.Uniform(low=tf.zeros(overal... | Returns a RandomBanditEnvironment with U(0, 1) observation and reward. | get_bounded_reward_random_environment | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/trainer_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/trainer_test.py | Apache-2.0 |
def testTrainerExportsCheckpoints(
self,
num_actions,
observation_shape,
action_shape,
batch_size,
training_loops,
steps_per_loop,
learning_rate,
):
"""Exercises trainer code, checks that expected checkpoints are exported."""
root_dir = tempfile.mkdtemp(dir=os.g... | Exercises trainer code, checks that expected checkpoints are exported. | testTrainerExportsCheckpoints | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/trainer_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/trainer_test.py | Apache-2.0 |
def get_environment_and_optimal_functions_by_name(environment_name, batch_size):
"""Helper function that outputs an environment and related functions.
Args:
environment_name: The (string) name of the desired environment.
batch_size: The batch_size
Returns:
A tuple of (environment, optimal_reward_fn,... | Helper function that outputs an environment and related functions.
Args:
environment_name: The (string) name of the desired environment.
batch_size: The batch_size
Returns:
A tuple of (environment, optimal_reward_fn, optimal_action_fn), where the
latter two functions are for calculating regret and... | get_environment_and_optimal_functions_by_name | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/trainer_test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/trainer_test_utils.py | Apache-2.0 |
def get_agent_by_name(agent_name, time_step_spec, action_spec):
"""Helper function that outputs an agent.
Args:
agent_name: The name (string) of the desired agent.
time_step_spec: The time step spec of the environment on which the agent
acts.
action_spec: The action spec on which the agent acts.
... | Helper function that outputs an agent.
Args:
agent_name: The name (string) of the desired agent.
time_step_spec: The time step spec of the environment on which the agent
acts.
action_spec: The action spec on which the agent acts.
Returns:
The desired agent.
| get_agent_by_name | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/trainer_test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/trainer_test_utils.py | Apache-2.0 |
def _all_rewards(observation, hidden_param):
"""Outputs rewards for all actions, given an observation."""
hidden_param = tf.cast(hidden_param, dtype=tf.float32)
global_obs = observation[bandit_spec_utils.GLOBAL_FEATURE_KEY]
per_arm_obs = observation[bandit_spec_utils.PER_ARM_FEATURE_KEY]
num_actions... | Outputs rewards for all actions, given an observation. | _all_rewards | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/train_eval_per_arm_stationary_linear.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/train_eval_per_arm_stationary_linear.py | Apache-2.0 |
def order_items_from_action_fn(orig_trajectory):
"""Puts the features of the selected items in the recommendation order.
This function is used to make sure that at training the item observation is
filled with features of items selected by the policy, in the order of the
selection. Features of unselecte... | Puts the features of the selected items in the recommendation order.
This function is used to make sure that at training the item observation is
filled with features of items selected by the policy, in the order of the
selection. Features of unselected items are discarded.
Args:
orig_trajectory:... | order_items_from_action_fn | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/train_eval_ranking.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/train_eval_ranking.py | Apache-2.0 |
def _global_context_sampling_fn():
"""Generates one sample of global features.
It generates a dictionary of size `NUM_GLOBAL_FEATURES`, with the following
syntax:
{...,
'global_feature_4': ['43'],
...
}
That is, the values are one-element numpy arrays of strings.
Returns:
... | Generates one sample of global features.
It generates a dictionary of size `NUM_GLOBAL_FEATURES`, with the following
syntax:
{...,
'global_feature_4': ['43'],
...
}
That is, the values are one-element numpy arrays of strings.
Returns:
A dictionary with string keys and numpy s... | _global_context_sampling_fn | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/train_eval_sparse_features.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/train_eval_sparse_features.py | Apache-2.0 |
def _arm_context_sampling_fn():
"""Generates one sample of arm features.
It generates a dictionary of size `NUM_ARM_FEATURES`, with the following
syntax:
{...,
'arm_feature_7': ['29'],
...
}
That is, the values are one-element numpy arrays of strings. Note that the
output sample... | Generates one sample of arm features.
It generates a dictionary of size `NUM_ARM_FEATURES`, with the following
syntax:
{...,
'arm_feature_7': ['29'],
...
}
That is, the values are one-element numpy arrays of strings. Note that the
output sample is for one arm and one non-batched tim... | _arm_context_sampling_fn | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/train_eval_sparse_features.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/train_eval_sparse_features.py | Apache-2.0 |
def _reward_fn(global_features, arm_features):
"""Outputs a [0, 1] float given a sample.
The output reward is generated by hashing the concatenation of feature keys
and values, then adding all up, taking modulo by 1000, and normalizing.
Args:
global_features: A dictionary with string keys and 1d... | Outputs a [0, 1] float given a sample.
The output reward is generated by hashing the concatenation of feature keys
and values, then adding all up, taking modulo by 1000, and normalizing.
Args:
global_features: A dictionary with string keys and 1d string numpy array
values.
arm_features... | _reward_fn | python | tensorflow/agents | tf_agents/bandits/agents/examples/v2/train_eval_sparse_features.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples/v2/train_eval_sparse_features.py | Apache-2.0 |
def trajectory_for_bandit(
initial_step: types.TimeStep,
action_step: types.PolicyStep,
final_step: types.TimeStep,
) -> types.NestedTensor:
"""Builds a trajectory from a single-step bandit episode.
Since all episodes consist of a single step, the returned `Trajectory` has no
time dimension. All inpu... | Builds a trajectory from a single-step bandit episode.
Since all episodes consist of a single step, the returned `Trajectory` has no
time dimension. All input and output `Tensor`s/arrays are expected to have
shape `[batch_size, ...]`.
Args:
initial_step: A `TimeStep` returned from `environment.step(...)`.... | trajectory_for_bandit | python | tensorflow/agents | tf_agents/bandits/drivers/driver_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/drivers/driver_utils.py | Apache-2.0 |
def _reset(self) -> ts.TimeStep:
"""Returns a time step containing an observation.
It should not be overridden by Bandit environment implementations.
Returns:
A time step of type FIRST containing an observation.
"""
return ts.restart(
self._observe(),
batch_size=self.batch_si... | Returns a time step containing an observation.
It should not be overridden by Bandit environment implementations.
Returns:
A time step of type FIRST containing an observation.
| _reset | python | tensorflow/agents | tf_agents/bandits/environments/bandit_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bandit_py_environment.py | Apache-2.0 |
def _step(self, action: types.NestedArray) -> ts.TimeStep:
"""Returns a time step containing the reward for the action taken.
The returning time step also contains the next observation.
It should not be overridden by bandit environment implementations.
Args:
action: The action taken by the Bandi... | Returns a time step containing the reward for the action taken.
The returning time step also contains the next observation.
It should not be overridden by bandit environment implementations.
Args:
action: The action taken by the Bandit policy.
Returns:
A time step of type LAST containing ... | _step | python | tensorflow/agents | tf_agents/bandits/environments/bandit_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bandit_py_environment.py | Apache-2.0 |
def _apply_action(self, action: types.NestedArray) -> types.Float:
"""Applies `action` to the Environment and returns the corresponding reward.
Args:
action: A value conforming action_spec that will be taken as action in the
environment.
Returns:
A float value that is the reward receiv... | Applies `action` to the Environment and returns the corresponding reward.
Args:
action: A value conforming action_spec that will be taken as action in the
environment.
Returns:
A float value that is the reward received by the environment.
| _apply_action | python | tensorflow/agents | tf_agents/bandits/environments/bandit_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bandit_py_environment.py | Apache-2.0 |
def __init__(
self,
time_step_spec: Optional[types.NestedArray] = None,
action_spec: Optional[types.NestedArray] = None,
batch_size: Optional[types.Int] = 1,
name: Optional[Text] = None,
):
"""Initialize instances of `BanditTFEnvironment`.
Args:
time_step_spec: A `TimeStep... | Initialize instances of `BanditTFEnvironment`.
Args:
time_step_spec: A `TimeStep` namedtuple containing `TensorSpec`s defining
the tensors returned by `step()` (step_type, reward, discount, and
observation).
action_spec: A nest of BoundedTensorSpec representing the actions of the
... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/bandit_tf_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bandit_tf_environment.py | Apache-2.0 |
def testObservationAndRewardShapes(self, batch_size, observation_shape):
"""Exercise `reset` and `step`. Ensure correct shapes are returned."""
env = ZerosEnvironment(
batch_size=batch_size, observation_shape=observation_shape
)
@common.function
def observation_and_reward():
observati... | Exercise `reset` and `step`. Ensure correct shapes are returned. | testObservationAndRewardShapes | python | tensorflow/agents | tf_agents/bandits/environments/bandit_tf_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bandit_tf_environment_test.py | Apache-2.0 |
def testTwoConsecutiveSteps(self, batch_size, observation_shape):
"""Test two consecutive calls to `step`."""
env = ZerosEnvironment(
batch_size=batch_size, observation_shape=observation_shape
)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.evaluate(env.reset())
self.ev... | Test two consecutive calls to `step`. | testTwoConsecutiveSteps | python | tensorflow/agents | tf_agents/bandits/environments/bandit_tf_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bandit_tf_environment_test.py | Apache-2.0 |
def testMultipleRewardsEnvironment(
self, batch_size, observation_shape, num_rewards
):
"""Test the multiple-rewards case. Ensure correct shapes are returned."""
env = MultipleRewardsEnvironment(
observation_shape=observation_shape,
batch_size=batch_size,
num_rewards=num_rewards... | Test the multiple-rewards case. Ensure correct shapes are returned. | testMultipleRewardsEnvironment | python | tensorflow/agents | tf_agents/bandits/environments/bandit_tf_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bandit_tf_environment_test.py | Apache-2.0 |
def _maybe_add_one_action(mask):
"""For time steps where the mask is all zeros, adds one action randomly."""
batch_size = tf.shape(mask)[0]
num_actions = tf.shape(mask)[1]
extra_actions = tf.one_hot(
tf.random.uniform([batch_size], 0, num_actions, dtype=tf.int32),
depth=num_actions,
dtype=tf.i... | For time steps where the mask is all zeros, adds one action randomly. | _maybe_add_one_action | python | tensorflow/agents | tf_agents/bandits/environments/bernoulli_action_mask_tf_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bernoulli_action_mask_tf_environment.py | Apache-2.0 |
def __init__(
self,
original_environment: bandit_tf_environment.BanditTFEnvironment,
action_constraint_join_fn: Callable[
[types.TensorSpec, types.TensorSpec], types.TensorSpec
],
action_probability: float,
):
"""Initializes a `BernoulliActionMaskTFEnvironment`.
Args:
... | Initializes a `BernoulliActionMaskTFEnvironment`.
Args:
original_environment: Instance of `BanditTFEnvironment`. This environment
will be wrapped.
action_constraint_join_fn: A function that joins the osbervation from the
original environment with the generated masks.
action_probab... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/bernoulli_action_mask_tf_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bernoulli_action_mask_tf_environment.py | Apache-2.0 |
def __init__(
self, means: Sequence[types.Float], batch_size: Optional[types.Int] = 1
):
"""Initializes a Bernoulli Bandit environment.
Args:
means: vector of floats in [0, 1], the mean rewards for actions. The
number of arms is determined by its length.
batch_size: (int) The batch ... | Initializes a Bernoulli Bandit environment.
Args:
means: vector of floats in [0, 1], the mean rewards for actions. The
number of arms is determined by its length.
batch_size: (int) The batch size.
| __init__ | python | tensorflow/agents | tf_agents/bandits/environments/bernoulli_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bernoulli_py_environment.py | Apache-2.0 |
def _batched_table_lookup(tbl, row, col):
"""Mapped 2D table lookup.
Args:
tbl: a `Tensor` of shape `[r, s, t]`.
row: a `Tensor` of dtype `int32` with shape `[r]` and values in the range
`[0, s - 1]`.
col: a `Tensor` of dtype `int32` with shape `[r]` and values in the range
`[0, t - 1]`.
... | Mapped 2D table lookup.
Args:
tbl: a `Tensor` of shape `[r, s, t]`.
row: a `Tensor` of dtype `int32` with shape `[r]` and values in the range
`[0, s - 1]`.
col: a `Tensor` of dtype `int32` with shape `[r]` and values in the range
`[0, t - 1]`.
Returns:
A `Tensor` `x` with shape `[r]` w... | _batched_table_lookup | python | tensorflow/agents | tf_agents/bandits/environments/classification_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/classification_environment.py | Apache-2.0 |
def __init__(
self,
dataset: tf.data.Dataset,
reward_distribution: types.Distribution,
batch_size: types.Int,
label_dtype_cast: Optional[tf.DType] = None,
shuffle_buffer_size: Optional[types.Int] = None,
repeat_dataset: Optional[bool] = True,
prefetch_size: Optional[types... | Initialize `ClassificationBanditEnvironment`.
Args:
dataset: a `tf.data.Dataset` consisting of two `Tensor`s, [inputs, labels]
where inputs can be of any shape, while labels are integer class labels.
The label tensor can be of any rank as long as it has 1 element.
reward_distribution: a... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/classification_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/classification_environment.py | Apache-2.0 |
def testObservationShapeAndValue(self, context, labels, batch_size):
"""Test that observations have correct shape and values from `context`."""
dataset = (
tf.data.Dataset.from_tensor_slices((context, labels))
.repeat()
.shuffle(4 * batch_size)
)
# Rewards of 1. is given when act... | Test that observations have correct shape and values from `context`. | testObservationShapeAndValue | python | tensorflow/agents | tf_agents/bandits/environments/classification_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/classification_environment_test.py | Apache-2.0 |
def testReturnsCorrectRewards(self):
"""Test that rewards are being returned correctly for a simple case."""
# Reward of 1 is given if action == (context % 3)
context = tf.reshape(tf.range(128), shape=[128, 1])
labels = tf.math.mod(context, 3)
batch_size = 32
dataset = (
tf.data.Dataset.... | Test that rewards are being returned correctly for a simple case. | testReturnsCorrectRewards | python | tensorflow/agents | tf_agents/bandits/environments/classification_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/classification_environment_test.py | Apache-2.0 |
def testPreviousLabelIsSetCorrectly(self):
"""Test that the previous label is set correctly for a simple case."""
# Reward of 1 is given if action == (context % 3)
context = tf.reshape(tf.range(128), shape=[128, 1])
labels = tf.math.mod(context, 3)
batch_size = 4
dataset = (
tf.data.Data... | Test that the previous label is set correctly for a simple case. | testPreviousLabelIsSetCorrectly | python | tensorflow/agents | tf_agents/bandits/environments/classification_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/classification_environment_test.py | Apache-2.0 |
def testShuffle(self):
"""Test that dataset is being shuffled when asked."""
# Reward of 1 is given if action == (context % 3)
context = tf.reshape(tf.range(128), shape=[128, 1])
labels = tf.math.mod(context, 3)
batch_size = 32
dataset = (
tf.data.Dataset.from_tensor_slices((context, lab... | Test that dataset is being shuffled when asked. | testShuffle | python | tensorflow/agents | tf_agents/bandits/environments/classification_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/classification_environment_test.py | Apache-2.0 |
def testPrefetch(self, mock_dataset_iterator):
"""Test that dataset is being prefetched when asked."""
mock_dataset_iterator.return_value = 'mock_iterator_result'
# Reward of 1 is given if action == (context % 3)
context = tf.reshape(tf.range(128), shape=[128, 1])
labels = tf.math.mod(context, 3)
... | Test that dataset is being prefetched when asked. | testPrefetch | python | tensorflow/agents | tf_agents/bandits/environments/classification_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/classification_environment_test.py | Apache-2.0 |
def _validate_mushroom_data(numpy_data):
"""Checks if the numpy array looks like the mushroom dataset.
Args:
numpy_data: numpy array of rank 2 consisting of single characters. It should
contain the mushroom dataset with each column being a feature and each row
being a sample.
"""
assert numpy_d... | Checks if the numpy array looks like the mushroom dataset.
Args:
numpy_data: numpy array of rank 2 consisting of single characters. It should
contain the mushroom dataset with each column being a feature and each row
being a sample.
| _validate_mushroom_data | python | tensorflow/agents | tf_agents/bandits/environments/dataset_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/dataset_utilities.py | Apache-2.0 |
def _one_hot(data):
"""Encodes columns of a numpy array as one-hot.
Args:
data: A numpy array of rank 2. Every column is a categorical feature and
every row is a sample.
Returns:
A 0/1 numpy array of rank 2 containing the same number of rows as the input.
The number of columns is equal to the ... | Encodes columns of a numpy array as one-hot.
Args:
data: A numpy array of rank 2. Every column is a categorical feature and
every row is a sample.
Returns:
A 0/1 numpy array of rank 2 containing the same number of rows as the input.
The number of columns is equal to the sum of distinct elements ... | _one_hot | python | tensorflow/agents | tf_agents/bandits/environments/dataset_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/dataset_utilities.py | Apache-2.0 |
def convert_mushroom_csv_to_tf_dataset(file_path, buffer_size=40000):
"""Converts the mushroom CSV dataset into a `tf.Dataset`.
The dataset CSV contains the label in the first column, then the features.
Two example rows:
`p,x,s,n,t,p,f,c,n,k,e,e,s,s,w,w,p,w,o,p,k,s,u`: poisonous;
`e,x,s,y,t,a,f,c,b,k,e,c... | Converts the mushroom CSV dataset into a `tf.Dataset`.
The dataset CSV contains the label in the first column, then the features.
Two example rows:
`p,x,s,n,t,p,f,c,n,k,e,e,s,s,w,w,p,w,o,p,k,s,u`: poisonous;
`e,x,s,y,t,a,f,c,b,k,e,c,s,s,w,w,p,w,o,p,n,n,g`: edible.
Args:
file_path: Path to the CSV fi... | convert_mushroom_csv_to_tf_dataset | python | tensorflow/agents | tf_agents/bandits/environments/dataset_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/dataset_utilities.py | Apache-2.0 |
def mushroom_reward_distribution(
r_noeat, r_eat_safe, r_eat_poison_bad, r_eat_poison_good, prob_poison_bad
):
"""Creates a distribution for rewards for the mushroom environment.
Args:
r_noeat: (float) Reward value for not eating the mushroom.
r_eat_safe: (float) Reward value for eating an edible mushr... | Creates a distribution for rewards for the mushroom environment.
Args:
r_noeat: (float) Reward value for not eating the mushroom.
r_eat_safe: (float) Reward value for eating an edible mushroom.
r_eat_poison_bad: (float) Reward value for eating and getting poisoned from
a poisonous mushroom.
r_e... | mushroom_reward_distribution | python | tensorflow/agents | tf_agents/bandits/environments/dataset_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/dataset_utilities.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.