## Basic usage with simulated data
set.seed(1234)
t <- runif(1000, -10, 10)
y <- 2*sin(t) + -0.06*t^2 + rnorm(length(t))
model_fit <- lgspline(t, y)
plot(model_fit)
## Find global maximum and minimum
max_point <- find_extremum(model_fit)
min_point <- find_extremum(model_fit, minimize = TRUE)
abline(v = max_point$t, col = 'blue') # Add maximum point
abline(v = min_point$t, col = 'red') # Add minimum point
## Advanced usage: custom objective functions
# expected improvement acquisition function
ei_custom_objective_function = function(mu, sigma, y_best, ...) {
d <- y_best - mu
d * pnorm(d/sigma) + sigma * dnorm(d/sigma)
}
# derivative of ei
ei_custom_objective_derivative = function(mu, sigma, y_best, d_mu, ...) {
d <- y_best - mu
z <- d/sigma
d_z <- -d_mu/sigma
pnorm(z)*d_mu - d*dnorm(z)*d_z + sigma*z*dnorm(z)*d_z
}
## Single iteration of Bayesian optimization
post_draw <- generate_posterior(model_fit)
acq <- find_extremum(model_fit,
stochastic = TRUE, # Enable stochastic exploration
B_predict = post_draw$post_draw_coefficients,
sigmasq_predict = post_draw$post_draw_sigmasq,
custom_objective_function = ei_custom_objective_function,
custom_objective_derivative = ei_custom_objective_derivative)
abline(v = acq$t, col = 'green') # Add acquisition point
Run the code above in your browser using DataLab