Example #1
0
def play(show_number):
    env = TicTacToeEnv(show_number=show_number)
    agents = [MinimaxAgent('O'),
              HumanAgent('X')]
    episode = 0
    while True:
        state = env.reset()
        _, mark = state
        done = False
        env.render()
        while not done:
            agent = agent_by_mark(agents, mark)
            env.show_turn(True, mark)
            ava_actions = env.available_actions()
            if mark=='O':
                n,action=agent.act(state, ava_actions)
            else:
                action = agent.act(state, ava_actions)
            if action is None:
                sys.exit()

            state, reward, done, info = env.step(action)
        
            print('')
            env.render()
            if done:
                env.show_result(True, mark, reward)
                break
            else:
                _, _ = state
            mark = next_mark(mark)

        episode += 1
Example #2
0
def play(max_episode=10):
    episode = 0
    start_mark = 'O'
    env = TicTacToeEnv()
    agents = [BaseAgent('O'), BaseAgent('X')]

    while episode < max_episode:
        env.set_start_mark(start_mark)
        state = env.reset()
        _, mark = state
        done = False
        while not done:
            env.show_turn(True, mark)

            agent = agent_by_mark(agents, mark)
            ava_actions = env.available_actions()
            action = agent.act(state, ava_actions)
            state, reward, done, info = env.step(action)
            env.render()

            if done:
                env.show_result(True, mark, reward)
                break
            else:
                _, mark = state

        # rotate start
        start_mark = next_mark(start_mark)
        episode += 1
Example #3
0
def learn_on_policy(episodes, epsilon=0.1, discount_factor=0.9):
    env = TicTacToeEnv()
    agents = [MCOPA('O', epsilon), MCOPA('X', epsilon)]

    start_mark = 'O'
    env.set_start_mark(start_mark)
    for i in range(episodes):
        episode = i + 1
        state = env.reset()
        _, mark = state
        steps = []
        done = False
        while not done:
            agent = agent_by_mark(agents, mark)
            actions = env.available_actions()
            action = agent.act(state, actions)
            next_state, reward, done, _ = env.step(action)
            steps.append((state, reward))
            if done:
                break
            _, mark = state = next_state

        steps.reverse()
        G = 0
        # As in one episode of tic tac toe there will only be unique states we don't need to check for them
        for step in steps:
            _, mark = step[0]
            G = step[1] + discount_factor * G
            agents[0].update(step[0], G)

        # rotate start
        start_mark = next_mark(start_mark)
Example #4
0
def _bench(max_episode, model_file, show_result=True):
    """Benchmark given model.

    Args:
        max_episode (int): Episode count to benchmark.
        model_file (str): Learned model file name to benchmark.
        show_result (bool): Output result to stdout.

    Returns:
        (dict): Benchmark result.
    """
    minfo = load_model(model_file)
    agents = [BaseAgent('O'), TDAgent('X', 0, 0)]
    show = False

    start_mark = 'O'
    env = TicTacToeEnv()
    env.set_start_mark(start_mark)

    episode = 0
    results = []
    for i in tqdm(range(max_episode)):
        env.set_start_mark(start_mark)
        state = env.reset()
        _, mark = state
        done = False
        while not done:
            agent = agent_by_mark(agents, mark)
            ava_actions = env.available_actions()
            action = agent.act(state, ava_actions)
            state, reward, done, info = env.step(action)
            if show:
                env.show_turn(True, mark)
                env.render(mode='human')

            if done:
                if show:
                    env.show_result(True, mark, reward)
                results.append(reward)
                break
            else:
                _, mark = state

        # rotation start
        start_mark = next_mark(start_mark)
        episode += 1

    o_win = results.count(1)
    x_win = results.count(-1)
    draw = len(results) - o_win - x_win
    mfile = model_file.replace(CWD + os.sep, '')
    minfo.update(
        dict(base_win=o_win, td_win=x_win, draw=draw, model_file=mfile))
    result = json.dumps(minfo)

    if show_result:
        print(result)
    return result
Example #5
0
def _play(load_file, vs_agent, show_number):
    """Play with learned model.

    Make TD agent and adversarial agnet to play with.
    Play and switch starting mark when the game finished.
    TD agent behave no exploring action while in play mode.

    Args:
        load_file (str):
        vs_agent (object): Enemy agent of TD agent.
        show_number (bool): Whether show grid number for visual hint.
    """
    load_model(load_file)
    env = TicTacToeEnv(show_number=show_number)
    td_agent = TDAgent('X', 0, 0)  # prevent exploring
    start_mark = 'O'
    agents = [vs_agent, td_agent]

    while True:
        # start agent rotation
        env.set_start_mark(start_mark)
        state = env.reset()
        _, mark = state
        done = False

        # show start board for human agent
        if mark == 'O':
            env.render(mode='human')

        while not done:
            agent = agent_by_mark(agents, mark)
            human = isinstance(agent, HumanAgent)

            env.show_turn(True, mark)
            ava_actions = env.available_actions()
            if human:
                action = agent.act(ava_actions)
                if action is None:
                    sys.exit()
            else:
                action = agent.act(state, ava_actions)

            state, reward, done, info = env.step(action)

            env.render(mode='human')
            if done:
                env.show_result(True, mark, reward)
                break
            else:
                _, mark = state

        # rotation start
        start_mark = next_mark(start_mark)
Example #6
0
def learn_off_policy(episodes, discount_factor=0.9):
    env = TicTacToeEnv()
    agents = [MCOffPA('O'),
              MCOffPA('X')]

    start_mark = 'O'
    env.set_start_mark(start_mark)
    for i in range(episodes):
        state = env.reset()
        _, mark = state
        steps = []
        done = False
        while not done:
            agent = agent_by_mark(agents, mark)
            actions = env.available_actions()
            action = random.choice(actions)
            next_state, reward, done, _ = env.step(action)
            steps.append((state, reward, action, actions))
            if done:
                break
            _, mark = state = next_state
            
        steps.reverse()
        G = 0
        W = 1
        
        # As in one episode of tic tac toe there will only be unique states we don't need to check for them
        for step in steps:
            _, mark = step[0]
            agent = agent_by_mark(agents, mark)
            G = step[1] + discount_factor*G
            agent.update(step[0], G, W)
            if agent.act(step[0], step[3]) != step[2]:
                break
                
            # behaviour policy = 1/available_actions
            W = W*len(step[3])
            
        # rotate start
        start_mark = next_mark(start_mark)
Example #7
0
def _learn(max_episode, epsilon, alpha, save_file):
    """Learn by episodes.

    Make two TD agent, and repeat self play for given episode count.
    Update state values as reward coming from the environment.

    Args:
        max_episode (int): Episode count.
        epsilon (float): Probability of exploration.
        alpha (float): Step size.
        save_file: File name to save result.
    """
    reset_state_values()

    env = TicTacToeEnv()
    agents = [TDAgent('O', epsilon, alpha), TDAgent('X', epsilon, alpha)]

    start_mark = 'O'
    for i in tqdm(range(max_episode)):
        episode = i + 1
        env.show_episode(False, episode)

        # reset agent for new episode
        for agent in agents:
            agent.episode_rate = episode / float(max_episode)

        env.set_start_mark(start_mark)
        state = env.reset()
        _, mark = state
        done = False
        while not done:
            agent = agent_by_mark(agents, mark)
            ava_actions = env.available_actions()
            env.show_turn(False, mark)
            action = agent.act(state, ava_actions)

            # update (no rendering)
            nstate, reward, done, info = env.step(action)
            agent.backup(state, nstate, reward)

            if done:
                env.show_result(False, mark, reward)
                # set terminal state value
                set_state_value(state, reward)

            _, mark = state = nstate

        # rotate start
        start_mark = next_mark(start_mark)

    # save states
    save_model(save_file, max_episode, epsilon, alpha)
Example #8
0
def plotting_MC(env, agent1, agent2, learn_fn, r=100):
    num_states = []
    num_roll_out = []
    ub = [[], []]
    lb = [[], []]
    mean = [[], []]

    agent1.reset()
    # Training curves
    k = 0
    for j in range(r):
        num_roll_out.append(k)
        num_states.append(agent1.num_states())

        for i in range(15):
            R = 0
            for _ in range(10):
                state = env.reset()
                _, mark = state
                done = False
                agents = [agent1, agent2]
                while not done:
                    agent = agent_by_mark(agents, mark)
                    actions = env.available_actions()
                    action = agent.act(state, actions)
                    next_state, reward, done, _ = env.step(action)
                    _, mark = state = next_state

                R += reward
            if len(ub[0]) == j:
                ub[0].append(R)
                lb[0].append(R)
                mean[0].append(R)
                ub[1].append(-R)
                lb[1].append(-R)
                mean[1].append(-R)
            else:
                ub[0][j] = max(ub[0][j], R)
                lb[0][j] = min(lb[0][j], R)
                mean[0][j] = mean[0][j] + (R - mean[0][j]) / (i + 1)
                ub[1][j] = max(ub[1][j], -R)
                lb[1][j] = min(lb[1][j], -R)
                mean[1][j] = mean[1][j] + (-R - mean[1][j]) / (i + 1)
        learn_fn(500)
        k += 500

    # plot the data
    fig = plt.figure(1, figsize=(14, 5))
    plot_mean_and_CI(mean[0],
                     ub[0],
                     lb[0],
                     num_states,
                     color_mean='r',
                     color_shading='r')
    plot_mean_and_CI(mean[1],
                     ub[1],
                     lb[1],
                     num_states,
                     color_mean='b',
                     color_shading='b')
    plt.title('Confidence interval vs states covered')
    plt.show()

    # plot the data
    fig = plt.figure(2, figsize=(14, 5))
    plot_mean_and_CI(mean[0],
                     ub[0],
                     lb[0],
                     num_roll_out,
                     color_mean='r',
                     color_shading='r')
    plot_mean_and_CI(mean[1],
                     ub[1],
                     lb[1],
                     num_roll_out,
                     color_mean='b',
                     color_shading='b')
    plt.title('Confidence interval vs number of rollouts')
    plt.show()