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_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 |
def load_movielens_data(data_file, delimiter=','):
"""Loads the movielens data and returns the ratings matrix."""
ratings_matrix = np.zeros([MOVIELENS_NUM_USERS, MOVIELENS_NUM_MOVIES])
with tf.io.gfile.GFile(data_file, 'r') as infile:
# The file is a csv with rows containing:
# user id | item id | rating ... | Loads the movielens data and returns the ratings matrix. | load_movielens_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 _update_row(input_x, updates, row_index):
"""Updates the i-th row of tensor `x` with the values given in `updates`.
Args:
input_x: the input tensor.
updates: the values to place on the i-th row of `x`.
row_index: which row to update.
Returns:
The updated tensor (same shape as `x`).
"""
n... | Updates the i-th row of tensor `x` with the values given in `updates`.
Args:
input_x: the input tensor.
updates: the values to place on the i-th row of `x`.
row_index: which row to update.
Returns:
The updated tensor (same shape as `x`).
| _update_row | python | tensorflow/agents | tf_agents/bandits/environments/drifting_linear_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/drifting_linear_environment.py | Apache-2.0 |
def _apply_givens_rotation(cosa, sina, axis_i, axis_j, input_x):
"""Applies a Givens rotation on tensor `x`.
Reference on Givens rotations:
https://en.wikipedia.org/wiki/Givens_rotation
Args:
cosa: the cosine of the angle.
sina: the sine of the angle.
axis_i: the first axis of rotation.
axis_j... | Applies a Givens rotation on tensor `x`.
Reference on Givens rotations:
https://en.wikipedia.org/wiki/Givens_rotation
Args:
cosa: the cosine of the angle.
sina: the sine of the angle.
axis_i: the first axis of rotation.
axis_j: the second axis of rotation.
input_x: the input tensor.
Retur... | _apply_givens_rotation | python | tensorflow/agents | tf_agents/bandits/environments/drifting_linear_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/drifting_linear_environment.py | Apache-2.0 |
def __init__(
self,
observation_distribution: types.Distribution,
observation_to_reward_distribution: types.Distribution,
drift_distribution: types.Distribution,
additive_reward_distribution: types.Distribution,
):
"""Initialize the parameters of the drifting linear dynamics.
Ar... | Initialize the parameters of the drifting linear dynamics.
Args:
observation_distribution: A distribution from tfp.distributions with shape
`[batch_size, observation_dim]` Note that the values of `batch_size` and
`observation_dim` are deduced from the distribution.
observation_to_reward... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/drifting_linear_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/drifting_linear_environment.py | Apache-2.0 |
def __init__(
self,
observation_distribution: types.Distribution,
observation_to_reward_distribution: types.Distribution,
drift_distribution: types.Distribution,
additive_reward_distribution: types.Distribution,
):
"""Initialize the environment with the dynamics parameters.
Args... | Initialize the environment with the dynamics parameters.
Args:
observation_distribution: A distribution from `tfp.distributions` with
shape `[batch_size, observation_dim]`. Note that the values of
`batch_size` and `observation_dim` are deduced from the distribution.
observation_to_rewar... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/drifting_linear_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/drifting_linear_environment.py | Apache-2.0 |
def testObservationToRewardsDoesNotVary(
self, observation_shape, action_shape, batch_size, seed
):
"""Ensure that `observation_to_reward` does not change with zero drift."""
tf.compat.v1.set_random_seed(seed)
env = get_deterministic_gaussian_non_stationary_environment(
observation_shape,
... | Ensure that `observation_to_reward` does not change with zero drift. | testObservationToRewardsDoesNotVary | python | tensorflow/agents | tf_agents/bandits/environments/drifting_linear_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/drifting_linear_environment_test.py | Apache-2.0 |
def testObservationToRewardsVaries(
self, observation_shape, action_shape, batch_size, seed
):
"""Ensure that `observation_to_reward` changes with non-zero drift."""
tf.compat.v1.set_random_seed(seed)
env = get_deterministic_gaussian_non_stationary_environment(
observation_shape,
act... | Ensure that `observation_to_reward` changes with non-zero drift. | testObservationToRewardsVaries | python | tensorflow/agents | tf_agents/bandits/environments/drifting_linear_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/drifting_linear_environment_test.py | Apache-2.0 |
def __call__(self, x, enable_noise=True):
"""Outputs reward given observation.
Args:
x: Observation vector.
enable_noise: Whether to add normal noise to the reward or not.
Returns:
A scalar value: the reward.
"""
mu = np.dot(x, self.theta)
if enable_noise:
return np.ran... | Outputs reward given observation.
Args:
x: Observation vector.
enable_noise: Whether to add normal noise to the reward or not.
Returns:
A scalar value: the reward.
| __call__ | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def sliding_linear_reward_fn_generator(context_dim, num_actions, variance):
"""A function that returns `num_actions` noisy linear functions.
Every linear function has an underlying parameter consisting of `context_dim`
consecutive integers. For example, with `context_dim = 3` and
`num_actions = 2`, the paramet... | A function that returns `num_actions` noisy linear functions.
Every linear function has an underlying parameter consisting of `context_dim`
consecutive integers. For example, with `context_dim = 3` and
`num_actions = 2`, the parameter of the linear function associated with
action 1 is `[1.0, 2.0, 3.0]`.
Arg... | sliding_linear_reward_fn_generator | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def normalized_sliding_linear_reward_fn_generator(
context_dim, num_actions, variance
):
"""Similar to the function above, but returns smaller-range functions.
Every linear function has an underlying parameter consisting of `context_dim`
floats of equal distance from each other. For example, with `context_di... | Similar to the function above, but returns smaller-range functions.
Every linear function has an underlying parameter consisting of `context_dim`
floats of equal distance from each other. For example, with `context_dim = 3`,
`num_actions = 2`, the parameter of the linear function associated with
action 1 is `[... | normalized_sliding_linear_reward_fn_generator | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def structured_linear_reward_fn_generator(
context_dim, num_actions, variance, drift_coefficient=0.1
):
"""A function that returns `num_actions` noisy linear functions.
Every linear function is related to its previous one:
```
theta_new = theta_previous + a * drift
```
Args:
context_dim: Number of... | A function that returns `num_actions` noisy linear functions.
Every linear function is related to its previous one:
```
theta_new = theta_previous + a * drift
```
Args:
context_dim: Number of parameters per function.
num_actions: Number of functions returned.
variance: Variance of the noisy line... | structured_linear_reward_fn_generator | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def random_linear_multiple_reward_fn_generator(
context_dim, num_actions, num_rewards, squeeze_dims=True
):
"""A function that returns `num_actions` linear functions.
For each action, the corresponding linear function has underlying parameters
of shape [`context_dim`, 'num_rewards']. Optionally, squeeze can ... | A function that returns `num_actions` linear functions.
For each action, the corresponding linear function has underlying parameters
of shape [`context_dim`, 'num_rewards']. Optionally, squeeze can be applied.
Args:
context_dim: Number of parameters per function.
num_actions: Number of functions returne... | random_linear_multiple_reward_fn_generator | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def compute_optimal_reward(
observation, per_action_reward_fns, enable_noise=False
):
"""Computes the optimal reward.
Args:
observation: a (possibly batched) observation.
per_action_reward_fns: a list of reward functions; one per action. Each
reward function generates a reward when called with an... | Computes the optimal reward.
Args:
observation: a (possibly batched) observation.
per_action_reward_fns: a list of reward functions; one per action. Each
reward function generates a reward when called with an observation.
enable_noise: (bool) whether to add noise to the rewards.
Returns:
The... | compute_optimal_reward | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def tf_compute_optimal_reward(
observation, per_action_reward_fns, enable_noise=False
):
"""TF wrapper around `compute_optimal_reward` to be used in `tf_metrics`."""
compute_optimal_reward_fn = functools.partial(
compute_optimal_reward,
per_action_reward_fns=per_action_reward_fns,
enable_noise... | TF wrapper around `compute_optimal_reward` to be used in `tf_metrics`. | tf_compute_optimal_reward | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def compute_optimal_action(
observation, per_action_reward_fns, enable_noise=False
):
"""Computes the optimal action.
Args:
observation: a (possibly batched) observation.
per_action_reward_fns: a list of reward functions; one per action. Each
reward function generates a reward when called with an... | Computes the optimal action.
Args:
observation: a (possibly batched) observation.
per_action_reward_fns: a list of reward functions; one per action. Each
reward function generates a reward when called with an observation.
enable_noise: (bool) whether to add noise to the rewards.
Returns:
The... | compute_optimal_action | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def tf_compute_optimal_action(
observation,
per_action_reward_fns,
enable_noise=False,
action_dtype=tf.int32,
):
"""TF wrapper around `compute_optimal_action` to be used in `tf_metrics`."""
compute_optimal_action_fn = functools.partial(
compute_optimal_action,
per_action_reward_fns=per_a... | TF wrapper around `compute_optimal_action` to be used in `tf_metrics`. | tf_compute_optimal_action | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def compute_optimal_reward_with_environment_dynamics(
observation, environment_dynamics
):
"""Computes the optimal reward using the environment dynamics.
Args:
observation: a (possibly batched) observation.
environment_dynamics: environment dynamics object (an instance of
`non_stationary_stochast... | Computes the optimal reward using the environment dynamics.
Args:
observation: a (possibly batched) observation.
environment_dynamics: environment dynamics object (an instance of
`non_stationary_stochastic_environment.EnvironmentDynamics`)
Returns:
The optimal reward.
| compute_optimal_reward_with_environment_dynamics | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def compute_optimal_action_with_environment_dynamics(
observation, environment_dynamics
):
"""Computes the optimal action using the environment dynamics.
Args:
observation: a (possibly batched) observation.
environment_dynamics: environment dynamics object (an instance of
`non_stationary_stochast... | Computes the optimal action using the environment dynamics.
Args:
observation: a (possibly batched) observation.
environment_dynamics: environment dynamics object (an instance of
`non_stationary_stochastic_environment.EnvironmentDynamics`)
Returns:
The optimal action.
| compute_optimal_action_with_environment_dynamics | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def compute_optimal_action_with_classification_environment(
observation, environment
):
"""Helper function for gin configurable SuboptimalArms metric."""
del observation
return environment.compute_optimal_action() | Helper function for gin configurable SuboptimalArms metric. | compute_optimal_action_with_classification_environment | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def compute_optimal_reward_with_classification_environment(
observation, environment
):
"""Helper function for gin configurable Regret metric."""
del observation
return environment.compute_optimal_reward() | Helper function for gin configurable Regret metric. | compute_optimal_reward_with_classification_environment | python | tensorflow/agents | tf_agents/bandits/environments/environment_utilities.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/environment_utilities.py | Apache-2.0 |
def _observe(self):
"""Returns the u vectors of a random sample of users."""
sampled_users = random.sample(
range(self._effective_num_users), self._batch_size
)
self._previous_users = self._current_users
self._current_users = sampled_users
batched_observations = self._u_hat[sampled_users... | Returns the u vectors of a random sample of users. | _observe | python | tensorflow/agents | tf_agents/bandits/environments/movielens_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/movielens_py_environment.py | Apache-2.0 |
def _apply_action(self, action):
"""Computes the reward for the input actions."""
rewards = []
for i, j in zip(self._current_users, action):
rewards.append(self._approx_ratings_matrix[i, j])
return np.array(rewards) | Computes the reward for the input actions. | _apply_action | python | tensorflow/agents | tf_agents/bandits/environments/movielens_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/movielens_py_environment.py | Apache-2.0 |
def reward(
self, observation: types.NestedTensor, env_time: types.Int
) -> types.NestedTensor:
"""Reward for the given observation and time step.
Args:
observation: A batch of observations with spec according to
`observation_spec.`
env_time: The scalar int64 tensor of the environme... | Reward for the given observation and time step.
Args:
observation: A batch of observations with spec according to
`observation_spec.`
env_time: The scalar int64 tensor of the environment time step. This is
incremented by the environment after the reward is computed.
Returns:
... | reward | python | tensorflow/agents | tf_agents/bandits/environments/non_stationary_stochastic_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/non_stationary_stochastic_environment.py | Apache-2.0 |
def __init__(self, environment_dynamics: EnvironmentDynamics):
"""Initializes a non-stationary environment with the given dynamics.
Args:
environment_dynamics: An instance of `EnvironmentDynamics` defining how
the environment evolves over time.
"""
self._env_time = tf.compat.v2.Variable(
... | Initializes a non-stationary environment with the given dynamics.
Args:
environment_dynamics: An instance of `EnvironmentDynamics` defining how
the environment evolves over time.
| __init__ | python | tensorflow/agents | tf_agents/bandits/environments/non_stationary_stochastic_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/non_stationary_stochastic_environment.py | Apache-2.0 |
def testObservationAndRewardsVary(self):
"""Ensure that observations and rewards change in consecutive calls."""
dynamics = DummyDynamics()
env = nsse.NonStationaryStochasticEnvironment(dynamics)
self.evaluate(tf.compat.v1.global_variables_initializer())
env_time = env._env_time
observation_sam... | Ensure that observations and rewards change in consecutive calls. | testObservationAndRewardsVary | python | tensorflow/agents | tf_agents/bandits/environments/non_stationary_stochastic_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/non_stationary_stochastic_environment_test.py | Apache-2.0 |
def __init__(
self,
piece_means: np.ndarray,
change_duration_generator: Callable[[], int],
batch_size: Optional[int] = 1,
):
"""Initializes a piecewise stationary Bernoulli Bandit environment.
Args:
piece_means: a matrix (list of lists) with shape (num_pieces, num_arms)
... | Initializes a piecewise stationary Bernoulli Bandit environment.
Args:
piece_means: a matrix (list of lists) with shape (num_pieces, num_arms)
containing floats in [0, 1]. Each list contains the mean rewards for the
num_arms actions of the num_pieces pieces. The list is wrapped around
... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/piecewise_bernoulli_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/piecewise_bernoulli_py_environment.py | Apache-2.0 |
def __init__(
self,
observation_distribution: types.Distribution,
interval_distribution: types.Distribution,
observation_to_reward_distribution: types.Distribution,
additive_reward_distribution: types.Distribution,
):
"""Initialize the parameters of the piecewise dynamics.
Args:... | Initialize the parameters of the piecewise dynamics.
Args:
observation_distribution: A distribution from tfp.distributions with shape
`[batch_size, observation_dim]` Note that the values of `batch_size` and
`observation_dim` are deduced from the distribution.
interval_distribution: A sc... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/piecewise_stochastic_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/piecewise_stochastic_environment.py | Apache-2.0 |
def same_interval_parameters():
"""Returns the parameters of the current piece.
Returns:
The pair of `tf.Tensor` `(observation_to_reward, additive_reward)`.
"""
return [
self._current_observation_to_reward,
self._current_additive_reward,
] | Returns the parameters of the current piece.
Returns:
The pair of `tf.Tensor` `(observation_to_reward, additive_reward)`.
| same_interval_parameters | python | tensorflow/agents | tf_agents/bandits/environments/piecewise_stochastic_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/piecewise_stochastic_environment.py | Apache-2.0 |
def new_interval_parameters():
"""Update and returns the piece parameters.
Returns:
The pair of `tf.Tensor` `(observation_to_reward, additive_reward)`.
"""
tf.compat.v1.assign_add(
self._current_interval,
tf.cast(self._interval_distribution.sample(), dtype=tf.int64),... | Update and returns the piece parameters.
Returns:
The pair of `tf.Tensor` `(observation_to_reward, additive_reward)`.
| new_interval_parameters | python | tensorflow/agents | tf_agents/bandits/environments/piecewise_stochastic_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/piecewise_stochastic_environment.py | Apache-2.0 |
def __init__(
self,
observation_distribution: types.Distribution,
interval_distribution: types.Distribution,
observation_to_reward_distribution: types.Distribution,
additive_reward_distribution: types.Distribution,
):
"""Initialize the environment with the dynamics parameters.
A... | Initialize the environment with the dynamics parameters.
Args:
observation_distribution: A distribution from `tfp.distributions` with
shape `[batch_size, observation_dim]`. Note that the values of
`batch_size` and `observation_dim` are deduced from the distribution.
interval_distributio... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/piecewise_stochastic_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/piecewise_stochastic_environment.py | Apache-2.0 |
def testActionSpec(self, observation_shape, action_shape, batch_size):
"""Ensure that the action spec is set correctly."""
interval = 3
env = get_deterministic_gaussian_non_stationary_environment(
observation_shape, action_shape, batch_size, interval
)
self.evaluate(tf.compat.v1.global_vari... | Ensure that the action spec is set correctly. | testActionSpec | python | tensorflow/agents | tf_agents/bandits/environments/piecewise_stochastic_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/piecewise_stochastic_environment_test.py | Apache-2.0 |
def __init__(
self,
observation_distribution: types.Distribution,
reward_distribution: types.Distribution,
action_spec: Optional[types.TensorSpec] = None,
):
"""Initializes an environment that returns random observations and rewards.
Note that `observation_distribution` and `reward_di... | Initializes an environment that returns random observations and rewards.
Note that `observation_distribution` and `reward_distribution` are expected
to have batch rank 1. That is, `observation_distribution.batch_shape` should
have length exactly 1. `tensorflow_probability.distributions.Independent` is
... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/random_bandit_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/random_bandit_environment.py | Apache-2.0 |
def get_gaussian_random_environment(
observation_shape, action_shape, batch_size
):
"""Returns a RandomBanditEnvironment with Gaussian observation and reward."""
overall_shape = [batch_size] + observation_shape
observation_distribution = tfd.Independent(
tfd.Normal(loc=tf.zeros(overall_shape), scale=tf.... | Returns a RandomBanditEnvironment with Gaussian observation and reward. | get_gaussian_random_environment | python | tensorflow/agents | tf_agents/bandits/environments/random_bandit_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/random_bandit_environment_test.py | Apache-2.0 |
def __init__(
self,
global_sampling_fn: Callable[[], types.Array],
item_sampling_fn: Callable[[], types.Array],
num_items: int,
num_slots: int,
scores_weight_matrix: types.Float,
feedback_model: int = FeedbackModel.CASCADING,
click_model: int = ClickModel.GHOST_ACTIONS,
... | Initializes the environment.
In each round, global context is generated by global_sampling_fn, item
contexts are generated by item_sampling_fn. The score matrix is of shape
`[item_dim, global_dim]`, and plays the role of the weight matrix in the
inner product of item and global features. This inner pro... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/ranking_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/ranking_environment.py | Apache-2.0 |
def _step(self, action):
"""We need to override this function because the reward dtype can be int."""
# TODO(b/199824775): The trajectory module assumes all reward is float32.
# Sort this out with TF-Agents.
output = super(RankingPyEnvironment, self)._step(action)
reward = output.reward
new_rewa... | We need to override this function because the reward dtype can be int. | _step | python | tensorflow/agents | tf_agents/bandits/environments/ranking_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/ranking_environment.py | Apache-2.0 |
def __init__(
self,
global_sampling_fn: Callable[[], types.Array],
item_sampling_fn: Callable[[], types.Array],
relevance_fn: Callable[[types.Array, types.Array], float],
num_items: int,
observation_probs: Sequence[float],
batch_size: int = 1,
name: Optional[Text] = None,... | Initializes an instance of `ExplicitPositionalBiasRankingEnvironment`.
Args:
global_sampling_fn: A function that outputs a random 1d array or list of
ints or floats. This output is the global context. Its shape and type
must be consistent across calls.
item_sampling_fn: A function that ... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/ranking_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/ranking_environment.py | Apache-2.0 |
def _get_relevances(self, global_obs, slotted_items):
"""Returns the relevance of each item in a batched action."""
s_range = range(self._num_slots)
b_range = range(self._batch_size)
relevances = np.array(
[
[
self._relevance_fn(global_obs[i], slotted_items[i, j])
... | Returns the relevance of each item in a batched action. | _get_relevances | python | tensorflow/agents | tf_agents/bandits/environments/ranking_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/ranking_environment.py | Apache-2.0 |
def check_unbatched_time_step_spec(time_step, time_step_spec, batch_size):
"""Checks if time step conforms array spec, even if batched."""
if batch_size is None:
return array_spec.check_arrays_nest(time_step, time_step_spec)
return array_spec.check_arrays_nest(
time_step, array_spec.add_outer_dims_nest... | Checks if time step conforms array spec, even if batched. | check_unbatched_time_step_spec | python | tensorflow/agents | tf_agents/bandits/environments/ranking_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/ranking_environment_test.py | Apache-2.0 |
def __init__(
self,
global_context_sampling_fn: Callable[[], types.Array],
arm_context_sampling_fn: Callable[[], types.Array],
max_num_actions: int,
reward_fn: Callable[[types.Array], Sequence[float]],
num_actions_fn: Optional[Callable[[], int]] = None,
batch_size: Optional[int... | Initializes the environment.
In each round, global context is generated by global_context_sampling_fn,
per-arm contexts are generated by arm_context_sampling_fn. The reward_fn
function takes the concatenation of a global and a per-arm feature, and
outputs a possibly random reward.
In case `num_acti... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/stationary_stochastic_per_arm_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/stationary_stochastic_per_arm_py_environment.py | Apache-2.0 |
def __init__(
self,
context_sampling_fn: Callable[[], np.ndarray],
reward_fns: Sequence[Callable[[np.ndarray], Sequence[float]]],
constraint_fns: Optional[
Sequence[Callable[[np.ndarray], Sequence[float]]]
] = None,
batch_size: Optional[int] = 1,
name: Optional[Text] ... | Initializes a Stationary Stochastic Bandit environment.
In each round, context is generated by context_sampling_fn, this context is
passed through a reward_function for each arm.
Example:
def context_sampling_fn():
return np.random.randint(0, 10, [1, 2]) # 2-dim ints between 0 and 10
... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/stationary_stochastic_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/stationary_stochastic_py_environment.py | Apache-2.0 |
def __init__(
self,
global_context_sampling_fn: Callable[[], types.Array],
arm_context_sampling_fn: Callable[[], types.Array],
num_actions: int,
reward_fn: Callable[[types.Array], Sequence[float]],
batch_size: Optional[int] = 1,
name: Optional[Text] = 'stationary_stochastic_str... | Initializes the environment.
In each round, global context is generated by global_context_sampling_fn,
per-arm contexts are generated by arm_context_sampling_fn.
The two feature generating functions should output a single observation, not
including either the batch_size or the number of actions.
... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/stationary_stochastic_structured_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/stationary_stochastic_structured_py_environment.py | Apache-2.0 |
def __init__(
self,
delta: float,
mu_base: Sequence[float],
std_base: Sequence[float],
mu_high: float,
std_high: float,
batch_size: Optional[int] = None,
name: Optional[Text] = 'wheel',
):
"""Initializes the Wheel Bandit environment.
Args:
delta: float in... | Initializes the Wheel Bandit environment.
Args:
delta: float in `(0, 1)`. Exploration parameter.
mu_base: (vector of float) Mean reward for each action, if the context
norm is below delta. The size of the vector is expected to be 5 (i.e.,
equal to the number of actions.)
std_base:... | __init__ | python | tensorflow/agents | tf_agents/bandits/environments/wheel_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/wheel_py_environment.py | Apache-2.0 |
def _observe(self) -> types.NestedArray:
"""Returns 2-dim samples falling in the unit circle."""
theta = np.random.uniform(0.0, 2.0 * np.pi, (self._batch_size))
r = np.sqrt(np.random.uniform(size=self._batch_size))
batched_observations = np.stack(
[r * np.cos(theta), r * np.sin(theta)], axis=1
... | Returns 2-dim samples falling in the unit circle. | _observe | python | tensorflow/agents | tf_agents/bandits/environments/wheel_py_environment.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/wheel_py_environment.py | Apache-2.0 |
def test_observation_validity(self, batch_size):
"""Tests that the observations fall into the unit circle."""
env = wheel_py_environment.WheelPyEnvironment(
delta=0.5,
mu_base=[1.2, 1.0, 1.0, 1.0, 1.0],
std_base=0.01 * np.ones(5),
mu_high=50.0,
std_high=0.01,
batc... | Tests that the observations fall into the unit circle. | test_observation_validity | python | tensorflow/agents | tf_agents/bandits/environments/wheel_py_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/wheel_py_environment_test.py | Apache-2.0 |
def test_rewards_validity(self, batch_size):
"""Tests that the rewards are valid."""
env = wheel_py_environment.WheelPyEnvironment(
delta=0.5,
mu_base=[1.2, 1.0, 1.0, 1.0, 1.0],
std_base=0.01 * np.ones(5),
mu_high=50.0,
std_high=0.01,
batch_size=batch_size,
)
... | Tests that the rewards are valid. | test_rewards_validity | python | tensorflow/agents | tf_agents/bandits/environments/wheel_py_environment_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/wheel_py_environment_test.py | Apache-2.0 |
def __init__(
self,
baseline_reward_fn: Callable[[types.Tensor], types.Tensor],
name: Optional[Text] = 'RegretMetric',
dtype: float = tf.float32,
):
"""Computes the regret with respect to a baseline.
The regret is computed by computing the difference of the current reward
from the... | Computes the regret with respect to a baseline.
The regret is computed by computing the difference of the current reward
from the baseline action reward. The latter is computed by calling the input
`baseline_reward_fn` function that given a (batched) observation computes
the baseline action reward.
... | __init__ | python | tensorflow/agents | tf_agents/bandits/metrics/tf_metrics.py | https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/metrics/tf_metrics.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.