Switch to unified view

a b/submission/baselines/results_plotter.py
1
import numpy as np
2
import matplotlib
3
matplotlib.use('TkAgg') # Can change to 'Agg' for non-interactive mode
4
5
import matplotlib.pyplot as plt
6
plt.rcParams['svg.fonttype'] = 'none'
7
8
from baselines.bench.monitor import load_results
9
10
X_TIMESTEPS = 'timesteps'
11
X_EPISODES = 'episodes'
12
X_WALLTIME = 'walltime_hrs'
13
POSSIBLE_X_AXES = [X_TIMESTEPS, X_EPISODES, X_WALLTIME]
14
EPISODES_WINDOW = 100
15
COLORS = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'black', 'purple', 'pink',
16
        'brown', 'orange', 'teal', 'coral', 'lightblue', 'lime', 'lavender', 'turquoise',
17
        'darkgreen', 'tan', 'salmon', 'gold', 'lightpurple', 'darkred', 'darkblue']
18
19
def rolling_window(a, window):
20
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
21
    strides = a.strides + (a.strides[-1],)
22
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
23
24
def window_func(x, y, window, func):
25
    yw = rolling_window(y, window)
26
    yw_func = func(yw, axis=-1)
27
    return x[window-1:], yw_func
28
29
def ts2xy(ts, xaxis):
30
    if xaxis == X_TIMESTEPS:
31
        x = np.cumsum(ts.l.values)
32
        y = ts.r.values
33
    elif xaxis == X_EPISODES:
34
        x = np.arange(len(ts))
35
        y = ts.r.values
36
    elif xaxis == X_WALLTIME:
37
        x = ts.t.values / 3600.
38
        y = ts.r.values
39
    else:
40
        raise NotImplementedError
41
    return x, y
42
43
def plot_curves(xy_list, xaxis, title):
44
    plt.figure(figsize=(8,2))
45
    maxx = max(xy[0][-1] for xy in xy_list)
46
    minx = 0
47
    for (i, (x, y)) in enumerate(xy_list):
48
        color = COLORS[i]
49
        plt.scatter(x, y, s=2)
50
        x, y_mean = window_func(x, y, EPISODES_WINDOW, np.mean) #So returns average of last EPISODE_WINDOW episodes
51
        plt.plot(x, y_mean, color=color)
52
    plt.xlim(minx, maxx)
53
    plt.title(title)
54
    plt.xlabel(xaxis)
55
    plt.ylabel("Episode Rewards")
56
    plt.tight_layout()
57
58
def plot_results(dirs, num_timesteps, xaxis, task_name):
59
    tslist = []
60
    for dir in dirs:
61
        ts = load_results(dir)
62
        ts = ts[ts.l.cumsum() <= num_timesteps]
63
        tslist.append(ts)
64
    xy_list = [ts2xy(ts, xaxis) for ts in tslist]
65
    plot_curves(xy_list, xaxis, task_name)
66
67
# Example usage in jupyter-notebook
68
# from baselines import log_viewer
69
# %matplotlib inline
70
# log_viewer.plot_results(["./log"], 10e6, log_viewer.X_TIMESTEPS, "Breakout")
71
# Here ./log is a directory containing the monitor.csv files
72
73
def main():
74
    import argparse
75
    import os
76
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
77
    parser.add_argument('--dirs', help='List of log directories', nargs = '*', default=['./log'])
78
    parser.add_argument('--num_timesteps', type=int, default=int(10e6))
79
    parser.add_argument('--xaxis', help = 'Varible on X-axis', default = X_TIMESTEPS)
80
    parser.add_argument('--task_name', help = 'Title of plot', default = 'Breakout')
81
    args = parser.parse_args()
82
    args.dirs = [os.path.abspath(dir) for dir in args.dirs]
83
    plot_results(args.dirs, args.num_timesteps, args.xaxis, args.task_name)
84
    plt.show()
85
86
if __name__ == '__main__':
87
    main()