def test_log(self): log_dir = "./newtest/test_log.txt" if os.path.exists(log_dir): shutil.rmtree(log_dir) logger = Logger(log_dir) logger.log("test text") logger.log_performance(1, 1) logger.log_performance(2, 2) logger.log_performance(3, 3) logger.close_files() logger.plot('aaa')
state = env.reset() for timestep in range(timesteps): action = agent.step(state) next_state, reward, done = env.step(action) ts = (state, action, reward, next_state, done) agent.feed(ts) if timestep % evaluate_every == 0: rewards = [] state = eval_env.reset() for _ in range(evaluate_num): action, _ = agent.eval_step(state) _, reward, done = env.step(action) if done: rewards.append(reward) logger.log_performance(env.timestep, np.mean(rewards)) # Close files in the logger logger.close_files() # Plot the learning curve logger.plot('DQN') # Save model save_dir = 'models/uno_single_dqn' if not os.path.exists(save_dir): os.makedirs(save_dir) saver = tf.train.Saver() saver.save(sess, os.path.join(save_dir, 'model'))
# The paths for saving the logs and learning curves log_dir = './experiments/leduc_holdem_cfr_result/' # Set a global seed set_global_seed(0) # Initilize CFR Agent agent = CFRAgent(env) agent.load() # If we have saved model, we first load the model # Evaluate CFR against pre-trained NFSP eval_env.set_agents([agent, models.load('leduc-holdem-nfsp').agents[0]]) # Init a Logger to plot the learning curve logger = Logger(log_dir) for episode in range(episode_num): agent.train() print('\rIteration {}'.format(episode), end='') # Evaluate the performance. Play with NFSP agents. if episode % evaluate_every == 0: agent.save() # Save model logger.log_performance(env.timestep, tournament(eval_env, evaluate_num)[0]) # Close files in the logger logger.close_files() # Plot the learning curve logger.plot('CFR')
class ExperimentRunner: def __init__(self, env, eval_env, log_every, save_every, base_dir, config, training_agent, vs_agent, feed_function, save_function): self.save_dir = "{}/{}".format(base_dir, datetime.now().strftime("%Y%m%d")) self.log_dir = os.path.join(self.save_dir, "logs/") self.model_dir = os.path.join(self.save_dir, "model/") if not os.path.exists(self.model_dir): os.makedirs(self.model_dir) self.log_every = log_every self.save_every = save_every self.config = config self.env = env self.eval_env = eval_env self.agent = training_agent self.training_agents = [self.agent, vs_agent] self.env.set_agents(self.training_agents) self.logger = Logger(self.log_dir) self.logger.log("CONFIG: ") self.logger.log(str(config)) self.stat_logger = YanivStatLogger(self.logger) self.feed_function = feed_function self.save_function = save_function self.action_space = utils.JOINED_ACTION_SPACE if config[ 'single_step_actions'] else utils.ACTION_SPACE def feed_game(self, agent, trajectories, player_id): self.feed_function(agent, trajectories[player_id]) if self.config.get("feed_both_games"): other_traj = trajectories[player_id + 1 % len(self.training_agents)] if self.training_agents[player_id + 1 % len(self.training_agents)].use_raw: self.feed_function( agent, list( map( lambda t: [t[0], self.action_space[t[1]], *t[2:]], other_traj, ))) else: self.feed_function(agent, other_traj) def run_training(self, episode_num, eval_every, eval_vs, eval_num): for episode in trange(episode_num, desc="Episodes", file=sys.stdout): # Generate data from the environment trajectories, _ = self.env.run(is_training=True) self.stat_logger.add_game(trajectories, self.env, 0) self.feed_game(self.agent, trajectories, 0) if self.config['feed_both_agents']: self.feed_game(self.training_agents[1], trajectories, 1) if episode != 0 and episode % self.log_every == 0: self.stat_logger.log_stats() if episode != 0 and episode % self.save_every == 0: self.save_function(self.agent, self.model_dir) if episode != 0 and episode % eval_every == 0: self.logger.log( "\n\n########## Evaluation {} ##########".format(episode)) self.evaluate_perf(eval_vs, eval_num) self.evaluate_perf(eval_vs, eval_num) self.save_function(self.agent, self.model_dir) def evaluate_perf(self, eval_vs, eval_num): if isinstance(eval_vs, list): for vs in eval_vs: self.run_evaluation(vs, eval_num) else: self.run_evaluation(eval_vs, eval_num) def run_evaluation(self, vs, num): self.eval_env.set_agents([self.agent, vs]) self.logger.log("eval vs {}".format(vs.__class__.__name__)) r = tournament(self.eval_env, num) eval_vs = "eval_{}_".format(vs.__class__.__name__) wandb.log( { eval_vs + "payoff": r["payoffs"][0], eval_vs + "draws": r["draws"], eval_vs + "roundlen": r["roundlen"], eval_vs + "assafs": r["assafs"][0], eval_vs + "win_rate": r["wins"][0] / num, }, ) self.logger.log("Timestep: {}, avg roundlen: {}".format( self.env.timestep, r["roundlen"])) for i in range(self.env.player_num): self.logger.log( "Agent {}:\nWins: {}, Draws: {}, Assafs: {}, Payoff: {}". format( i, r["wins"][i], r["draws"], r["assafs"][i], r["payoffs"][i], )) self.logger.log_performance(self.env.timestep, r["payoffs"][0])
def train_mahjong(): # Make environment env = rlcard.make('mahjong', config={'seed': 0}) eval_env = rlcard.make('mahjong', config={'seed': 0}) # Set the iterations numbers and how frequently we evaluate the performance evaluate_every = 1000 evaluate_num = 1000 episode_num = 10000 # The intial memory size memory_init_size = 1000 # Train the agent every X steps train_every = 64 # The paths for saving the logs and learning curves log_dir = './experiments/mahjong_nfsp_result/' # Set a global seed set_global_seed(0) with tf.Session() as sess: # Initialize a global step global_step = tf.Variable(0, name='global_step', trainable=False) # Set up the agents agents = [] for i in range(env.player_num): agent = NFSPAgent(sess, scope='nfsp' + str(i), action_num=env.action_num, state_shape=env.state_shape, hidden_layers_sizes=[512, 512], anticipatory_param=0.5, batch_size=256, rl_learning_rate=0.00005, sl_learning_rate=0.00001, min_buffer_size_to_learn=memory_init_size, q_replay_memory_size=int(1e5), q_replay_memory_init_size=memory_init_size, train_every=train_every, q_train_every=train_every, q_batch_size=256, q_mlp_layers=[512, 512]) agents.append(agent) random_agent = RandomAgent(action_num=eval_env.action_num) env.set_agents(agents) eval_env.set_agents( [agents[0], random_agent, random_agent, random_agent]) # Initialize global variables sess.run(tf.global_variables_initializer()) # Init a Logger to plot the learning curvefrom rlcard.agents.random_agent import RandomAgent logger = Logger(log_dir) for episode in tqdm(range(episode_num)): # First sample a policy for the episode for agent in agents: agent.sample_episode_policy() # Generate data from the environment trajectories, _ = env.run(is_training=True) # Feed transitions into agent memory, and train the agent for i in range(env.player_num): for ts in trajectories[i]: agents[i].feed(ts) # Evaluate the performance. Play with random agents. if episode % evaluate_every == 0: logger.log_performance(env.timestep, tournament(eval_env, evaluate_num)[0]) # Close files in the logger logger.close_files() # Plot the learning curve logger.plot('NFSP') # Save model save_dir = 'models/mahjong_nfsp' if not os.path.exists(save_dir): os.makedirs(save_dir) saver = tf.train.Saver() saver.save(sess, os.path.join(save_dir, 'model'))
sess.run(tf.global_variables_initializer()) # Init a Logger to plot the learning curve logger = Logger(log_dir) for episode in range(episode_num): # Generate data from the environment trajectories, _ = env.run(is_training=True) # Feed transitions into agent memory, and train the agent for ts in trajectories[0]: agent.feed(ts) # Evaluate the performance. Play with random agents. if episode % evaluate_every == 0: t = tournament(eval_env, evaluate_num)[0] logger.log_performance(env.timestep, t) # Close files in the logger logger.close_files() # Plot the learning curve logger.plot('DQN') # Save model save_dir = 'models/yaniv_dqn' if not os.path.exists(save_dir): os.makedirs(save_dir) saver = tf.train.Saver() saver.save(sess, os.path.join(save_dir, 'model'))
i, step_counters[i], sl_loss), end='') ### Evaluation Step: Evaluate the agent every 100 steps and generate the plot for analysis. ### # Evaluate the performance. Play with random agents. if episode % evaluate_every == 0: reward = 0 for eval_episode in range(evaluate_num): _, payoffs = eval_env.run(is_training=False) reward += payoffs[0] logger.log('\n########## Evaluation ##########') logger.log('Timestep: {} Average reward is {}'.format( env.timestep, float(reward) / evaluate_num)) # Add point to logger logger.log_performance(env.timestep, float(reward) / evaluate_num) # Make plot if episode % 100000 == 0 and episode > 0: if not os.path.exists(save_dir): os.makedirs(save_dir) saver = tf.train.Saver() saver.save( sess, os.path.join(save_dir, 'model' + str(episode // 100000))) # logger.plot('NSFP') # Make the final plot # plot(csv_path, figure_path + 'fig.png', 'NSFP')
state_shape=env.state_shape, batch_size=64, mlp_layers=[64]) env.set_agents([ agent, RandomAgent(action_num=env.action_num), RandomAgent(action_num=env.action_num), RandomAgent(action_num=env.action_num) ]) eval_env.set_agents([ agent, RandomAgent(action_num=env.action_num), RandomAgent(action_num=env.action_num), RandomAgent(action_num=env.action_num) ]) logger = Logger('.') for episode in range(100000): # Generate data from the environment trajectories, _ = env.run(is_training=True) # Feed transitions into agent memory, and train the agent for ts in trajectories[0]: agent.feed(ts) # Evaluate the performance. Play with random agents. if episode % 5000 == 0: logger.log_performance(env.timestep, tournament(eval_env, 10000)[0]) logger.close_files() logger.plot('DQN')