CNNTrainer_cartpole_master_dqn.py 3.54 KB
Newer Older
1
from reinforcement_learning.agent import DqnAgent
Nicola Gatto's avatar
Nicola Gatto committed
2
from reinforcement_learning.util import AgentSignalHandler
Nicola Gatto's avatar
Nicola Gatto committed
3
from reinforcement_learning.cnnarch_logger import ArchLogger
4 5
import reinforcement_learning.environment
import CNNCreator_cartpole_master_dqn
Nicola Gatto's avatar
Nicola Gatto committed
6 7 8 9

import os
import sys
import re
10 11 12
import logging
import mxnet as mx

Nicola Gatto's avatar
Nicola Gatto committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

def resume_session():
    session_param_output = os.path.join(session_output_dir, agent_name)
    resume_session = False
    resume_directory = None
    if os.path.isdir(session_output_dir) and os.path.isdir(session_param_output):
        regex = re.compile(r'\d\d\d\d-\d\d-\d\d-\d\d-\d\d')
        dir_content = os.listdir(session_param_output)
        session_files = filter(regex.search, dir_content)
        session_files.sort(reverse=True)
        for d in session_files:
            interrupted_session_dir = os.path.join(session_param_output, d, '.interrupted_session')
            if os.path.isdir(interrupted_session_dir):
                resume = raw_input('Interrupted session from {} found. Do you want to resume? (y/n) '.format(d))
                if resume == 'y':
                    resume_session = True
                    resume_directory = interrupted_session_dir
                break
    return resume_session, resume_directory

Nicola Gatto's avatar
Nicola Gatto committed
33

34
if __name__ == "__main__":
Nicola Gatto's avatar
Nicola Gatto committed
35 36 37 38 39 40 41 42 43 44
    agent_name='cartpole_master_dqn'
    # Prepare output directory and logger
    output_directory = 'model_output'\
        + '/' + agent_name\
        + '/' + time.strftime(
            '%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
    ArchLogger.set_output_directory(output_directory)
    ArchLogger.set_logger_name(agent_name)
    ArchLogger.set_output_level(ArchLogger.INFO)

45 46
    env = reinforcement_learning.environment.GymEnvironment('CartPole-v0')

Nicola Gatto's avatar
Nicola Gatto committed
47 48 49
    context = mx.cpu()
    qnet_creator = CNNCreator_cartpole_master_dqn.CNNCreator_cartpole_master_dqn()
    qnet_creator.construct(context)
50

Nicola Gatto's avatar
Nicola Gatto committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    agent_params = {
        'environment': env,
        'replay_memory_params': {
            'method':'buffer',
            'memory_size':10000,
            'sample_size':32,
            'state_dtype':'float32',
            'action_dtype':'float32',
            'rewards_dtype':'float32'
        },
        'strategy_params': {
            'method':'epsgreedy',
            'epsilon': 1,
            'min_epsilon': 0.01,
            'epsilon_decay_method': 'linear',
            'epsilon_decay': 0.01,
        },
        'agent_name': agent_name,
        'verbose': True,
        'state_dim': (4,),
        'action_dim': (2,),
        'ctx': 'cpu',
        'discount_factor': 0.999,
        'training_episodes': 160,
        'train_interval': 1,
        'snapshot_interval': 20,
        'max_episode_step': 250,
        'target_score': 185.5,
        'qnet':qnet_creator.net,
        'use_fix_target': True,
        'target_update_interval': 200,
        'loss_function': 'euclidean',
        'optimizer': 'rmsprop',
        'optimizer_params': {
            'learning_rate': 0.001        },
        'double_dqn': False,
87 88
    }

Nicola Gatto's avatar
Nicola Gatto committed
89
    resume, resume_directory = resume_session()
Nicola Gatto's avatar
Nicola Gatto committed
90

Nicola Gatto's avatar
Nicola Gatto committed
91 92 93 94 95 96 97
    if resume:
        resume_agent_params = {
            'session_dir': resume_directory,
            'environment': env,
            'net': qnet_creator.net,
        }
        agent = DqnAgent.resume_from_session(**resume_agent_params)
Nicola Gatto's avatar
Nicola Gatto committed
98
    else:
Nicola Gatto's avatar
Nicola Gatto committed
99
        agent = DqnAgent(**agent_params)
Nicola Gatto's avatar
Nicola Gatto committed
100 101 102 103 104 105 106

    signal_handler = AgentSignalHandler()
    signal_handler.register_agent(agent)

    train_successful = agent.train()

    if train_successful:
Nicola Gatto's avatar
Nicola Gatto committed
107
        agent.save_best_network(qnet_creator._model_dir_ + qnet_creator._model_prefix_ + '_newest', epoch=0)