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

import os
import sys
import re
Nicola Gatto's avatar
Nicola Gatto committed
10 11
import time
import numpy as np
12 13 14
import mxnet as mx


Nicola Gatto's avatar
Nicola Gatto committed
15
def resume_session(sessions_dir):
16 17
    resume_session = False
    resume_directory = None
Nicola Gatto's avatar
Nicola Gatto committed
18
    if os.path.isdir(sessions_dir):
19
        regex = re.compile(r'\d\d\d\d-\d\d-\d\d-\d\d-\d\d')
Nicola Gatto's avatar
Nicola Gatto committed
20
        dir_content = os.listdir(sessions_dir)
21 22 23
        session_files = filter(regex.search, dir_content)
        session_files.sort(reverse=True)
        for d in session_files:
Nicola Gatto's avatar
Nicola Gatto committed
24
            interrupted_session_dir = os.path.join(sessions_dir, d, '.interrupted_session')
25 26 27 28 29 30 31 32
            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 45
    agent_name = 'reinforcement_agent'
    # Prepare output directory and logger
    all_output_dir = os.path.join('model', agent_name)
    output_directory = os.path.join(
        all_output_dir,
        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)

46
    env_params = {
Nicola Gatto's avatar
Nicola Gatto committed
47 48 49 50
        'ros_node_name': 'reinforcementConfig1TrainerNode',
        'state_topic': '/environment/state',
        'action_topic': '/environment/action',
        'reset_topic': '/environment/reset',
51 52 53
    }
    env = reinforcement_learning.environment.RosEnvironment(**env_params)

Nicola Gatto's avatar
Nicola Gatto committed
54 55 56
    context = mx.cpu()
    qnet_creator = CNNCreator_reinforcementConfig1.CNNCreator_reinforcementConfig1()
    qnet_creator.construct(context)
57

Nicola Gatto's avatar
Nicola Gatto committed
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 87 88
    agent_params = {
        'environment': env,
        'replay_memory_params': {
            'method': 'buffer',
            'memory_size': 1000000,
            'sample_size': 64,
            'state_dtype': 'float32',
            'action_dtype': 'float32',
            'rewards_dtype': 'float32'
        },
        'strategy_params': {
            'method':'epsgreedy',
            'epsilon': 1,
            'min_epsilon': 0.02,
            'epsilon_decay_method': 'linear',
            'epsilon_decay': 0.0001,
        },
        'agent_name': agent_name,
        'verbose': True,
        'output_directory': output_directory,
        'state_dim': (8,),
        'action_dim': (3,),
        'discount_factor': 0.99999,
        'training_episodes': 1000,
        'train_interval': 1,
        'snapshot_interval': 500,
        'max_episode_step': 10000,
        'target_score': 35000,
        'qnet':qnet_creator.net,
        'use_fix_target': True,
        'target_update_interval': 500,
Eyüp Harputlu's avatar
Eyüp Harputlu committed
89
        'loss': 'huber',
Nicola Gatto's avatar
Nicola Gatto committed
90 91 92 93
        'optimizer': 'adam',
        'optimizer_params': {
            'learning_rate': 0.001        },
        'double_dqn': True,
94 95
    }

Nicola Gatto's avatar
Nicola Gatto committed
96
    resume, resume_directory = resume_session(all_output_dir)
97

Nicola Gatto's avatar
Nicola Gatto committed
98 99 100 101 102 103
    if resume:
        output_directory, _ = os.path.split(resume_directory)
        ArchLogger.set_output_directory(output_directory)
        resume_agent_params = {
            'session_dir': resume_directory,
            'environment': env,
Nicola Gatto's avatar
Nicola Gatto committed
104
            'net': qnet_creator.networks[0],
Nicola Gatto's avatar
Nicola Gatto committed
105 106
        }
        agent = DqnAgent.resume_from_session(**resume_agent_params)
107
    else:
Nicola Gatto's avatar
Nicola Gatto committed
108
        agent = DqnAgent(**agent_params)
109 110 111 112 113 114 115

    signal_handler = AgentSignalHandler()
    signal_handler.register_agent(agent)

    train_successful = agent.train()

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