Logo elodees  elodees

A caring AI for a better world













Only alphabetic characters accented or not as well as the space are accepted

Logo IA




Hierarchical Actor Critic (HAC)





No account yet ?

Sign up to access all content




The new hierarchical reinforcement learning approach called Hierarchical Actor-Critic (HAC) aims to make learning tasks more efficient with rare binary rewards that allow agents to learn to decompose tasks from scratch.

The technique uses a set of critical actor networks that learn to break down tasks into a hierarchy of sub-goals.



train.py



Tested in Anaconda and Python 3.7

import torch
import gym
import asset
import numpy as np
from HAC import HAC
 
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
def train():
    #################### Hyperparameters ####################
    env_name = "MountainCarContinuous-h-v1"
    save_episode = 10               # keep saving every n episodes
    max_episodes = 1000             # max num of training episodes
    random_seed = 0
    render = False
 
    env = gym.make(env_name)
    state_dim = env.observation_space.shape[0]
    action_dim = env.action_space.shape[0]
 
    """
     Actions (both primitive and subgoal) are implemented as follows:
       action = ( network output (Tanh) * bounds ) + offset
       clip_high and clip_low bound the exploration noise
    """
 
    # primitive action bounds and offset
    action_bounds = env.action_space.high[0]
    action_offset = np.array([0.0])
    action_offset = torch.FloatTensor(action_offset.reshape(1, -1)).to(device)
    action_clip_low = np.array([-1.0 * action_bounds])
    action_clip_high = np.array([action_bounds])
 
    # state bounds and offset
    state_bounds_np = np.array([0.9, 0.07])
    state_bounds = torch.FloatTensor(state_bounds_np.reshape(1, -1)).to(device)
    state_offset =  np.array([-0.3, 0.0])
    state_offset = torch.FloatTensor(state_offset.reshape(1, -1)).to(device)
    state_clip_low = np.array([-1.2, -0.07])
    state_clip_high = np.array([0.6, 0.07])
 
    # exploration noise std for primitive action and subgoals
    exploration_action_noise = np.array([0.1])        
    exploration_state_noise = np.array([0.02, 0.01]) 
 
    goal_state = np.array([0.48, 0.04])        # final goal state to be achived
    threshold = np.array([0.01, 0.02])         # threshold value to check if goal state is achieved
 
    # HAC parameters:
    k_level = 2                 # num of levels in hierarchy
    H = 20                      # time horizon to achieve subgoal
    lamda = 0.3                 # subgoal testing parameter
 
    # DDPG parameters:
    gamma = 0.95                # discount factor for future rewards
    n_iter = 100                # update policy n_iter times in one DDPG update
    batch_size = 100            # num of transitions sampled from replay buffer
    lr = 0.001
 
    # save trained models
    directory = "./preTrained/{}/{}level/".format(env_name, k_level) 
    filename = "HAC_{}".format(env_name)
    #########################################################
 
 
    if random_seed:
        print("Random Seed: {}".format(random_seed))
        env.seed(random_seed)
        torch.manual_seed(random_seed)
        np.random.seed(random_seed)
 
    # creating HAC agent and setting parameters
    agent = HAC(k_level, H, state_dim, action_dim, render, threshold, 
                action_bounds, action_offset, state_bounds, state_offset, lr)
 
    agent.set_parameters(lamda, gamma, action_clip_low, action_clip_high, 
                       state_clip_low, state_clip_high, exploration_action_noise, exploration_state_noise)
 
    # logging file:
    log_f = open("log.txt","w+")
 
    # training procedure 
    for i_episode in range(1, max_episodes+1):
        agent.reward = 0
        agent.timestep = 0
 
        state = env.reset()
        # collecting experience in environment
        last_state, done = agent.run_HAC(env, k_level-1, state, goal_state, False)
 
        if agent.check_goal(last_state, goal_state, threshold):
            print("################ Solved! ################ ")
            name = filename + '_solved'
            agent.save(directory, name)
 
        # update all levels
        agent.update(n_iter, batch_size)
 
        # logging updates:
        log_f.write('{},{}\n'.format(i_episode, agent.reward))
        log_f.flush()
 
        if i_episode % save_episode == 0:
            agent.save(directory, filename)
 
        print("Episode: {}\t Reward: {}".format(i_episode, agent.reward))
 
 
if __name__ == '__main__':
    train()
 


...
Episode: 977 Reward: 93.14981821106747
Episode: 978 Reward: 85.80301098235486
Episode: 979 Reward: 94.08497730146644
Episode: 980 Reward: 93.57323148462481
################ Solved! ################
Episode: 981 Reward: 94.30903430418017
Episode: 982 Reward: 94.16225743305678
Episode: 983 Reward: 89.56179598471766
################ Solved! ################
Episode: 984 Reward: 90.52526236341699
Episode: 985 Reward: 85.97721570578817
Episode: 986 Reward: 93.25564229552454
Episode: 987 Reward: 91.38921550721918
Episode: 988 Reward: 93.09983090507252
Episode: 989 Reward: 93.37642257504483
Episode: 990 Reward: 86.88152311143642
Episode: 991 Reward: 92.48002705280233
################ Solved! ################
Episode: 992 Reward: 92.49259349840285
Episode: 993 Reward: 93.25648441532256
################ Solved! ################
Episode: 994 Reward: 93.23889726981061
Episode: 995 Reward: 91.76052267619784
Episode: 996 Reward: 92.79597948160385
################ Solved! ################
Episode: 997 Reward: 91.78779442199951
Episode: 998 Reward: 94.31434415302715
Episode: 999 Reward: 90.06717270862326
Episode: 1000 Reward: 90.95175499155059



Tensorflow playground
Tensorflow playground


Tensorflow playground


Hierarchical-Actor-Critic-HAC-PyTorch

License: MITLicenseMIT  Copyright (c) 2019 Nikhil Barhate


GitHub









Reinforcement learning













Welcome, my name is Eric Soupet and I am the administrator of the site elodees.com. elodees.com is a state of the art of Artificial Intelligence and aims to be collaborative, you can now offer content such as articles, events, tutorials, ... so don't hesitate !

Platform images credit : Pixabay - Pixabay License | Pexels - Pexels License