Exemplo n.º 1
0
def import_bo():
    """
    Test if edbo is installed and the main method can
    be instantiated
    """
    
    from edbo.bro import BO
    bo = BO()
    
    return len(bo.obj.domain) == 0
Exemplo n.º 2
0
def BO_pred(acq_func, plot=False, return_='pred', append=False, init='external'):
    
    # Experiment index
    X = np.linspace(0,1,1000)
    exindex = pd.DataFrame([[x, f(x)] for x in X], columns=['x', 'f(x)'])
    training_points = [50, 300, 500, 900]
    
    # Instatiate BO class
    bo = BO(exindex=exindex,
            domain=exindex.drop('f(x)', axis=1),
            results=exindex.iloc[training_points],
            acquisition_function=acq_func,
            init_method=init,
            lengthscale_prior=[GammaPrior(1.2,1.1), 0.2],
            noise_prior=None,
            batch_size=random.sample([1,2,3,4,5,6,7,8,9,10],1)[0],
            fast_comp=True,
            gpu=True)
    
    bo.run(append=append)

    # Check prediction
    if return_ == 'pred':
        
        try:
            bo.model.predict(to_torch(bo.obj.domain))                          # torch.tensor
            bo.model.predict(bo.obj.domain.values)                             # numpy.array
            bo.model.predict(list(bo.obj.domain.values))                       # list
            bo.model.predict(exindex.drop('f(x)', axis=1))                     # pandas.DataFrame
        except:
            return False
        
        pred = bo.model.predict(bo.obj.domain.iloc[[32]])
        pred = bo.obj.scaler.unstandardize(pred)
        return (pred[0] - 1.33) < 0.1
    
    # Check predictive postrior variance
    elif return_ == 'var':
        
        try:
            bo.model.predict(to_torch(bo.obj.domain))                          # torch.tensor
            bo.model.predict(bo.obj.domain.values)                             # numpy.array
            bo.model.predict(list(bo.obj.domain.values))                       # list
            bo.model.predict(exindex.drop('f(x)', axis=1))                     # pandas.DataFrame
        except:
            return False
        
        var = bo.model.variance(bo.obj.domain.iloc[[32]])
        return (var[0] - 0.04) < 0.1
    
    # Make sure sampling works with tensors, arrays, lists, and DataFrames
    elif return_ == 'sample':
        try:
            bo.model.sample_posterior(to_torch(bo.obj.domain))                 # torch.tensor
            bo.model.sample_posterior(bo.obj.domain.values)                    # numpy.array
            bo.model.sample_posterior(list(bo.obj.domain.values))              # list
            bo.model.sample_posterior(exindex.drop('f(x)', axis=1))            # pandas.DataFrame
            return True
        except:
            return False
        
    # Plot model
    elif return_ == 'plot':
        next_points = bo.obj.get_results(bo.proposed_experiments)
        mean = bo.obj.scaler.unstandardize(bo.model.predict(bo.obj.domain))
        std = np.sqrt(bo.model.variance(bo.obj.domain)) * bo.obj.scaler.std * 2
        samples = bo.obj.scaler.unstandardize(bo.model.sample_posterior(bo.obj.domain, batch_size=3))

        plt.figure(1, figsize=(6,6))

        # Model mean and standard deviation
        plt.subplot(211)
        plt.plot(X, exindex['f(x)'], color='black')
        plt.plot(X, mean, label='GP')
        plt.fill_between(X, mean-std, mean+std, alpha=0.4)
        # Known results and next selected point
        plt.scatter(bo.obj.results_input()['x'], bo.obj.results_input()['f(x)'], color='black', label='known')
        plt.scatter(next_points['x'],next_points['f(x)'], color='red', label='next_experiments')
        plt.ylabel('f(x)')
        # Samples
        plt.subplot(212)
        for sample in samples:
            plt.plot(X, torch_to_numpy(sample, gpu=True))
        plt.xlabel('x')
        plt.ylabel('Posterior Samples')
        plt.show()

        return True
    
    elif return_ == 'simulate':
        
        if init != 'external':
            bo.init_seq.batch_size = random.sample([2,3,4,5,6,7,8,9,10],1)[0]
            
        bo.simulate(iterations=5)
        bo.plot_convergence()
        bo.model.regression()
        
        return True
Exemplo n.º 3
0
def BO_pred(acq_func,
            plot=False,
            return_='pred',
            append=False,
            init='external',
            fast_comp=True):

    # Experiment index
    X = np.linspace(0, 1, 1000)
    exindex = pd.DataFrame([[x, f(x)] for x in X], columns=['x', 'f(x)'])
    training_points = [50, 300, 500, 900]

    # Instatiate BO class
    bo = BO(exindex=exindex,
            domain=exindex.drop('f(x)', axis=1),
            results=exindex.iloc[training_points],
            acquisition_function=acq_func,
            init_method=init,
            lengthscale_prior=[GammaPrior(1.2, 1.1), 0.2],
            noise_prior=None,
            batch_size=random.sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1)[0],
            fast_comp=fast_comp)

    bo.run(append=append)

    # Check prediction
    if return_ == 'pred':

        try:
            bo.model.predict(to_torch(bo.obj.domain))  # torch.tensor
            bo.model.predict(bo.obj.domain.values)  # numpy.array
            bo.model.predict(list(bo.obj.domain.values))  # list
            bo.model.predict(exindex.drop('f(x)', axis=1))  # pandas.DataFrame
        except:
            return False

        pred = bo.model.predict(bo.obj.domain.iloc[[32]])
        pred = bo.obj.scaler.unstandardize(pred)
        return (pred[0] - 1.33) < 0.1

    # Check predictive postrior variance
    elif return_ == 'var':

        try:
            bo.model.predict(to_torch(bo.obj.domain))  # torch.tensor
            bo.model.predict(bo.obj.domain.values)  # numpy.array
            bo.model.predict(list(bo.obj.domain.values))  # list
            bo.model.predict(exindex.drop('f(x)', axis=1))  # pandas.DataFrame
        except:
            return False

        var = bo.model.variance(bo.obj.domain.iloc[[32]])
        return (var[0] - 0.04) < 0.1

    # Make sure sampling works with tensors, arrays, lists, and DataFrames
    elif return_ == 'sample':
        try:
            bo.model.sample_posterior(to_torch(bo.obj.domain))  # torch.tensor
            bo.model.sample_posterior(bo.obj.domain.values)  # numpy.array
            bo.model.sample_posterior(list(bo.obj.domain.values))  # list
            bo.model.sample_posterior(exindex.drop('f(x)',
                                                   axis=1))  # pandas.DataFrame
            return True
        except:
            return False

    elif return_ == 'simulate':

        if init != 'external':
            bo.init_seq.batch_size = random.sample(
                [2, 3, 4, 5, 6, 7, 8, 9, 10], 1)[0]

        bo.simulate(iterations=5)

        return True

    elif return_ == 'none':
        return True