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 log_hyperparameters(object_dict: Dict[str, Any]) -> None: """Controls which config parts are saved by Lightning loggers. Additionally saves: - Number of model parameters :param object_dict: A dictionary containing the following objects: - `"cfg"`: A DictConfig object containing the mai...
Controls which config parts are saved by Lightning loggers. Additionally saves: - Number of model parameters :param object_dict: A dictionary containing the following objects: - `"cfg"`: A DictConfig object containing the main config. - `"model"`: The Lightning model. - `"train...
log_hyperparameters
python
abus-aikorea/voice-pro
third_party/Matcha-TTS/matcha/utils/logging_utils.py
https://github.com/abus-aikorea/voice-pro/blob/master/third_party/Matcha-TTS/matcha/utils/logging_utils.py
MIT
def get_pylogger(name: str = __name__) -> logging.Logger: """Initializes a multi-GPU-friendly python command line logger. :param name: The name of the logger, defaults to ``__name__``. :return: A logger object. """ logger = logging.getLogger(name) # this ensures all logging levels get marked ...
Initializes a multi-GPU-friendly python command line logger. :param name: The name of the logger, defaults to ``__name__``. :return: A logger object.
get_pylogger
python
abus-aikorea/voice-pro
third_party/Matcha-TTS/matcha/utils/pylogger.py
https://github.com/abus-aikorea/voice-pro/blob/master/third_party/Matcha-TTS/matcha/utils/pylogger.py
MIT
def print_config_tree( cfg: DictConfig, print_order: Sequence[str] = ( "data", "model", "callbacks", "logger", "trainer", "paths", "extras", ), resolve: bool = False, save_to_file: bool = False, ) -> None: """Prints the contents of a DictCo...
Prints the contents of a DictConfig as a tree structure using the Rich library. :param cfg: A DictConfig composed by Hydra. :param print_order: Determines in what order config components are printed. Default is ``("data", "model", "callbacks", "logger", "trainer", "paths", "extras")``. :param resolve: ...
print_config_tree
python
abus-aikorea/voice-pro
third_party/Matcha-TTS/matcha/utils/rich_utils.py
https://github.com/abus-aikorea/voice-pro/blob/master/third_party/Matcha-TTS/matcha/utils/rich_utils.py
MIT
def enforce_tags(cfg: DictConfig, save_to_file: bool = False) -> None: """Prompts user to input tags from command line if no tags are provided in config. :param cfg: A DictConfig composed by Hydra. :param save_to_file: Whether to export tags to the hydra output folder. Default is ``False``. """ if ...
Prompts user to input tags from command line if no tags are provided in config. :param cfg: A DictConfig composed by Hydra. :param save_to_file: Whether to export tags to the hydra output folder. Default is ``False``.
enforce_tags
python
abus-aikorea/voice-pro
third_party/Matcha-TTS/matcha/utils/rich_utils.py
https://github.com/abus-aikorea/voice-pro/blob/master/third_party/Matcha-TTS/matcha/utils/rich_utils.py
MIT
def extras(cfg: DictConfig) -> None: """Applies optional utilities before the task is started. Utilities: - Ignoring python warnings - Setting tags from command line - Rich config printing :param cfg: A DictConfig object containing the config tree. """ # return if no `extra...
Applies optional utilities before the task is started. Utilities: - Ignoring python warnings - Setting tags from command line - Rich config printing :param cfg: A DictConfig object containing the config tree.
extras
python
abus-aikorea/voice-pro
third_party/Matcha-TTS/matcha/utils/utils.py
https://github.com/abus-aikorea/voice-pro/blob/master/third_party/Matcha-TTS/matcha/utils/utils.py
MIT
def task_wrapper(task_func: Callable) -> Callable: """Optional decorator that controls the failure behavior when executing the task function. This wrapper can be used to: - make sure loggers are closed even if the task function raises an exception (prevents multirun failure) - save the exceptio...
Optional decorator that controls the failure behavior when executing the task function. This wrapper can be used to: - make sure loggers are closed even if the task function raises an exception (prevents multirun failure) - save the exception to a `.log` file - mark the run as failed with a...
task_wrapper
python
abus-aikorea/voice-pro
third_party/Matcha-TTS/matcha/utils/utils.py
https://github.com/abus-aikorea/voice-pro/blob/master/third_party/Matcha-TTS/matcha/utils/utils.py
MIT
def get_metric_value(metric_dict: Dict[str, Any], metric_name: str) -> float: """Safely retrieves value of the metric logged in LightningModule. :param metric_dict: A dict containing metric values. :param metric_name: The name of the metric to retrieve. :return: The value of the metric. """ if ...
Safely retrieves value of the metric logged in LightningModule. :param metric_dict: A dict containing metric values. :param metric_name: The name of the metric to retrieve. :return: The value of the metric.
get_metric_value
python
abus-aikorea/voice-pro
third_party/Matcha-TTS/matcha/utils/utils.py
https://github.com/abus-aikorea/voice-pro/blob/master/third_party/Matcha-TTS/matcha/utils/utils.py
MIT
def get_user_data_dir(appname="matcha_tts"): """ Args: appname (str): Name of application Returns: Path: path to user data directory """ MATCHA_HOME = os.environ.get("MATCHA_HOME") if MATCHA_HOME is not None: ans = Path(MATCHA_HOME).expanduser().resolve(strict=False) ...
Args: appname (str): Name of application Returns: Path: path to user data directory
get_user_data_dir
python
abus-aikorea/voice-pro
third_party/Matcha-TTS/matcha/utils/utils.py
https://github.com/abus-aikorea/voice-pro/blob/master/third_party/Matcha-TTS/matcha/utils/utils.py
MIT
def get_args(): """ Description: Parses arguments at command line. Parameters: None Return: args - the arguments parsed """ parser = argparse.ArgumentParser() parser.add_argument('--mode', dest='mode', type=str, default='train') # can be 'train' or 'test' parser.add_argument('--actor_...
Description: Parses arguments at command line. Parameters: None Return: args - the arguments parsed
get_args
python
ericyangyu/PPO-for-Beginners
arguments.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/arguments.py
MIT
def _log_summary(ep_len, ep_ret, ep_num): """ Print to stdout what we've logged so far in the most recent episode. Parameters: None Return: None """ # Round decimal places for more aesthetic logging messages ep_len = str(round(ep_len, 2)) ep_ret = str(round(ep_ret, 2)) # Print logging st...
Print to stdout what we've logged so far in the most recent episode. Parameters: None Return: None
_log_summary
python
ericyangyu/PPO-for-Beginners
eval_policy.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/eval_policy.py
MIT
def rollout(policy, env, render): """ Returns a generator to roll out each episode given a trained policy and environment to test on. Parameters: policy - The trained policy to test env - The environment to evaluate the policy on render - Specifies whether to render or not Return: A generator ...
Returns a generator to roll out each episode given a trained policy and environment to test on. Parameters: policy - The trained policy to test env - The environment to evaluate the policy on render - Specifies whether to render or not Return: A generator object rollout, or iterable, which wil...
rollout
python
ericyangyu/PPO-for-Beginners
eval_policy.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/eval_policy.py
MIT
def eval_policy(policy, env, render=False): """ The main function to evaluate our policy with. It will iterate a generator object "rollout", which will simulate each episode and return the most recent episode's length and return. We can then log it right after. And yes, eval_policy will run forever until you k...
The main function to evaluate our policy with. It will iterate a generator object "rollout", which will simulate each episode and return the most recent episode's length and return. We can then log it right after. And yes, eval_policy will run forever until you kill the process. Parameters: policy - The...
eval_policy
python
ericyangyu/PPO-for-Beginners
eval_policy.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/eval_policy.py
MIT
def train(env, hyperparameters, actor_model, critic_model): """ Trains the model. Parameters: env - the environment to train on hyperparameters - a dict of hyperparameters to use, defined in main actor_model - the actor model to load in if we want to continue training critic_model - the critic model t...
Trains the model. Parameters: env - the environment to train on hyperparameters - a dict of hyperparameters to use, defined in main actor_model - the actor model to load in if we want to continue training critic_model - the critic model to load in if we want to continue training Return: None
train
python
ericyangyu/PPO-for-Beginners
main.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/main.py
MIT
def test(env, actor_model): """ Tests the model. Parameters: env - the environment to test the policy on actor_model - the actor model to load in Return: None """ print(f"Testing {actor_model}", flush=True) # If the actor model is not specified, then exit if actor_model == '': print(f"Didn't sp...
Tests the model. Parameters: env - the environment to test the policy on actor_model - the actor model to load in Return: None
test
python
ericyangyu/PPO-for-Beginners
main.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/main.py
MIT
def main(args): """ The main function to run. Parameters: args - the arguments parsed from command line Return: None """ # NOTE: Here's where you can set hyperparameters for PPO. I don't include them as part of # ArgumentParser because it's too annoying to type them every time at command line. Instead...
The main function to run. Parameters: args - the arguments parsed from command line Return: None
main
python
ericyangyu/PPO-for-Beginners
main.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/main.py
MIT
def __init__(self, in_dim, out_dim): """ Initialize the network and set up the layers. Parameters: in_dim - input dimensions as an int out_dim - output dimensions as an int Return: None """ super(FeedForwardNN, self).__init__() self.layer1 = nn.Linear(in_dim, 64) self.layer2 = nn.Linea...
Initialize the network and set up the layers. Parameters: in_dim - input dimensions as an int out_dim - output dimensions as an int Return: None
__init__
python
ericyangyu/PPO-for-Beginners
network.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/network.py
MIT
def forward(self, obs): """ Runs a forward pass on the neural network. Parameters: obs - observation to pass as input Return: output - the output of our forward pass """ # Convert observation to tensor if it's a numpy array if isinstance(obs, np.ndarray): obs = torch.tensor(obs, dtype=torc...
Runs a forward pass on the neural network. Parameters: obs - observation to pass as input Return: output - the output of our forward pass
forward
python
ericyangyu/PPO-for-Beginners
network.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/network.py
MIT
def __init__(self, policy_class, env, **hyperparameters): """ Initializes the PPO model, including hyperparameters. Parameters: policy_class - the policy class to use for our actor/critic networks. env - the environment to train on. hyperparameters - all extra arguments passed into PPO that should ...
Initializes the PPO model, including hyperparameters. Parameters: policy_class - the policy class to use for our actor/critic networks. env - the environment to train on. hyperparameters - all extra arguments passed into PPO that should be hyperparameters. Returns: None
__init__
python
ericyangyu/PPO-for-Beginners
ppo.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/ppo.py
MIT
def learn(self, total_timesteps): """ Train the actor and critic networks. Here is where the main PPO algorithm resides. Parameters: total_timesteps - the total number of timesteps to train for Return: None """ print(f"Learning... Running {self.max_timesteps_per_episode} timesteps per episode, ...
Train the actor and critic networks. Here is where the main PPO algorithm resides. Parameters: total_timesteps - the total number of timesteps to train for Return: None
learn
python
ericyangyu/PPO-for-Beginners
ppo.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/ppo.py
MIT
def rollout(self): """ Too many transformers references, I'm sorry. This is where we collect the batch of data from simulation. Since this is an on-policy algorithm, we'll need to collect a fresh batch of data each time we iterate the actor/critic networks. Parameters: None Return: batch_obs ...
Too many transformers references, I'm sorry. This is where we collect the batch of data from simulation. Since this is an on-policy algorithm, we'll need to collect a fresh batch of data each time we iterate the actor/critic networks. Parameters: None Return: batch_obs - the observations colle...
rollout
python
ericyangyu/PPO-for-Beginners
ppo.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/ppo.py
MIT
def compute_rtgs(self, batch_rews): """ Compute the Reward-To-Go of each timestep in a batch given the rewards. Parameters: batch_rews - the rewards in a batch, Shape: (number of episodes, number of timesteps per episode) Return: batch_rtgs - the rewards to go, Shape: (number of timesteps in batch)...
Compute the Reward-To-Go of each timestep in a batch given the rewards. Parameters: batch_rews - the rewards in a batch, Shape: (number of episodes, number of timesteps per episode) Return: batch_rtgs - the rewards to go, Shape: (number of timesteps in batch)
compute_rtgs
python
ericyangyu/PPO-for-Beginners
ppo.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/ppo.py
MIT
def get_action(self, obs): """ Queries an action from the actor network, should be called from rollout. Parameters: obs - the observation at the current timestep Return: action - the action to take, as a numpy array log_prob - the log probability of the selected action in the distribution """...
Queries an action from the actor network, should be called from rollout. Parameters: obs - the observation at the current timestep Return: action - the action to take, as a numpy array log_prob - the log probability of the selected action in the distribution
get_action
python
ericyangyu/PPO-for-Beginners
ppo.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/ppo.py
MIT
def evaluate(self, batch_obs, batch_acts): """ Estimate the values of each observation, and the log probs of each action in the most recent batch with the most recent iteration of the actor network. Should be called from learn. Parameters: batch_obs - the observations from the most recently collected...
Estimate the values of each observation, and the log probs of each action in the most recent batch with the most recent iteration of the actor network. Should be called from learn. Parameters: batch_obs - the observations from the most recently collected batch as a tensor. Shape: (number of tim...
evaluate
python
ericyangyu/PPO-for-Beginners
ppo.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/ppo.py
MIT
def _init_hyperparameters(self, hyperparameters): """ Initialize default and custom values for hyperparameters Parameters: hyperparameters - the extra arguments included when creating the PPO model, should only include hyperparameters defined below with custom values. Return: None """ ...
Initialize default and custom values for hyperparameters Parameters: hyperparameters - the extra arguments included when creating the PPO model, should only include hyperparameters defined below with custom values. Return: None
_init_hyperparameters
python
ericyangyu/PPO-for-Beginners
ppo.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/ppo.py
MIT
def _log_summary(self): """ Print to stdout what we've logged so far in the most recent batch. Parameters: None Return: None """ # Calculate logging values. I use a few python shortcuts to calculate each value # without explaining since it's not too important to PPO; feel free to look it over...
Print to stdout what we've logged so far in the most recent batch. Parameters: None Return: None
_log_summary
python
ericyangyu/PPO-for-Beginners
ppo.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/ppo.py
MIT
def get_file_locations(): """ Gets the absolute paths of each data file to graph. Parameters: None Return: paths - a dict with the following structure: { env: { seeds: absolute_seeds_file_path stable_baseli...
Gets the absolute paths of each data file to graph. Parameters: None Return: paths - a dict with the following structure: { env: { seeds: absolute_seeds_file_path stable_baselines: [absolute_file_paths_to_data...
get_file_locations
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def extract_ppo_for_beginners_data(env, filename): """ Extract the total timesteps and average episodic return from the logging data specified to PPO for Beginners. Parameters: env - The environment we're currently graphing. filename - The file containing data. Shoul...
Extract the total timesteps and average episodic return from the logging data specified to PPO for Beginners. Parameters: env - The environment we're currently graphing. filename - The file containing data. Should be "seed_xxx.txt" such that the ...
extract_ppo_for_beginners_data
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def extract_stable_baselines_data(env, filename): """ Extract the total timesteps and average episodic return from the logging data specified to Stable Baselines PPO2. Parameters: env - The environment we're currently graphing. filename - The file containing data. Sh...
Extract the total timesteps and average episodic return from the logging data specified to Stable Baselines PPO2. Parameters: env - The environment we're currently graphing. filename - The file containing data. Should be "seed_xxx.txt" such that the ...
extract_stable_baselines_data
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def calculate_lower_bounds(x_s, y_s): """ Calculate lower bounds of total timesteps and average episodic return per iteration. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of average episodic return per seed. Re...
Calculate lower bounds of total timesteps and average episodic return per iteration. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of average episodic return per seed. Return: Lower bounds of both x_s a...
calculate_lower_bounds
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def calculate_upper_bounds(x_s, y_s): """ Calculate upper bounds of total timesteps and average episodic return per iteration. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of average episodic return per seed. Re...
Calculate upper bounds of total timesteps and average episodic return per iteration. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of average episodic return per seed. Return: Upper bounds of both x_s a...
calculate_upper_bounds
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def calculate_means(x_s, y_s): """ Calculate mean of each total timestep and average episodic return over all trials at each iteration. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of average episodic return per seed ...
Calculate mean of each total timestep and average episodic return over all trials at each iteration. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of average episodic return per seed Return: Means of x_...
calculate_means
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def clip_data(x_s, y_s): """ In the case that there are different number of iterations across learning trials, clip all trials to the length of the shortest trial. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of ...
In the case that there are different number of iterations across learning trials, clip all trials to the length of the shortest trial. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of average episodic return per seed...
clip_data
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def extract_data(paths): """ Extracts data from all the files, and returns a generator object extract_data to iterably return data for each environment. Number of iterations should equal number of environments in graph_data. Parameters: paths - Contains the paths to eac...
Extracts data from all the files, and returns a generator object extract_data to iterably return data for each environment. Number of iterations should equal number of environments in graph_data. Parameters: paths - Contains the paths to each data file. Check function desc...
extract_data
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def graph_data(paths): """ Graphs the data with matplotlib. Will display on screen for user to screenshot. Parameters: paths - Contains the paths to each data file. Check function description of get_file_locations() to see how paths is structured. Return: ...
Graphs the data with matplotlib. Will display on screen for user to screenshot. Parameters: paths - Contains the paths to each data file. Check function description of get_file_locations() to see how paths is structured. Return: None
graph_data
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def main(): """ Main function to get file locations and graph the data. Parameters: None Return: None """ # Extract absolute file paths paths = get_file_locations() # Graph the data from the file paths extracted graph_data(paths)
Main function to get file locations and graph the data. Parameters: None Return: None
main
python
ericyangyu/PPO-for-Beginners
graph_code/make_graph.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/make_graph.py
MIT
def train_stable_baselines(args): """ Trains with PPO2 on specified environment. Parameters: args - the arguments defined in main. Return: None """ # Import stable baselines from stable_baselines import PPO2 from stable_baselines.common.callbacks import CheckpointCallback from stable_baselines.commo...
Trains with PPO2 on specified environment. Parameters: args - the arguments defined in main. Return: None
train_stable_baselines
python
ericyangyu/PPO-for-Beginners
graph_code/run.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/run.py
MIT
def train_ppo_for_beginners(args): """ Trains with PPO for Beginners on specified environment. Parameters: args - the arguments defined in main. Return: None """ # Import ppo for beginners from ppo_for_beginners.ppo import PPO from ppo_for_beginners.network import FeedForwardNN # Store hyperparamet...
Trains with PPO for Beginners on specified environment. Parameters: args - the arguments defined in main. Return: None
train_ppo_for_beginners
python
ericyangyu/PPO-for-Beginners
graph_code/run.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/run.py
MIT
def main(args): """ An intermediate function that will call either PPO2 learn or PPO for Beginners learn. Parameters: args - the arguments defined below Return: None """ if args.code == 'stable_baselines_ppo2': train_stable_baselines(args) elif args.code == 'ppo_for_beginners': train_ppo_for_begin...
An intermediate function that will call either PPO2 learn or PPO for Beginners learn. Parameters: args - the arguments defined below Return: None
main
python
ericyangyu/PPO-for-Beginners
graph_code/run.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/run.py
MIT
def evaluate(self, batch_obs, batch_acts, batch_rtgs): """ Estimate the values of each observation, and the log probs of each action in the most recent batch with the most recent iteration of the actor network. Should be called from learn. Parameters: batch_obs - the observations from the most recent...
Estimate the values of each observation, and the log probs of each action in the most recent batch with the most recent iteration of the actor network. Should be called from learn. Parameters: batch_obs - the observations from the most recently collected batch as a tensor. Shape: (number of tim...
evaluate
python
ericyangyu/PPO-for-Beginners
graph_code/ppo_for_beginners/ppo.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/graph_code/ppo_for_beginners/ppo.py
MIT
def __init__(self, policy_class, env, **hyperparameters): """ Initializes the PPO model, including hyperparameters. Parameters: policy_class - the policy class to use for our actor/critic networks. env - the environment to train on. hyperp...
Initializes the PPO model, including hyperparameters. Parameters: policy_class - the policy class to use for our actor/critic networks. env - the environment to train on. hyperparameters - all extra arguments passed into PPO that should be hyperp...
__init__
python
ericyangyu/PPO-for-Beginners
part4/ppo_for_beginners/ppo_optimized.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/part4/ppo_for_beginners/ppo_optimized.py
MIT
def learn(self, total_timesteps): """ Train the actor and critic networks. Here is where the main PPO algorithm resides. Parameters: total_timesteps - the total number of timesteps to train for Return: None """ print(f"Learnin...
Train the actor and critic networks. Here is where the main PPO algorithm resides. Parameters: total_timesteps - the total number of timesteps to train for Return: None
learn
python
ericyangyu/PPO-for-Beginners
part4/ppo_for_beginners/ppo_optimized.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/part4/ppo_for_beginners/ppo_optimized.py
MIT
def get_action(self, obs): """ Queries an action from the actor network, should be called from rollout. Parameters: obs - the observation at the current timestep Return: action - the action to take, as a numpy array log_prob -...
Queries an action from the actor network, should be called from rollout. Parameters: obs - the observation at the current timestep Return: action - the action to take, as a numpy array log_prob - the log probability of the selected a...
get_action
python
ericyangyu/PPO-for-Beginners
part4/ppo_for_beginners/ppo_optimized.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/part4/ppo_for_beginners/ppo_optimized.py
MIT
def evaluate(self, batch_obs, batch_acts): """ Estimate the values of each observation, and the log probs of each action in the most recent batch with the most recent iteration of the actor network. Should be called from learn. Parameters: batch_o...
Estimate the values of each observation, and the log probs of each action in the most recent batch with the most recent iteration of the actor network. Should be called from learn. Parameters: batch_obs - the observations from the most recently collected...
evaluate
python
ericyangyu/PPO-for-Beginners
part4/ppo_for_beginners/ppo_optimized.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/part4/ppo_for_beginners/ppo_optimized.py
MIT
def _init_hyperparameters(self, hyperparameters): """ Initialize default and custom values for hyperparameters Parameters: hyperparameters - the extra arguments included when creating the PPO model, should only include hyperparameters ...
Initialize default and custom values for hyperparameters Parameters: hyperparameters - the extra arguments included when creating the PPO model, should only include hyperparameters defined below with custom values. Return: ...
_init_hyperparameters
python
ericyangyu/PPO-for-Beginners
part4/ppo_for_beginners/ppo_optimized.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/part4/ppo_for_beginners/ppo_optimized.py
MIT
def _log_summary(self): """ Print to stdout what we've logged so far in the most recent batch. Parameters: None Return: None """ # Calculate logging values. I use a few python shortcuts to calculate each value # withou...
Print to stdout what we've logged so far in the most recent batch. Parameters: None Return: None
_log_summary
python
ericyangyu/PPO-for-Beginners
part4/ppo_for_beginners/ppo_optimized.py
https://github.com/ericyangyu/PPO-for-Beginners/blob/master/part4/ppo_for_beginners/ppo_optimized.py
MIT
def _validate_args( object_height: float, shadow_length: float, date_time: datetime, ) -> None: """ Validate the text search CLI arguments, raises an error if the arguments are invalid. """ if not object_height: raise ValueError("Object height cannot be empty") if not shadow_leng...
Validate the text search CLI arguments, raises an error if the arguments are invalid.
_validate_args
python
bellingcat/ShadowFinder
src/shadowfinder/cli.py
https://github.com/bellingcat/ShadowFinder/blob/master/src/shadowfinder/cli.py
MIT
def find( object_height: float, shadow_length: float, date: str, time: str, time_format: str = "utc", grid: str = "timezone_grid.json", ) -> None: """ Find the shadow length of an object given its height and the date and time. :param object_hei...
Find the shadow length of an object given its height and the date and time. :param object_height: Height of the object in arbitrary units :param shadow_length: Length of the shadow in arbitrary units :param date: Date in the format YYYY-MM-DD :param time: UTC Time in the format ...
find
python
bellingcat/ShadowFinder
src/shadowfinder/cli.py
https://github.com/bellingcat/ShadowFinder/blob/master/src/shadowfinder/cli.py
MIT
def find_sun( sun_altitude_angle: float, date: str, time: str, time_format: str = "utc", grid: str = "timezene_grid.json", ) -> None: """ Locate a shadow based on the solar altitude angle and the date and time. :param sun_altitude_angle: Sun altitude a...
Locate a shadow based on the solar altitude angle and the date and time. :param sun_altitude_angle: Sun altitude angle in degrees :param date: Date in the format YYYY-MM-DD :param time: UTC Time in the format HH:MM:SS
find_sun
python
bellingcat/ShadowFinder
src/shadowfinder/cli.py
https://github.com/bellingcat/ShadowFinder/blob/master/src/shadowfinder/cli.py
MIT
def generate_timezone_grid( grid: str = "timezone_grid.json", ) -> None: """ Generate a timezone grid file. :param grid: File path to save the timezone grid. """ shadow_finder = ShadowFinder() shadow_finder.generate_timezone_grid() shadow_finder.save_...
Generate a timezone grid file. :param grid: File path to save the timezone grid.
generate_timezone_grid
python
bellingcat/ShadowFinder
src/shadowfinder/cli.py
https://github.com/bellingcat/ShadowFinder/blob/master/src/shadowfinder/cli.py
MIT
def test_executable_without_args(): """Tests that running shadowfinder without any arguments returns the CLI's help string and 0 exit code.""" # GIVEN expected = """ NAME shadowfinder SYNOPSIS shadowfinder COMMAND COMMANDS COMMAND is one of the following: find Find the shadow leng...
Tests that running shadowfinder without any arguments returns the CLI's help string and 0 exit code.
test_executable_without_args
python
bellingcat/ShadowFinder
tests/test_executable.py
https://github.com/bellingcat/ShadowFinder/blob/master/tests/test_executable.py
MIT
def test_creation_with_valid_arguments_should_pass(): """Baseline test to assert that we can create an instance of ShadowFinder with only object height, shadow length, and a datetime object.""" # GIVEN object_height = 6 shadow_length = 3.2 date_time = datetime.now() # WHEN / THEN Shadow...
Baseline test to assert that we can create an instance of ShadowFinder with only object height, shadow length, and a datetime object.
test_creation_with_valid_arguments_should_pass
python
bellingcat/ShadowFinder
tests/test_shadowfinder.py
https://github.com/bellingcat/ShadowFinder/blob/master/tests/test_shadowfinder.py
MIT
def test_huber_loss(self): """Test of huber loss huber_loss() allows two types of inputs: - `y_target` and `y_pred` - `diff` """ # [1, 1] -> [0.5, 0.5] loss = huber_loss(np.array([1., 1.]), delta=1.) np.testing.assert_array_equal( np.array([0.5...
Test of huber loss huber_loss() allows two types of inputs: - `y_target` and `y_pred` - `diff`
test_huber_loss
python
keiohta/tf2rl
tests/misc/test_huber_loss.py
https://github.com/keiohta/tf2rl/blob/master/tests/misc/test_huber_loss.py
MIT
def layer_test(layer_cls, kwargs=None, input_shape=None, input_dtype=None, input_data=None, expected_output=None, expected_output_dtype=None, custom_objects=None): """Test routine for a layer with a single input and single output. Arguments: layer_cls: Layer class object. ...
Test routine for a layer with a single input and single output. Arguments: layer_cls: Layer class object. kwargs: Optional dictionary of keyword arguments for instantiating the layer. input_shape: Input shape tuple. input_dtype: Data type of the input data. input_data: Numpy a...
layer_test
python
keiohta/tf2rl
tests/networks/utils.py
https://github.com/keiohta/tf2rl/blob/master/tests/networks/utils.py
MIT
def explorer(global_rb, queue, trained_steps, is_training_done, lock, env_fn, policy_fn, set_weights_fn, noise_level, n_env=64, n_thread=4, buffer_size=1024, episode_max_steps=1000, gpu=0): """Collect transitions and store them to prioritized replay buffer. Args: global_rb: mu...
Collect transitions and store them to prioritized replay buffer. Args: global_rb: multiprocessing.managers.AutoProxy[PrioritizedReplayBuffer] Prioritized replay buffer sharing with multiple explorers and only one learner. This object is shared over processes, so it must be locked wh...
explorer
python
keiohta/tf2rl
tf2rl/algos/apex.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/apex.py
MIT
def learner(global_rb, trained_steps, is_training_done, lock, env, policy_fn, get_weights_fn, n_training, update_freq, evaluation_freq, gpu, queues): """Update network weights using samples collected by explorers. Args: global_rb: multiprocessing.managers.AutoProxy[PrioritizedRe...
Update network weights using samples collected by explorers. Args: global_rb: multiprocessing.managers.AutoProxy[PrioritizedReplayBuffer] Prioritized replay buffer sharing with multiple explorers and only one learner. This object is shared over processes, so it must be locked when t...
learner
python
keiohta/tf2rl
tf2rl/algos/apex.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/apex.py
MIT
def evaluator(is_training_done, env, policy_fn, set_weights_fn, queue, gpu, save_model_interval=int(1e6), n_evaluation=10, episode_max_steps=1000, show_test_progress=False): """Evaluate trained network weights periodically. Args: is_training_done: multiprocessing.Event ...
Evaluate trained network weights periodically. Args: is_training_done: multiprocessing.Event multiprocessing.Event object to share the status of training. env: Open-AI gym compatible environment Environment object. policy_fn: function Method object to gen...
evaluator
python
keiohta/tf2rl
tf2rl/algos/apex.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/apex.py
MIT
def __init__(self, eta=0.05, name="BiResDDPG", **kwargs): """ Initialize BiResDDPG agent Args: eta (float): Gradients mixing factor. name (str): Name of agent. The default is ``"BiResDDPG"``. state_shape (iterable of int): action_dim (int): ...
Initialize BiResDDPG agent Args: eta (float): Gradients mixing factor. name (str): Name of agent. The default is ``"BiResDDPG"``. state_shape (iterable of int): action_dim (int): max_action (float): Size of maximum action. (``-max_action`` <=...
__init__
python
keiohta/tf2rl
tf2rl/algos/bi_res_ddpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/bi_res_ddpg.py
MIT
def compute_td_error(self, states, actions, next_states, rewards, dones): """ Compute TD error Args: states actions next_states rewars dones Returns: np.ndarray: Sum of two TD errors. """ td_error1,...
Compute TD error Args: states actions next_states rewars dones Returns: np.ndarray: Sum of two TD errors.
compute_td_error
python
keiohta/tf2rl
tf2rl/algos/bi_res_ddpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/bi_res_ddpg.py
MIT
def get_argument(parser=None): """ Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser """ parser = DDPG.get_argument(parser) ...
Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser
get_argument
python
keiohta/tf2rl
tf2rl/algos/bi_res_ddpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/bi_res_ddpg.py
MIT
def __init__( self, state_shape, action_dim, q_func=None, name="DQN", lr=0.001, adam_eps=1e-07, units=(32, 32), epsilon=0.1, epsilon_min=None, epsilon_decay_step=int(1e6), n_wa...
Initialize Categorical DQN Args: state_shape (iterable of int): Observation space shape action_dim (int): Dimension of discrete action q_function (QFunc): Custom Q function class. If ``None`` (default), Q function is constructed with ``QFunc``. name (str...
__init__
python
keiohta/tf2rl
tf2rl/algos/categorical_dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/categorical_dqn.py
MIT
def get_action(self, state, test=False, tensor=False): """ Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. tensor (bool): When ``True``, return type is ``tf.Tensor`` Returns: ...
Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. tensor (bool): When ``True``, return type is ``tf.Tensor`` Returns: tf.Tensor or np.ndarray or float: Selected action
get_action
python
keiohta/tf2rl
tf2rl/algos/categorical_dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/categorical_dqn.py
MIT
def train(self, states, actions, next_states, rewards, done, weights=None): """ Train DQN Args: states actions next_states rewards done weights (optional): Weights for importance sampling """ if weights is N...
Train DQN Args: states actions next_states rewards done weights (optional): Weights for importance sampling
train
python
keiohta/tf2rl
tf2rl/algos/categorical_dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/categorical_dqn.py
MIT
def compute_td_error(self, states, actions, next_states, rewards, dones): """ Compute TD error Args: states actions next_states rewars dones Returns tf.Tensor: TD error """ # TODO: fix this ugly con...
Compute TD error Args: states actions next_states rewars dones Returns tf.Tensor: TD error
compute_td_error
python
keiohta/tf2rl
tf2rl/algos/categorical_dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/categorical_dqn.py
MIT
def _compute_td_error_body(self, states, actions, next_states, rewards, dones): """ Args: states: actions: next_states: rewards: Shape should be (batch_size, 1) dones: Shape should be (batch_size, 1) Ret...
Args: states: actions: next_states: rewards: Shape should be (batch_size, 1) dones: Shape should be (batch_size, 1) Returns:
_compute_td_error_body
python
keiohta/tf2rl
tf2rl/algos/categorical_dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/categorical_dqn.py
MIT
def __init__(self, *args, **kwargs): """ Initialize CURL Args: action_dim (int): obs_shape: (iterable of int): The default is ``(84, 84, 9)`` n_conv_layers (int): Number of convolutional layers at encoder. The default is ``4`...
Initialize CURL Args: action_dim (int): obs_shape: (iterable of int): The default is ``(84, 84, 9)`` n_conv_layers (int): Number of convolutional layers at encoder. The default is ``4`` n_conv_filters (int): Number of filters in convolutional layers. The...
__init__
python
keiohta/tf2rl
tf2rl/algos/curl_sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/curl_sac.py
MIT
def train(self, states, actions, next_states, rewards, dones, weights=None): """ Train CURL Args: states actions next_states rewards done weights (optional): Weights for importance sampling """ if weights is...
Train CURL Args: states actions next_states rewards done weights (optional): Weights for importance sampling
train
python
keiohta/tf2rl
tf2rl/algos/curl_sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/curl_sac.py
MIT
def __init__( self, state_shape, action_dim, name="DDPG", max_action=1., lr_actor=0.001, lr_critic=0.001, actor_units=(400, 300), critic_units=(400, 300), sigma=0.1, tau=0.005, ...
Initialize DDPG agent Args: state_shape (iterable of int): action_dim (int): name (str): Name of agent. The default is ``"DDPG"``. max_action (float): Size of maximum action. (``-max_action`` <= action <= ``max_action``). The degault is ``1``. ...
__init__
python
keiohta/tf2rl
tf2rl/algos/ddpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/ddpg.py
MIT
def train(self, states, actions, next_states, rewards, done, weights=None): """ Train DDPG Args: states actions next_states rewards done weights (optional): Weights for importance sampling """ if weights is ...
Train DDPG Args: states actions next_states rewards done weights (optional): Weights for importance sampling
train
python
keiohta/tf2rl
tf2rl/algos/ddpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/ddpg.py
MIT
def __init__( self, state_shape, action_dim, q_func=None, name="DQN", lr=0.001, adam_eps=1e-07, units=(32, 32), epsilon=0.1, epsilon_min=None, epsilon_decay_step=int(1e6), n_wa...
Initialize DQN agent Args: state_shape (iterable of int): Observation space shape action_dim (int): Dimension of discrete action q_function (QFunc): Custom Q function class. If ``None`` (default), Q function is constructed with ``QFunc``. name (str): Nam...
__init__
python
keiohta/tf2rl
tf2rl/algos/dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/dqn.py
MIT
def __init__( self, state_shape, units=(32, 32), lr=0.001, enable_sn=False, name="GAIfO", **kwargs): """ Initialize GAIfO Args: state_shape (iterable of int): action_dim (int): ...
Initialize GAIfO Args: state_shape (iterable of int): action_dim (int): units (iterable of int): The default is ``(32, 32)`` lr (float): Learning rate. The default is ``0.001`` enable_sn (bool): Whether enable Spectral Normalization. The defa...
__init__
python
keiohta/tf2rl
tf2rl/algos/gaifo.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/gaifo.py
MIT
def inference(self, states, actions, next_states): """ Infer Reward with GAIfO Args: states actions next_states Returns: tf.Tensor: Reward """ assert states.shape == next_states.shape if states.ndim == 1: ...
Infer Reward with GAIfO Args: states actions next_states Returns: tf.Tensor: Reward
inference
python
keiohta/tf2rl
tf2rl/algos/gaifo.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/gaifo.py
MIT
def __init__( self, state_shape, action_dim, units=[32, 32], lr=0.001, enable_sn=False, name="GAIL", **kwargs): """ Initialize GAIL Args: state_shape (iterable of int): action...
Initialize GAIL Args: state_shape (iterable of int): action_dim (int): units (iterable of int): The default is ``[32, 32]`` lr (float): Learning rate. The default is ``0.001`` enable_sn (bool): Whether enable Spectral Normalization. The defai...
__init__
python
keiohta/tf2rl
tf2rl/algos/gail.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/gail.py
MIT
def inference(self, states, actions, next_states): """ Infer Reward with GAIL Args: states actions next_states Returns: tf.Tensor: Reward """ if states.ndim == actions.ndim == 1: states = np.expand_dims(states,...
Infer Reward with GAIL Args: states actions next_states Returns: tf.Tensor: Reward
inference
python
keiohta/tf2rl
tf2rl/algos/gail.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/gail.py
MIT
def __init__( self, clip=True, clip_ratio=0.2, name="PPO", **kwargs): """ Initialize PPO Args: clip (bool): Whether clip or not. The default is ``True``. clip_ratio (float): Probability ratio is clipped between ...
Initialize PPO Args: clip (bool): Whether clip or not. The default is ``True``. clip_ratio (float): Probability ratio is clipped between ``1-clip_ratio`` and ``1+clip_ratio``. name (str): Name of agent. The default is ``"PPO"``. state_shape (iterable of ...
__init__
python
keiohta/tf2rl
tf2rl/algos/ppo.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/ppo.py
MIT
def train(self, states, actions, advantages, logp_olds, returns): """ Train PPO Args: states actions advantages logp_olds returns """ # Train actor and critic if self.actor_critic is not None: actor_...
Train PPO Args: states actions advantages logp_olds returns
train
python
keiohta/tf2rl
tf2rl/algos/ppo.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/ppo.py
MIT
def __init__( self, state_shape, action_dim, name="SAC", max_action=1., lr=3e-4, lr_alpha=3e-4, actor_units=(256, 256), critic_units=(256, 256), tau=5e-3, alpha=.2, auto_alpha=...
Initialize SAC Args: state_shape (iterable of int): action_dim (int): name (str): Name of network. The default is ``"SAC"`` max_action (float): lr (float): Learning rate. The default is ``3e-4``. lr_alpha (alpha): Learning rate fo...
__init__
python
keiohta/tf2rl
tf2rl/algos/sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac.py
MIT
def get_action(self, state, test=False): """ Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: tf.Tensor or float: Selected action """ assert isinstance(state,...
Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: tf.Tensor or float: Selected action
get_action
python
keiohta/tf2rl
tf2rl/algos/sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac.py
MIT
def train(self, states, actions, next_states, rewards, dones, weights=None): """ Train SAC Args: states actions next_states rewards done weights (optional): Weights for importance sampling """ if weights is ...
Train SAC Args: states actions next_states rewards done weights (optional): Weights for importance sampling
train
python
keiohta/tf2rl
tf2rl/algos/sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac.py
MIT
def compute_td_error(self, states, actions, next_states, rewards, dones): """ Compute TD error Args: states actions next_states rewars dones Returns np.ndarray: TD error """ if isinstance(actions, t...
Compute TD error Args: states actions next_states rewars dones Returns np.ndarray: TD error
compute_td_error
python
keiohta/tf2rl
tf2rl/algos/sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac.py
MIT
def __init__(self, action_dim, obs_shape=(84, 84, 9), n_conv_layers=4, n_conv_filters=32, feature_dim=50, tau_encoder=0.05, tau_critic=0.01, auto_alpha=True, lr_sac=1e...
Initialize SAC+AE Args: action_dim (int): obs_shape: (iterable of int): The default is ``(84, 84, 9)`` n_conv_layers (int): Number of convolutional layers at encoder. The default is ``4`` n_conv_filters (int): Number of filters in convolutional layers. T...
__init__
python
keiohta/tf2rl
tf2rl/algos/sac_ae.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac_ae.py
MIT
def get_action(self, state, test=False): """ Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: tf.Tensor or float: Selected action Notes: When the input i...
Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: tf.Tensor or float: Selected action Notes: When the input image have different size, cropped image is used ...
get_action
python
keiohta/tf2rl
tf2rl/algos/sac_ae.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac_ae.py
MIT
def train(self, states, actions, next_states, rewards, dones, weights=None): """ Train SAC+AE Args: states actions next_states rewards done weights (optional): Weights for importance sampling """ if weights ...
Train SAC+AE Args: states actions next_states rewards done weights (optional): Weights for importance sampling
train
python
keiohta/tf2rl
tf2rl/algos/sac_ae.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac_ae.py
MIT
def __init__( self, state_shape, action_dim, name="TD3", actor_update_freq=2, policy_noise=0.2, noise_clip=0.5, critic_units=(400, 300), **kwargs): """ Initialize TD3 Args: sh...
Initialize TD3 Args: shate_shape (iterable of ints): Observation state shape action_dim (int): Action dimension name (str): Network name. The default is ``"TD3"``. actor_update_freq (int): Number of critic updates per one actor upate. policy_...
__init__
python
keiohta/tf2rl
tf2rl/algos/td3.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/td3.py
MIT
def __init__( self, state_shape, action_dim, units=(32, 32), n_latent_unit=32, lr=5e-5, kl_target=0.5, reg_param=0., enable_sn=False, enable_gp=False, name="VAIL", **kwargs): ...
Initialize VAIL Args: state_shape (iterable of int): action_dim (int): units (iterable of int): The default is ``(32, 32)`` lr (float): Learning rate. The default is ``5e-5`` kl_target (float): The default is ``0.5`` reg_param (fl...
__init__
python
keiohta/tf2rl
tf2rl/algos/vail.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vail.py
MIT
def _compute_kl_latent(self, means, log_stds): r""" Compute KL divergence of latent spaces over standard Normal distribution to compute loss in eq.5. The formulation of KL divergence between two normal distributions is as follows: ln(\sigma_2 / \sigma_1) + {(\mu_1 - \mu_2)^2...
Compute KL divergence of latent spaces over standard Normal distribution to compute loss in eq.5. The formulation of KL divergence between two normal distributions is as follows: ln(\sigma_2 / \sigma_1) + {(\mu_1 - \mu_2)^2 + \sigma_1^2 - \sigma_2^2} / (2 * \sigma_2^2) Sinc...
_compute_kl_latent
python
keiohta/tf2rl
tf2rl/algos/vail.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vail.py
MIT
def __init__( self, state_shape, action_dim, is_discrete, actor=None, critic=None, actor_critic=None, max_action=1., actor_units=(256, 256), critic_units=(256, 256), lr_actor=1e-3, ...
Initialize VPG Args: state_shape (iterable of int): action_dim (int): is_discrete (bool): actor: critic: actor_critic: max_action (float): maximum action size. actor_units (iterable of int): Numbers of unit...
__init__
python
keiohta/tf2rl
tf2rl/algos/vpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vpg.py
MIT
def get_action(self, state, test=False): """ Get action and probability Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: np.ndarray or float: Selected action np.ndarray or f...
Get action and probability Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: np.ndarray or float: Selected action np.ndarray or float: Log(p)
get_action
python
keiohta/tf2rl
tf2rl/algos/vpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vpg.py
MIT
def get_action_and_val(self, state, test=False): """ Get action, probability, and critic value Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: np.ndarray: Selected action n...
Get action, probability, and critic value Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: np.ndarray: Selected action np.ndarray: Log(p) np.ndarray: Critic value ...
get_action_and_val
python
keiohta/tf2rl
tf2rl/algos/vpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vpg.py
MIT
def train(self, states, actions, advantages, logp_olds, returns): """ Train VPG Args: states actions advantages logp_olds returns """ # Train actor and critic actor_loss, logp_news = self._train_actor_body( ...
Train VPG Args: states actions advantages logp_olds returns
train
python
keiohta/tf2rl
tf2rl/algos/vpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vpg.py
MIT
def __init__(self, env, noop_max=30): """ Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0. """ gym.Wrapper.__init__(self, env) self.noop_max = noop_max self.override_num_noops = None self.noop_action = 0 ...
Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def reset(self, **kwargs): """ Do no-op action for a number of steps in [1, noop_max]. """ self.env.reset(**kwargs) if self.override_num_noops is not None: noops = self.override_num_noops else: noops = self.unwrapped.np_random.randint( ...
Do no-op action for a number of steps in [1, noop_max].
reset
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env): """ Take action on reset for environments that are fixed until firing. """ gym.Wrapper.__init__(self, env) assert env.unwrapped.get_action_meanings()[1] == 'FIRE' assert len(env.unwrapped.get_action_meanings()) >= 3
Take action on reset for environments that are fixed until firing.
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env): """ Make end-of-life == end-of-episode, but only reset on true game over. Done by DeepMind for the DQN and co. since it helps value estimation. """ gym.Wrapper.__init__(self, env) self.lives = 0 self.was_real_done = True
Make end-of-life == end-of-episode, but only reset on true game over. Done by DeepMind for the DQN and co. since it helps value estimation.
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def reset(self, **kwargs): """ Reset only when lives are exhausted. This way all states are still reachable even though lives are episodic, and the learner need not know about any of this behind-the-scenes. """ if self.was_real_done: obs = self.env.reset(**kwa...
Reset only when lives are exhausted. This way all states are still reachable even though lives are episodic, and the learner need not know about any of this behind-the-scenes.
reset
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env, skip=4): """ Return only every `skip`-th frame """ gym.Wrapper.__init__(self, env) # most recent raw observations (for max pooling across time steps) self._obs_buffer = np.zeros( (2,)+env.observation_space.shape, dtype=np.uint8) ...
Return only every `skip`-th frame
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def step(self, action): """ Repeat action, sum reward, and max over last observations. """ total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_...
Repeat action, sum reward, and max over last observations.
step
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env, width=84, height=84, grayscale=True, dict_space_key=None): """ Warp frames to 84x84 as done in the Nature paper and later work. If the environment uses dictionary observations, `dict_space_key` can be specified which indicates which observation should be warped. ...
Warp frames to 84x84 as done in the Nature paper and later work. If the environment uses dictionary observations, `dict_space_key` can be specified which indicates which observation should be warped.
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env, k): """ Stack k last frames. Returns lazy array, which is much more memory efficient. See also baselines.common.atari_wrappers.LazyFrames """ gym.Wrapper.__init__(self, env) self.k = k self.frames = deque([], maxlen=k) shp =...
Stack k last frames. Returns lazy array, which is much more memory efficient. See also baselines.common.atari_wrappers.LazyFrames
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, frames): """ This object ensures that common frames between the observations are only stored once. It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay buffers. This object should only be converted to numpy array before being p...
This object ensures that common frames between the observations are only stored once. It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay buffers. This object should only be converted to numpy array before being passed to the model. You'd not b...
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False): """ Configure environment for DeepMind-style Atari. """ if episode_life: env = EpisodicLifeEnv(env) if 'FIRE' in env.unwrapped.get_action_meanings(): env = FireResetEnv(env) env = WarpFr...
Configure environment for DeepMind-style Atari.
wrap_deepmind
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT