Exemplo n.º 1
0
    def draw_basic_figure(obj_func=False):
        fig, ax = plt.subplots(1, 1, squeeze=True)
        ax.set_xlim(bounds["x"])
        ax.set_ylim(bounds["gp_y"])
        ax.grid()
        boplot.plot_gp(model=gp, confidence_intervals=[1.0, 2.0, 3.0], custom_x=x, ax=ax)
        if obj_func:
            boplot.plot_objective_function(ax=ax)
        boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)
        boplot.highlight_output(
            y=np.array([ymin]),
            label=['$c_{inc}$'],
            lloc='left',
            ax=ax,
            # disable_ticks=True
        )
        # boplot.annotate_y_edge(
        #     label='$c_{inc}$',
        #     xy=((ax.get_xlim()[0] + x[ymin_arg]) / 2, ymin),
        #     ax=ax,
        #     align='left',
        #     yoffset=1.0
        # )

        return fig, ax
Exemplo n.º 2
0
    def draw_basic_plot(mark_incumbent=True, show_objective=False):
        fig, ax = plt.subplots(1, 1, squeeze=True)
        ax.set_xlim(bounds["x"])
        ax.set_ylim(bounds["gp_y"])
        ax.grid()
        boplot.plot_gp(model=gp,
                       confidence_intervals=[1.0, 2.0, 3.0],
                       custom_x=x,
                       ax=ax)
        if show_objective:
            boplot.plot_objective_function(ax=ax)
        boplot.mark_observations(X_=x,
                                 Y_=y,
                                 mark_incumbent=mark_incumbent,
                                 highlight_datapoint=None,
                                 highlight_label=None,
                                 ax=ax)

        if mark_incumbent:
            boplot.highlight_output(y=np.array([ymin]),
                                    label=['$c_{inc}$'],
                                    lloc='left',
                                    ax=ax,
                                    disable_ticks=True)
            boplot.annotate_y_edge(label='$c_{inc}$',
                                   xy=(x[ymin_arg], ymin),
                                   ax=ax,
                                   align='left',
                                   yoffset=0.8)

        return fig, ax
Exemplo n.º 3
0
    def draw_basic_figure(tgp=gp,
                          tx=x,
                          tX_=x,
                          tY_=y,
                          title='',
                          highlight_datapoint=None,
                          highlight_label="",
                          ax=None):
        if ax is None:
            fig, ax = plt.subplots(1, 1, squeeze=True)
            plt.subplots_adjust(0.05, 0.15, 0.95, 0.85)
            figflag = True
        else:
            figflag = False

        ax.set_xlim(bounds["x"])
        ax.set_ylim(bounds["gp_y"])
        if title:
            ax.set_title(title, loc='left')
        ax.grid()
        boplot.plot_objective_function(ax=ax)
        boplot.plot_gp(model=tgp,
                       confidence_intervals=[1.0, 2.0, 3.0],
                       ax=ax,
                       custom_x=tx)
        if highlight_datapoint:
            boplot.mark_observations(X_=tX_,
                                     Y_=tY_,
                                     mark_incumbent=False,
                                     ax=ax,
                                     highlight_datapoint=highlight_datapoint,
                                     highlight_label=highlight_label)
        else:
            boplot.mark_observations(X_=tX_,
                                     Y_=tY_,
                                     mark_incumbent=False,
                                     ax=ax)

        if figflag:
            return fig, ax
        else:
            return ax
Exemplo n.º 4
0
    def draw_basic_plot(ax2_sci_not=False):
        fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True)
        ax1.set_xlim(bounds['x'])
        ax1.set_ylim(bounds['gp_y'])
        ax2.set_xlim(bounds['x'])
        ax2.set_ylim(bounds['acq_y'])

        if ax2_sci_not:
            f = mtick.ScalarFormatter(useOffset=False, useMathText=True)
            g = lambda x, pos: "${}$".format(f._formatSciNotation('%1.10e' % x)
                                             )
            ax2.yaxis.set_major_formatter(mtick.FuncFormatter(g))

        ax1.grid()
        ax2.grid()

        boplot.plot_objective_function(ax=ax1)
        boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, ax=ax1)

        return fig, (ax1, ax2)
Exemplo n.º 5
0
def run_bo(acquisition, max_iter, initial_design, acq_add, init=None):
    """
    BO
    :param acquisition: type of acquisition function to be used
    :param max_iter: max number of function calls
    :param seed: seed used to keep experiments reproducible
    :param initial_design: Method for initializing the GP, choice between 'uniform', 'random', and 'presentation'
    :param acq_add: additional parameteres for acquisition function (e.g. kappa for LCB)
    :param init: Number of datapoints to initialize GP with.
    :return: all evaluated points.
    """

    logging.debug("Running BO with Acquisition Function {0}, maximum iterations {1}, initial design {2}, "
                  "acq_add {3} and init {4}".format(acquisition, max_iter, initial_design, acq_add, init))
    x, y = initialize_dataset(initial_design=initial_design, init=init)
    logging.debug("Initialized dataset with:\nsamples {0}\nObservations {1}".format(x, y))

    for i in range(1, max_iter):  # BO loop
        logging.debug('Sample #%d' % (i))

        # Fit GP to the currently available dataset
        gp = GPR(kernel=Matern())
        logging.debug("Fitting GP to\nx: {}\ny:{}".format(x, y))
        gp.fit(x, y)  # fit the model

        # ----------Plotting calls---------------
        fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True)
        fig.tight_layout()
        ax1.set_xlim(bounds["x"])
        ax1.set_ylim(bounds["gp_y"])
        ax1.grid()
        ax2.set_xlim(bounds["x"])
        ax2.set_ylim(bounds["acq_y"])
        ax2.grid()
        boplot.plot_objective_function(ax=ax1)
        boplot.plot_gp(model=gp, confidence_intervals=[1.0, 2.0], ax=ax1, custom_x=x)
        boplot.mark_observations(X_=x, Y_=y, ax=ax1)
        # ---------------------------------------

        # noinspection PyStringFormat
        logging.debug("Model fit to dataset.\nOriginal Inputs: {0}\nOriginal Observations: {1}\n"
                      "Predicted Means: {2}\nPredicted STDs: {3}".format(x, y, *(gp.predict(x, return_std=True))))

        # Partially initialize the acquisition function to work with the fmin interface
        # (only the x parameter is not specified)
        acqui = partial(acquisition, model=gp, eta=min(y), add=acq_add)

        boplot.plot_acquisition_function(acquisition, min(y), gp, acq_add, invert=True, ax=ax2)

        # optimize acquisition function, repeat 10 times, use best result
        x_ = None
        y_ = 10000
        # Feel free to adjust the hyperparameters
        for j in range(NUM_ACQ_OPTS):
            opt_res = minimize(acqui, np.random.uniform(bounds["x"][0], bounds["x"][1]),
                               #bounds=bounds["x"],
                               options={'maxfun': 20, 'maxiter': 20}, method="L-BFGS-B")
            if opt_res.fun[0] < y_:
                x_ = opt_res.x
                y_ = opt_res.fun[0]

        # ----------Plotting calls---------------
        boplot.highlight_configuration(x_, ax=ax1)
        boplot.highlight_configuration(x_, ax=ax2)
        # ---------------------------------------

        # Update dataset with new observation
        x.append(x_)
        y.append(f(x_))

        logging.info("After {0}. loop iteration".format(i))
        logging.info("x: {0:.3E}, y: {1:.3E}".format(x_[0], y_))



        # ----------Plotting calls---------------
        for ax in (ax1, ax2):
            ax.legend()
            ax.set_xlabel(labels['xlabel'])

        ax1.set_ylabel(labels['gp_ylabel'])
        ax1.set_title("Visualization of GP", loc='left')

        ax2.set_title("Visualization of Acquisition Function", loc='left')
        ax2.set_ylabel(labels['acq_ylabel'])
        if TOGGLE_PRINT:
            plt.savefig("plot_{}.pdf".format(i), dpi='figure')
        else:
            plt.show()
        # ---------------------------------------

    return y
Exemplo n.º 6
0
def visualize_ei(initial_design, init=None):
    """
    Visualize one-step of EI.
    :param initial_design: Method for initializing the GP, choice between 'uniform', 'random', and 'presentation'
    :param init: Number of datapoints to initialize GP with.
    :return: None
    """

    # 1. Plot GP fit on initial dataset
    # 2. Mark current incumbent
    # 3. Mark Zone of Probable Improvement
    # 4. Mark Hypothetical Real cost of a random configuration
    # 5. Display I(lambda)
    # 6. Display Vertical Normal Distribution

    # boplot.set_rcparams(**{'legend.loc': 'lower left'})

    logging.debug("Visualizing EI with initial design {} and init {}".format(initial_design, init))
    # Initialize dummy dataset
    x, y = initialize_dataset(initial_design=initial_design, init=init)
    ymin_arg = np.argmin(y)
    ymin = y[ymin_arg]
    logging.debug("Initialized dataset with:\nsamples {0}\nObservations {1}".format(x, y))

    # Fit GP to the currently available dataset
    gp = GPR(kernel=Matern())
    logging.debug("Fitting GP to\nx: {}\ny:{}".format(x, y))
    gp.fit(x, y)  # fit the model
    mu_star_t_xy = get_mu_star(gp)
    logging.info("Mu-star at time t: {}".format(mu_star_t_xy))

    # noinspection PyStringFormat
    logging.debug("Model fit to dataset.\nOriginal Inputs: {0}\nOriginal Observations: {1}\n"
                  "Predicted Means: {2}\nPredicted STDs: {3}".format(x, y, *(gp.predict(x, return_std=True))))

    # 1. Plot GP fit on initial dataset
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, highlight_datapoint=None, highlight_label=None, ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("ei_1.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 2. Mark current incumbent
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("ei_2.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 3. Mark Zone of Probable Improvement
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)
    boplot.darken_graph(y=ymin, ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    ax.legend().remove()

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("ei_3.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 4. Forget the underlying objective function
    # -------------------------------------------

    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    # boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)
    boplot.darken_graph(y=ymin, ax=ax)

    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("ei_4.pdf")
    else:
        plt.show()

    # -------------------------------------------

    # 5. Mark Hypothetical Real cost of a random configuration
    # -------------------------------------------

    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    # boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)
    boplot.darken_graph(y=ymin, ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    candidate = 11.0
    cost = -3.5
    boplot.highlight_configuration(x=np.array([candidate]), label=r'$\lambda$', lloc='bottom', ax=ax)
    boplot.highlight_output(y=np.array([cost]), label='', lloc='left', ax=ax)
    boplot.annotate_y_edge(label=r'$c(\lambda)$', xy=(candidate, cost), align='left', ax=ax)

    ax.legend().remove()

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("ei_5.pdf")
    else:
        plt.show()

    # -------------------------------------------

    # 6. Display I(lambda)
    # -------------------------------------------

    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    # boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)
    boplot.darken_graph(y=ymin, ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    boplot.highlight_configuration(x=np.array([candidate]), label=r'$\lambda$', lloc='bottom', ax=ax)
    boplot.highlight_output(y=np.array([cost]), label='', lloc='left', ax=ax)
    boplot.annotate_y_edge(label=r'$c(\lambda)$', xy=(candidate, cost), align='left', ax=ax)

    xmid = (x[ymin_arg][0] + candidate) / 2.
    ax.annotate(s='', xy=(xmid, cost), xytext=(xmid, ymin),
                 arrowprops={'arrowstyle': '<|-|>',})

    textx = xmid + (ax.get_xlim()[1] - ax.get_xlim()[0]) / 40
    ax.text(textx, (ymin + cost) / 2, r'$I^{(t)}(\lambda)$', weight='heavy')

    ax.legend().remove()

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("ei_6.pdf")
    else:
        plt.show()

    # -------------------------------------------


    # 7. Display Vertical Normal Distribution
    # -------------------------------------------

    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    # boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)
    boplot.darken_graph(y=ymin, ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    boplot.highlight_configuration(x=np.array([candidate]), label=r'$\lambda$', lloc='bottom', ax=ax)
    boplot.highlight_output(y=np.array([cost]), label='', lloc='left', ax=ax)
    boplot.annotate_y_edge(label=r'$c(\lambda)$', xy=(candidate, cost), align='left', ax=ax)

    xmid = (x[ymin_arg][0] + candidate) / 2.
    ax.annotate(s='', xy=(xmid, cost), xytext=(xmid, ymin),
                 arrowprops={'arrowstyle': '<|-|>',})

    textx = xmid + (ax.get_xlim()[1] - ax.get_xlim()[0]) / 40
    ax.text(textx, (ymin + cost) / 2, r'$I^{(t)}(\lambda)$', weight='heavy')

    vcurve_x, vcurve_y, mu = boplot.draw_vertical_normal(
        gp=gp, incumbenty=ymin, ax=ax, xtest=candidate,
        xscale=2.0, yscale=1.0
    )

    ann_x = candidate + 0.3 * (np.max(vcurve_x) - candidate) / 2
    ann_y = ymin - (mu - ymin) / 2

    arrow_x = ann_x + 0.5
    arrow_y = ann_y - 3.0

    # label = "{:.2f}".format(candidate)
    label = '\lambda'

    ax.annotate(
        s=r'$PI^{(t)}(%s)$' % label, xy=(ann_x, ann_y), xytext=(arrow_x, arrow_y),
        arrowprops={'arrowstyle': 'fancy'},
        weight='heavy', color='darkgreen', zorder=15
    )

    ax.legend().remove()

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("ei_7.pdf")
    else:
        plt.show()
Exemplo n.º 7
0
def visualize_lcb(initial_design, init=None):
    """
    Visualize one-step of LCB.
    :param initial_design: Method for initializing the GP, choice between 'uniform', 'random', and 'presentation'
    :param init: Number of datapoints to initialize GP with.
    :return: None
    """

    # 1. Plot 3 different confidence envelopes
    # 2. Plot only LCB for one confidence envelope
    # 3. Mark next sample

    boplot.set_rcparams(**{'legend.loc': 'lower right'})

    logging.debug("Visualizing PI with initial design {} and init {}".format(initial_design, init))
    # Initialize dummy dataset
    x, y = initialize_dataset(initial_design=initial_design, init=init)
    logging.debug("Initialized dataset with:\nsamples {0}\nObservations {1}".format(x, y))

    # Fit GP to the currently available dataset
    gp = GPR(kernel=Matern())
    logging.debug("Fitting GP to\nx: {}\ny:{}".format(x, y))
    gp.fit(x, y)  # fit the model

    # noinspection PyStringFormat
    logging.debug("Model fit to dataset.\nOriginal Inputs: {0}\nOriginal Observations: {1}\n"
                  "Predicted Means: {2}\nPredicted STDs: {3}".format(x, y, *(gp.predict(x, return_std=True))))

    # 1. Plot 3 different confidence envelopes
    # -------------Plotting code -----------------

    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[1.0, 2.0, 3.0], type='both', custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, highlight_datapoint=None, highlight_label=None, ax=ax)

    ax.legend().set_zorder(zorders['legend'])
    ax.set_xlabel(labels['xlabel'])

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig(f"{OUTPUT_DIR}/lcb_1.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 2. Plot only LCB for one confidence envelope
    # -------------Plotting code -----------------

    boplot.set_rcparams(**{'legend.loc': 'upper left'})
    kappa = 3.0

    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[kappa], type='lower', custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)

    ax.legend().set_zorder(zorders['legend'])
    ax.set_xlabel(labels['xlabel'])

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig(f"{OUTPUT_DIR}/lcb_2.pdf")
    else:
        plt.show()
Exemplo n.º 8
0
def visualize_lcb(initial_design, init=None):
    """
    Visualize one-step of LCB.
    :param initial_design: Method for initializing the GP, choice between 'uniform', 'random', and 'presentation'
    :param init: Number of datapoints to initialize GP with.
    :return: None
    """

    # 1. Plot 3 different confidence envelopes
    # 2. Plot only LCB for one confidence envelope
    # 3. Mark next sample

    boplot.set_rcparams(**{'legend.loc': 'lower right'})

    logging.debug("Visualizing PI with initial design {} and init {}".format(
        initial_design, init))
    # Initialize dummy dataset
    x, y = initialize_dataset(initial_design=initial_design, init=init)
    logging.debug(
        "Initialized dataset with:\nsamples {0}\nObservations {1}".format(
            x, y))

    # Fit GP to the currently available dataset
    gp = GPR(kernel=Matern())
    logging.debug("Fitting GP to\nx: {}\ny:{}".format(x, y))
    gp.fit(x, y)  # fit the model

    # noinspection PyStringFormat
    logging.debug(
        "Model fit to dataset.\nOriginal Inputs: {0}\nOriginal Observations: {1}\n"
        "Predicted Means: {2}\nPredicted STDs: {3}".format(
            x, y, *(gp.predict(x, return_std=True))))

    # 1. Plot 3 different confidence envelopes
    # -------------Plotting code -----------------

    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp,
                   confidence_intervals=[1.0, 2.0, 3.0],
                   type='both',
                   custom_x=x,
                   ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x,
                             Y_=y,
                             mark_incumbent=False,
                             highlight_datapoint=None,
                             highlight_label=None,
                             ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("lcb_1.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 2. Plot only LCB for one confidence envelope
    # -------------Plotting code -----------------

    boplot.set_rcparams(**{'legend.loc': 'upper left'})
    kappa = 3.0

    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp,
                   confidence_intervals=[kappa],
                   type='lower',
                   custom_x=x,
                   ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x,
                             Y_=y,
                             mark_incumbent=True,
                             highlight_datapoint=None,
                             highlight_label=None,
                             ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("lcb_2.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 3. Show LCB in parallel
    # -------------Plotting code -----------------

    if TOGGLE_PRINT:
        fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True, figsize=(18, 9))
    else:
        fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True)

    ax1.set_xlim(bounds["x"])
    ax1.set_ylim(bounds["gp_y"])
    ax1.grid()
    boplot.plot_gp(model=gp,
                   confidence_intervals=[kappa],
                   type='lower',
                   custom_x=x,
                   ax=ax1)
    boplot.plot_objective_function(ax=ax1)
    boplot.mark_observations(X_=x,
                             Y_=y,
                             mark_incumbent=True,
                             highlight_datapoint=None,
                             highlight_label=None,
                             ax=ax1)

    lcb_max = get_lcb_maximum(gp, kappa)
    logging.info("LCB Maximum at:{}".format(lcb_max))
    boplot.highlight_configuration(x=lcb_max[0],
                                   label=None,
                                   lloc='bottom',
                                   ax=ax1)
    ax1.set_xlabel(labels['xlabel'])
    ax1.set_ylabel(labels['gp_ylabel'])
    ax1.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    ax2.set_xlim(bounds["x"])
    ax2.set_ylim(bounds["acq_y"])
    ax2.grid()
    ax2.set_xlabel(labels['xlabel'])
    ax2.set_ylabel(labels['acq_ylabel'])
    ax2.set_title(r"Visualization of $LCB$", loc='left')

    boplot.highlight_configuration(x=lcb_max[0],
                                   label=None,
                                   lloc='bottom',
                                   ax=ax2)
    boplot.plot_acquisition_function(acquisition_functions['LCB'],
                                     0.0,
                                     gp,
                                     kappa,
                                     ax=ax2)

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("lcb_3.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 4. Mark next sample
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp,
                   confidence_intervals=[3.0],
                   type='lower',
                   custom_x=x,
                   ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x,
                             Y_=y,
                             mark_incumbent=True,
                             highlight_datapoint=None,
                             highlight_label=None,
                             ax=ax)

    lcb_max = get_lcb_maximum(gp, 3.0)
    logging.info("LCB Maximum at:{}".format(lcb_max))
    boplot.highlight_configuration(x=lcb_max[0],
                                   label=None,
                                   lloc='bottom',
                                   ax=ax)
    boplot.highlight_output(y=lcb_max[1], label='', lloc='left', ax=ax)
    boplot.annotate_y_edge(label=r'${\hat{c}}^{(t)}(%.2f)$' % lcb_max[0],
                           xy=lcb_max,
                           align='left',
                           ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    ax.legend().remove()

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("lcb_4.pdf")
    else:
        plt.show()
Exemplo n.º 9
0
def visualize_es(initial_design, init=None):
    """
    Visualize one-step of ES.
    :param initial_design: Method for initializing the GP, choice between 'uniform', 'random', and 'presentation'
    :param init: Number of datapoints to initialize GP with.
    :return: None
    """

    # 1. Show GP fit on initial dataset, 0 samples, histogram
    # 2. Show GP fit on initial dataset, 1 sample, histogram
    # 3. Show GP fit on initial dataset, 3 samples, histogram
    # 4. Show GP fit on initial dataset, 50 samples, histogram
    # 5. Show PDF derived from the histogram at 50 samples
    # 6. Mark maximum of the PDF as next configuration to be evaluated

    # a. Plot GP
    # b. Sample GP, mark minima, update histogram of lambda*
    # c. Repeat 2 for each sample.
    # d. Show results after multiple iterations

    boplot.set_rcparams(**{'figure.figsize': (22, 11)})

    # Initial setup
    # -------------------------------------------

    logging.debug("Visualizing ES with initial design {} and init {}".format(
        initial_design, init))
    # Initialize dummy dataset
    x, y = initialize_dataset(initial_design=initial_design, init=init)
    logging.debug(
        "Initialized dataset with:\nsamples {0}\nObservations {1}".format(
            x, y))

    # Fit GP to the currently available dataset
    gp = GPR(kernel=Matern())
    logging.debug("Fitting GP to\nx: {}\ny:{}".format(x, y))
    gp.fit(x, y)  # fit the model

    histogram_precision = 20
    X_ = boplot.get_plot_domain(precision=histogram_precision)
    nbins = X_.shape[0]
    logging.info("Creating histograms with {} bins".format(nbins))
    bin_range = (bounds['x'][0], bounds['x'][1] + 1 / histogram_precision)

    # -------------------------------------------

    def draw_samples(nsamples, ax1, ax2, show_min=False, return_pdf=False):
        if not nsamples:
            return
        seed2 = 1256
        seed3 = 65

        mu = gp.sample_y(X=X_, n_samples=nsamples, random_state=seed3)
        boplot.plot_gp_samples(mu=mu,
                               nsamples=nsamples,
                               precision=histogram_precision,
                               custom_x=X_,
                               show_min=show_min,
                               ax=ax1,
                               seed=seed2)
        data_h = X_[np.argmin(mu, axis=0), 0]
        logging.info("Shape of data_h is {}".format(data_h.shape))
        logging.debug("data_h is: {}".format(data_h))

        bins = ax2.hist(data_h,
                        bins=nbins,
                        range=bin_range,
                        density=return_pdf,
                        color='lightgreen',
                        edgecolor='black',
                        alpha=0.0 if return_pdf else 1.0)

        return bins

    # 1. Show GP fit on initial dataset, 0 samples, histogram
    # -------------------------------------------

    ax2_title = r'$p_{min}=P(\lambda=\lambda^*)$'

    bounds['acq_y'] = (0.0, 1.0)

    fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True)
    ax1.set_xlim(bounds['x'])
    ax1.set_ylim(bounds['gp_y'])
    ax2.set_xlim(bounds['x'])
    ax2.set_ylim(bounds['acq_y'])
    ax1.grid()
    ax2.grid()

    boplot.plot_objective_function(ax=ax1)
    boplot.plot_gp(model=gp, confidence_intervals=[3.0], ax=ax1, custom_x=x)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, ax=ax1)

    nsamples = 0
    draw_samples(nsamples=nsamples, ax1=ax1, ax2=ax2, show_min=True)

    # Plot uniform prior for p_min
    xplot = boplot.get_plot_domain()
    ylims = ax2.get_ylim()
    xlims = ax2.get_xlim()
    yupper = [(ylims[1] - ylims[0]) / (xlims[1] - xlims[0])] * xplot.shape[0]
    ax2.plot(xplot[:, 0], yupper, color='green', linewidth=2.0)
    ax2.fill_between(xplot[:, 0], ylims[0], yupper, color='lightgreen')

    ax1.legend().set_zorder(20)
    ax1.set_xlabel(labels['xlabel'])
    ax1.set_ylabel(labels['gp_ylabel'])
    ax1.set_title(r"Visualization of $\mathcal{G}^t$", loc='left')

    ax2.set_xlabel(labels['xlabel'])
    ax2.set_ylabel(r'$p_{min}$')
    ax2.set_title(ax2_title, loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig('es_1')
    else:
        plt.show()
    # -------------------------------------------

    # 2. Show GP fit on initial dataset, 1 sample, histogram
    # -------------------------------------------

    bounds['acq_y'] = (0.0, 5.0)
    ax2_title = r'Frequency of $\lambda=\hat{\lambda}^*$'

    fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True)
    ax1.set_xlim(bounds['x'])
    ax1.set_ylim(bounds['gp_y'])
    ax2.set_xlim(bounds['x'])
    ax2.set_ylim(bounds['acq_y'])
    ax1.grid()
    ax2.grid()

    boplot.plot_objective_function(ax=ax1)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, ax=ax1)

    nsamples = 1
    draw_samples(nsamples=nsamples, ax1=ax1, ax2=ax2, show_min=True)

    ax1.legend().set_zorder(20)
    ax1.set_xlabel(labels['xlabel'])
    ax1.set_ylabel(labels['gp_ylabel'])
    ax1.set_title(r"One sample from $\mathcal{G}^t$", loc='left')

    ax2.set_xlabel(labels['xlabel'])

    # ax2.set_ylabel(r'$p_{min}$')
    ax2.set_ylabel(r'Frequency')
    ax2.set_title(ax2_title, loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig('es_2')
    else:
        plt.show()

    # 3. Show GP fit on initial dataset, 10 samples, histogram
    # -------------------------------------------

    bounds['acq_y'] = (0.0, 10.0)
    ax2_title = r'Frequency of $\lambda=\hat{\lambda}^*$'

    fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True)
    ax1.set_xlim(bounds['x'])
    ax1.set_ylim(bounds['gp_y'])
    ax2.set_xlim(bounds['x'])
    ax2.set_ylim(bounds['acq_y'])
    ax1.grid()
    ax2.grid()

    boplot.plot_objective_function(ax=ax1)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, ax=ax1)

    nsamples = 10
    draw_samples(nsamples=nsamples, ax1=ax1, ax2=ax2)

    ax1.set_xlabel(labels['xlabel'])
    ax1.set_ylabel(labels['gp_ylabel'])
    ax1.set_title(r"Ten samples from $\mathcal{G}^t$", loc='left')

    ax2.set_xlabel(labels['xlabel'])

    # ax2.set_ylabel(r'$p_{min}$')
    ax2.set_ylabel(r'Frequency')
    ax2.set_title(ax2_title, loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig('es_3')
    else:
        plt.show()

    # -------------------------------------------

    # 4. Show GP fit on initial dataset, 200 samples, histogram
    # -------------------------------------------

    bounds["acq_y"] = (0.0, 20.0)
    ax2_title = r'Frequency of $\lambda=\hat{\lambda}^*$'

    fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True)
    ax1.set_xlim(bounds['x'])
    ax1.set_ylim(bounds['gp_y'])
    ax2.set_xlim(bounds['x'])
    ax2.set_ylim(bounds['acq_y'])
    ax1.grid()
    ax2.grid()

    boplot.plot_objective_function(ax=ax1)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, ax=ax1)

    nsamples = 200
    draw_samples(nsamples=nsamples, ax1=ax1, ax2=ax2)

    ax1.set_xlabel(labels['xlabel'])
    ax1.set_ylabel(labels['gp_ylabel'])
    ax1.set_title(r"200 samples from $\mathcal{G}^t$", loc='left')

    ax2.set_xlabel(labels['xlabel'])

    # ax2.set_ylabel(r'$p_{min}$')
    ax2.set_ylabel(r'Frequency')
    ax2.set_title(ax2_title, loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig('es_4')
    else:
        plt.show()
    # -------------------------------------------

    # 5. Show PDF derived from the histogram at 200 samples
    # -------------------------------------------

    ax2_title = "$\hat{P}(\lambda=\lambda^*)$"
    bounds["acq_y"] = (0.0, 1.0)

    fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True)
    ax1.set_xlim(bounds['x'])
    ax1.set_ylim(bounds['gp_y'])
    ax2.set_xlim(bounds['x'])
    ax2.set_ylim(bounds["acq_y"])
    ax1.grid()
    ax2.grid()

    boplot.plot_objective_function(ax=ax1)
    boplot.plot_gp(model=gp, confidence_intervals=[3.0], ax=ax1, custom_x=x)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, ax=ax1)

    nsamples = 200
    seed3 = 65

    mu = gp.sample_y(X=X_, n_samples=nsamples, random_state=seed3)
    data_h = X_[np.argmin(mu, axis=0), 0]

    kde = kd(kernel='gaussian', bandwidth=0.75).fit(data_h.reshape(-1, 1))
    xplot = boplot.get_plot_domain()
    ys = np.exp(kde.score_samples(xplot))

    ax2.plot(xplot, ys, color='green', lw=2.)
    ax2.fill_between(xplot[:, 0], ax2.get_ylim()[0], ys, color='lightgreen')

    ax1.set_xlabel(labels['xlabel'])
    ax1.set_ylabel(labels['gp_ylabel'])
    ax1.set_title(r"Visualization of $\mathcal{G}^t$", loc='left')

    ax2.set_xlabel(labels['xlabel'])
    ax2.set_ylabel(r'$p_{min}$')
    ax2.set_title(ax2_title, loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig('es_5')
    else:
        plt.show()

    # -------------------------------------------

    # 6. Mark maximum of the PDF as next configuration to be evaluated
    # -------------------------------------------

    ax2_title = "$\hat{P}(\lambda=\lambda^*)$"
    bounds["acq_y"] = (0.0, 1.0)

    fig, (ax1, ax2) = plt.subplots(2, 1, squeeze=True)
    ax1.set_xlim(bounds['x'])
    ax1.set_ylim(bounds['gp_y'])
    ax2.set_xlim(bounds['x'])
    ax2.set_ylim(bounds["acq_y"])
    ax1.grid()
    ax2.grid()

    boplot.plot_objective_function(ax=ax1)
    boplot.plot_gp(model=gp, confidence_intervals=[3.0], ax=ax1, custom_x=x)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, ax=ax1)

    nsamples = 200
    seed3 = 65

    mu = gp.sample_y(X=X_, n_samples=nsamples, random_state=seed3)
    data_h = X_[np.argmin(mu, axis=0), 0]

    kde = kd(kernel='gaussian', bandwidth=0.75).fit(data_h.reshape(-1, 1))
    xplot = boplot.get_plot_domain()
    ys = np.exp(kde.score_samples(xplot))

    idx_umax = np.argmax(ys)
    boplot.highlight_configuration(x=xplot[idx_umax],
                                   label='',
                                   ax=ax1,
                                   disable_ticks=True)
    boplot.annotate_x_edge(label=r'$\lambda^{(t)}$',
                           xy=(xplot[idx_umax], ax1.get_ylim()[0]),
                           ax=ax1,
                           align='top',
                           offset_param=1.5)
    boplot.highlight_configuration(x=xplot[idx_umax],
                                   label='',
                                   ax=ax2,
                                   disable_ticks=True)
    boplot.annotate_x_edge(label=r'$\lambda^{(t)}$',
                           xy=(xplot[idx_umax], ys[idx_umax]),
                           ax=ax2,
                           align='top',
                           offset_param=1.0)

    ax2.plot(xplot, ys, color='green', lw=2.)
    ax2.fill_between(xplot[:, 0], ax2.get_ylim()[0], ys, color='lightgreen')

    ax1.set_xlabel(labels['xlabel'])
    ax1.set_ylabel(labels['gp_ylabel'])
    ax1.set_title(r"Visualization of $\mathcal{G}^t$", loc='left')

    ax2.set_xlabel(labels['xlabel'])
    ax2.set_ylabel(r'$p_{min}$')
    ax2.set_title(ax2_title, loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig('es_6')
    else:
        plt.show()
Exemplo n.º 10
0
def visualize_pi(initial_design, init=None):
    """
    Visualize one-step of PI.
    :param initial_design: Method for initializing the GP, choice between 'uniform', 'random', and 'presentation'
    :param init: Number of datapoints to initialize GP with.
    :return: None
    """

    # 1. Plot GP fit on initial dataset
    # 2. Mark current incumbent
    # 3. Mark Zone of Probable Improvement
    # 4. Draw Vertical Normal at a good candidate for improvement
    # 5. Draw Vertical Normal at a bad candidate for improvement

    # boplot.set_rcparams(**{'legend.loc': 'lower left'})

    logging.debug("Visualizing PI with initial design {} and init {}".format(initial_design, init))
    # Initialize dummy dataset
    x, y = initialize_dataset(initial_design=initial_design, init=init)
    ymin_arg = np.argmin(y)
    ymin = y[ymin_arg]
    logging.debug("Initialized dataset with:\nsamples {0}\nObservations {1}".format(x, y))

    # Fit GP to the currently available dataset
    gp = GPR(kernel=Matern())
    logging.debug("Fitting GP to\nx: {}\ny:{}".format(x, y))
    gp.fit(x, y)  # fit the model
    mu_star_t_xy = get_mu_star(gp)
    logging.info("Mu-star at time t: {}".format(mu_star_t_xy))

    # noinspection PyStringFormat
    logging.debug("Model fit to dataset.\nOriginal Inputs: {0}\nOriginal Observations: {1}\n"
                  "Predicted Means: {2}\nPredicted STDs: {3}".format(x, y, *(gp.predict(x, return_std=True))))

    # 1. Plot GP fit on initial dataset
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=False, highlight_datapoint=None, highlight_label=None, ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("pi_1.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 2. Mark current incumbent
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("pi_2.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 3. Mark Zone of Probable Improvement
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)
    boplot.darken_graph(y=ymin, ax=ax)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    ax.legend().remove()

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("pi_3.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 4. Draw Vertical Normal at a good candidate for improvement
    # -------------Plotting code -----------------
    candidate = 5.0
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)
    boplot.darken_graph(y=ymin, ax=ax)

    vcurve_x, vcurve_y, mu = boplot.draw_vertical_normal(gp=gp, incumbenty=ymin, ax=ax, xtest=candidate, xscale=2.0, yscale=1.0)

    ann_x = candidate + 0.5 * (np.max(vcurve_x) - candidate) / 2
    ann_y = mu - 0.25

    arrow_x = ann_x
    arrow_y = ann_y - 3.0

    label = "{:.2f}".format(candidate)

    ax.annotate(
        s=r'$PI^{(t)}(%s)$' % label, xy=(ann_x, ann_y), xytext=(arrow_x, arrow_y),
        arrowprops={'arrowstyle': 'fancy'},
        weight='heavy', color='darkgreen', zorder=15
    )

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    ax.legend().remove()

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("pi_4.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 5. Draw Vertical Normal at a bad candidate for improvement
    # -------------Plotting code -----------------

    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x, Y_=y, mark_incumbent=True, highlight_datapoint=None, highlight_label=None, ax=ax)
    boplot.darken_graph(y=ymin, ax=ax)

    candidate = 5.0
    vcurve_x, vcurve_y, mu = boplot.draw_vertical_normal(
        gp=gp, incumbenty=ymin, ax=ax, xtest=candidate,
        xscale=2.0, yscale=1.0
    )

    ann_x = candidate + 0.5 * (np.max(vcurve_x) - candidate) / 2
    ann_y = mu - 0.25

    arrow_x = ann_x
    arrow_y = ann_y - 3.0

    label = "{:.2f}".format(candidate)

    ax.annotate(
        s=r'$PI^{(t)}(%s)$' % label, xy=(ann_x, ann_y), xytext=(arrow_x, arrow_y),
        arrowprops={'arrowstyle': 'fancy'},
        weight='heavy', color='darkgreen', zorder=15
    )

    candidate = 8.0
    vcurve_x, vcurve_y, mu = boplot.draw_vertical_normal(
        gp=gp, incumbenty=ymin, ax=ax, xtest=candidate,
        xscale=2.0, yscale=1.0
    )

    ann_x = candidate + 0.5 * (np.max(vcurve_x) - candidate) / 2
    ann_y = mu

    arrow_x = ann_x
    arrow_y = ann_y - 3.0

    label = "{:.2f}".format(candidate)

    ax.annotate(s=r'$PI^{(t)}(%s)$' % label, xy=(ann_x, ann_y), xytext=(arrow_x, arrow_y),
                arrowprops={'arrowstyle': 'fancy'},
                weight='heavy', color='darkgreen', zorder=15)

    ax.legend().set_zorder(20)
    ax.set_xlabel(labels['xlabel'])
    ax.set_ylabel(labels['gp_ylabel'])
    ax.set_title(r"Visualization of $\mathcal{G}^{(t)}$", loc='left')

    ax.legend().remove()

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig("pi_5.pdf")
    else:
        plt.show()
Exemplo n.º 11
0
def visualize_ts(initial_design, init=None):
    """
    Visualize one-step of TS.
    :param initial_design: Method for initializing the GP, choice between 'uniform', 'random', and 'presentation'
    :param init: Number of datapoints to initialize GP with.
    :return: None
    """

    # 1. Plot GP fit on initial dataset
    # 2. Plot one sample
    # 3. Mark minimum of sample

    boplot.set_rcparams(**{'legend.loc': 'upper left'})

    logging.debug("Visualizing EI with initial design {} and init {}".format(
        initial_design, init))
    # Initialize dummy dataset
    x, y = initialize_dataset(initial_design=initial_design, init=init)
    ymin_arg = np.argmin(y)
    ymin = y[ymin_arg]
    logging.debug(
        "Initialized dataset with:\nsamples {0}\nObservations {1}".format(
            x, y))

    # Fit GP to the currently available dataset
    gp = GPR(kernel=Matern())
    logging.debug("Fitting GP to\nx: {}\ny:{}".format(x, y))
    gp.fit(x, y)  # fit the model

    # noinspection PyStringFormat
    logging.debug(
        "Model fit to dataset.\nOriginal Inputs: {0}\nOriginal Observations: {1}\n"
        "Predicted Means: {2}\nPredicted STDs: {3}".format(
            x, y, *(gp.predict(x, return_std=True))))

    # 1. Plot GP fit on initial dataset
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp,
                   confidence_intervals=[1.0, 2.0, 3.0],
                   custom_x=x,
                   ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x,
                             Y_=y,
                             mark_incumbent=False,
                             highlight_datapoint=None,
                             highlight_label=None,
                             ax=ax)

    ax.legend().set_zorder(zorders['legend'])
    ax.set_xlabel(labels['xlabel'])

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig(f"{OUTPUT_DIR}/ts_1.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 2. Plot one sample
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    boplot.plot_gp(model=gp,
                   confidence_intervals=[1.0, 2.0, 3.0],
                   custom_x=x,
                   ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x,
                             Y_=y,
                             mark_incumbent=False,
                             highlight_datapoint=None,
                             highlight_label=None,
                             ax=ax)

    # Sample from the GP
    nsamples = 1
    seed2 = 2
    seed3 = 1375
    X_ = boplot.get_plot_domain(precision=None)
    mu = gp.sample_y(X=X_, n_samples=nsamples, random_state=seed3)
    boplot.plot_gp_samples(mu=mu,
                           nsamples=nsamples,
                           precision=None,
                           custom_x=X_,
                           show_min=False,
                           ax=ax,
                           seed=seed2)

    ax.legend().set_zorder(zorders['legend'])
    ax.set_xlabel(labels['xlabel'])

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig(f"{OUTPUT_DIR}/ts_2.pdf")
    else:
        plt.show()
    # -------------------------------------------

    # 3. Mark minimum of sample
    # -------------Plotting code -----------------
    fig, ax = plt.subplots(1, 1, squeeze=True)
    ax.set_xlim(bounds["x"])
    ax.set_ylim(bounds["gp_y"])
    ax.grid()
    # boplot.plot_gp(model=gp, confidence_intervals=[2.0], custom_x=x, ax=ax)
    boplot.plot_objective_function(ax=ax)
    boplot.mark_observations(X_=x,
                             Y_=y,
                             mark_incumbent=False,
                             highlight_datapoint=None,
                             highlight_label=None,
                             ax=ax)

    # Sample from the GP
    nsamples = 1
    X_ = boplot.get_plot_domain(precision=None)
    mu = gp.sample_y(X=X_, n_samples=nsamples, random_state=seed3)
    colors['highlighted_observations'] = 'red'  # Special for Thompson Sampling
    boplot.plot_gp_samples(mu=mu,
                           nsamples=nsamples,
                           precision=None,
                           custom_x=X_,
                           show_min=True,
                           ax=ax,
                           seed=seed2)

    min_idx = np.argmin(mu, axis=0)
    candidate = X_[min_idx]
    cost = mu[min_idx]

    boplot.highlight_configuration(x=np.array([candidate]),
                                   label='',
                                   lloc='bottom',
                                   disable_ticks=True,
                                   ax=ax)
    boplot.annotate_x_edge(label=r'$\lambda^{(t)}$',
                           xy=(candidate, cost),
                           align='top',
                           ax=ax)
    boplot.highlight_output(y=np.array([cost]),
                            label='',
                            lloc='left',
                            disable_ticks=True,
                            ax=ax)
    boplot.annotate_y_edge(label=r'$g(\lambda^{(t)})$',
                           xy=(candidate, cost),
                           align='left',
                           ax=ax)

    ax.legend().set_zorder(zorders['legend'])
    ax.set_xlabel(labels['xlabel'])

    plt.tight_layout()
    if TOGGLE_PRINT:
        plt.savefig(f"{OUTPUT_DIR}/ts_3.pdf")
    else:
        plt.show()