Gradient-Based Methods for Minimizing Test Functions
#| '!! shinylive warning !!': |
#| shinylive does not work in self-contained HTML documents.
#| Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 870
library(shiny)
### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
env = parent.frame(), quoted = FALSE) {
func <- shiny::exprToFunction(expr, env, quoted)
shiny::renderImage({
info <- shiny::getCurrentOutputInfo()
w <- if (is.numeric(width)) width else info$width()
h <- if (is.numeric(height)) height else info$height()
shiny::req(w > 0, h > 0)
pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
if (is.null(pr)) pr <- 1
f <- tempfile(fileext = ".png")
dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
on.exit(grDevices::dev.off(dev), add = TRUE)
grDevices::dev.control(displaylist = "enable")
v <- withVisible(func())
if (v$visible) print(v$value)
list(src = f, contentType = "image/png", width = w, height = h,
coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
}, deleteFile = TRUE)
}
## ---------------------------------------------------------------- objectives
mk <- function(label, fv, xlim, ylim, start, xstar) {
force(fv)
list(label = label, fv = fv, f = function(p) fv(p[1], p[2]),
xlim = xlim, ylim = ylim, start = start,
xstar = matrix(xstar, ncol = 2))
}
FNS <- list(
quad = mk(
"(a) Well-conditioned quadratic",
function(x, y) 0.5 * (2 * (x - 1)^2 + 1.6 * (x - 1) * (y - 1) +
2 * (y - 1)^2),
c(-3, 4), c(-3, 4), c(-2, 3), c(1, 1)
),
banana = mk(
"(b) Rosenbrock banana (narrow curved ridge)",
function(x, y) (1 - x)^2 + 100 * (y - x^2)^2,
c(-2, 2), c(-1, 3), c(-1.2, 1), c(1, 1)
),
mix = mk(
"(c) Highly correlated, two modes",
function(x, y) {
rho <- 0.9; den <- 1 - rho^2
q <- function(u, v) (u^2 - 2 * rho * u * v + v^2) / den
-log(exp(-0.5 * q(x - 1.2, y - 1.2)) +
0.6 * exp(-0.5 * q(x + 1.5, y + 1.5) / 1.5) + 1e-12)
},
c(-4, 4), c(-4, 4), c(-3, -0.5), c(1.2, 1.2)
),
himmel = mk(
"(d) Himmelblau (four global minima)",
function(x, y) (x^2 + y - 11)^2 + (x + y^2 - 7)^2,
c(-5, 5), c(-5, 5), c(-4, 4),
rbind(c(3, 2), c(-2.805118, 3.131312),
c(-3.779310, -3.283186), c(3.584428, -1.848126))
),
beale = mk(
"(e) Beale (flat plateau, sharp valley)",
function(x, y) (1.5 - x + x * y)^2 + (2.25 - x + x * y^2)^2 +
(2.625 - x + x * y^3)^2,
c(-4.5, 4.5), c(-4.5, 4.5), c(-1, 1), c(3, 0.5)
),
rastrigin = mk(
"(f) Rastrigin (many local minima)",
function(x, y) 20 + x^2 - 10 * cos(2 * pi * x) +
y^2 - 10 * cos(2 * pi * y),
c(-5.12, 5.12), c(-5.12, 5.12), c(-3.1, 4.2), c(0, 0)
)
)
## default learning rates for the momentum method: a fixed step has to suit
## the scale of each function (larger values diverge on (b), (d) and (e))
ETA <- c(quad = 0.1, banana = 0.002, mix = 0.03, himmel = 0.01,
beale = 0.01, rastrigin = 0.003)
## ------------------------------------------------- numerical derivatives
num_grad <- function(f, x) {
h <- 1e-5 * (1 + abs(x))
g <- numeric(2)
for (i in 1:2) {
e <- numeric(2); e[i] <- h[i]
g[i] <- (f(x + e) - f(x - e)) / (2 * h[i])
}
g
}
num_hess <- function(f, x) {
h <- 1e-4 * (1 + abs(x))
H <- matrix(0, 2, 2)
for (i in 1:2) for (j in i:2) {
ei <- numeric(2); ei[i] <- h[i]
ej <- numeric(2); ej[j] <- h[j]
H[i, j] <- (f(x + ei + ej) - f(x + ei - ej) -
f(x - ei + ej) + f(x - ei - ej)) / (4 * h[i] * h[j])
H[j, i] <- H[i, j]
}
H
}
## --------------------------------------------------- Wolfe line search
line_search <- function(f, g, x, d, a0 = 1, c1 = 1e-4, c2 = 0.9) {
f0 <- f(x); gd0 <- sum(g * d)
if (!is.finite(gd0) || gd0 >= 0) return(list(alpha = 0, ok = FALSE))
lo <- 0; hi <- Inf; a <- a0
for (it in 1:60) {
fa <- f(x + a * d)
if (!is.finite(fa) || fa > f0 + c1 * a * gd0) {
hi <- a; a <- 0.5 * (lo + hi)
} else {
ga <- num_grad(f, x + a * d)
if (sum(ga * d) < c2 * gd0) {
lo <- a
a <- if (is.finite(hi)) 0.5 * (lo + hi) else min(2 * a, 1e4)
} else {
return(list(alpha = a, ok = TRUE))
}
}
if (a < 1e-14) return(list(alpha = 0, ok = FALSE))
}
list(alpha = a, ok = (a > 0))
}
## ------------------------------------------------------------- algorithms
run_alg <- function(alg, FN, x0, maxit = 60, tol = 1e-6,
eta = 0.01, beta = 0.9, alpha = 0.1, beta2 = 0.999) {
f <- FN$f
## no line search: a fixed step needs many more iterations
if (alg %in% c("mom", "adam")) maxit <- 200
X <- matrix(NA_real_, maxit + 1, 2); G <- matrix(NA_real_, maxit + 1, 2)
D <- matrix(NA_real_, maxit + 1, 2); Fv <- rep(NA_real_, maxit + 1)
AL <- rep(NA_real_, maxit + 1)
x <- x0; B <- diag(2)
g_prev <- NULL; d_prev <- NULL; s_prev <- NULL; v <- c(0, 0)
m <- c(0, 0); m2 <- c(0, 0) # Adam's averages of g and g^2
n <- 0; note <- "maximum number of iterations reached"
for (k in seq_len(maxit)) {
if (any(!is.finite(x)) || max(abs(x)) > 1e6) { note <- "diverged"; break }
g <- num_grad(f, x); gn <- sqrt(sum(g^2))
X[k, ] <- x; G[k, ] <- g; Fv[k] <- f(x); n <- k
if (!is.finite(gn)) { note <- "diverged"; break }
if (gn < tol) { note <- "converged (||grad|| < 1e-6)"; break }
if (alg == "mom") {
## heavy ball: the step keeps a fraction beta of the previous step;
## no line search, the learning rate eta is fixed
v <- beta * v - eta * g
D[k, ] <- v; AL[k] <- eta
x <- x + v
next
}
if (alg == "adam") {
## Adam: momentum on g, divided coordinate-wise by the root of a running
## average of g^2, so each coordinate moves about alpha per step
## whatever the scale of f; both averages are bias-corrected
m <- beta * m + (1 - beta) * g
m2 <- beta2 * m2 + (1 - beta2) * g^2
v <- -alpha * (m / (1 - beta^k)) / (sqrt(m2 / (1 - beta2^k)) + 1e-8)
D[k, ] <- v; AL[k] <- alpha
x <- x + v
next
}
if (alg == "nr") {
H <- num_hess(f, x); H <- (H + t(H)) / 2
ev <- eigen(H, symmetric = TRUE, only.values = TRUE)$values
delta <- 1e-3 * max(1, max(abs(ev)))
tau <- max(0, delta - min(ev))
d <- tryCatch(solve(H + tau * diag(2), -g), error = function(e) -g)
} else if (alg == "gd") {
d <- -g
} else if (alg == "cg") {
if (is.null(d_prev)) {
d <- -g
} else {
y <- g - g_prev
beta <- max(0, sum(g * y) / max(sum(g_prev^2), 1e-300)) # PR+
d <- -g + beta * d_prev
}
if (sum(g * d) > -1e-12) d <- -g # restart
} else { # BFGS
if (!is.null(s_prev)) {
y <- g - g_prev; sy <- sum(s_prev * y)
if (sy > 1e-10) {
rho <- 1 / sy
V <- diag(2) - rho * outer(s_prev, y)
B <- V %*% B %*% t(V) + rho * outer(s_prev, s_prev)
}
}
d <- -as.vector(B %*% g)
if (sum(g * d) > -1e-12) { B <- diag(2); d <- -g }
}
ls <- line_search(f, g, x, d)
D[k, ] <- d; AL[k] <- ls$alpha
if (ls$alpha <= 0) { note <- "line search failed (flat or non-descent)"; break }
s_prev <- ls$alpha * d; g_prev <- g; d_prev <- d
x <- x + s_prev
}
list(X = X[1:n, , drop = FALSE], G = G[1:n, , drop = FALSE],
D = D[1:n, , drop = FALSE], F = Fv[1:n], A = AL[1:n],
n = n, note = note)
}
ALGS <- c("Safeguarded Newton (modified Hessian + line search)" = "nr",
"Gradient descent + line search" = "gd",
"Conjugate gradient (PR+)" = "cg",
"BFGS (quasi-Newton)" = "bfgs",
"Momentum (heavy ball, fixed step)" = "mom",
"Adam (step scaled per coordinate)" = "adam")
## ---------------------------- widen the data box to the device aspect ratio
expand_box <- function(xlim, ylim, pin) {
if (length(pin) != 2 || any(!is.finite(pin)) || any(pin <= 0))
return(list(xlim = xlim, ylim = ylim))
r <- pin[1] / pin[2]
wd <- diff(xlim); ht <- diff(ylim)
if (wd / ht < r) {
w <- ht * r; m <- mean(xlim); xlim <- m + c(-0.5, 0.5) * w
} else {
h <- wd / r; m <- mean(ylim); ylim <- m + c(-0.5, 0.5) * h
}
list(xlim = xlim, ylim = ylim)
}
## --------------------------------------------------------------------- UI
## an icon-only playback button; the title shows as a tooltip
ctrl_btn <- function(id, icon_name, title, class = "btn-default")
actionButton(id, NULL, icon = icon(icon_name), title = title, class = class,
style = "flex: 1; padding: 6px 0;")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
width = 4,
selectInput("fn", "objective function",
setNames(names(FNS), sapply(FNS, `[[`, "label"))),
selectInput("alg", "algorithm", ALGS),
div(style = "display: flex; gap: 10px;",
div(style = "flex: 1;",
numericInput("x1", HTML("starting x<sub>1</sub>"),
value = FNS[[1]]$start[1], step = 0.5,
width = "100%")),
div(style = "flex: 1;",
numericInput("x2", HTML("starting x<sub>2</sub>"),
value = FNS[[1]]$start[2], step = 0.5,
width = "100%"))),
helpText("Or click inside the contour plot to choose a new ",
"starting value."),
selectInput("compare", "overlay the path of",
c("none" = "none", ALGS)),
## settings of momentum and Adam, each shown when its method is used;
## beta is shared (Adam's beta_1 plays the role of the momentum beta)
conditionalPanel(
"['mom', 'adam'].includes(input.alg) || ['mom', 'adam'].includes(input.compare)",
div(style = "display: flex; gap: 10px;",
conditionalPanel(
"input.alg == 'mom' || input.compare == 'mom'", style = "flex: 1;",
numericInput("eta", HTML("momentum η"),
value = ETA[[1]], min = 0, step = 0.001,
width = "100%")),
conditionalPanel(
"input.alg == 'adam' || input.compare == 'adam'", style = "flex: 1;",
numericInput("alpha", HTML("Adam α"),
value = 0.1, min = 0, step = 0.01, width = "100%")),
div(style = "flex: 1;",
numericInput("beta", HTML("β (Adam β<sub>1</sub>)"),
value = 0.9, min = 0, max = 0.999, step = 0.05,
width = "100%")))),
checkboxInput("autoplay", "autoplay when the start changes", TRUE),
sliderInput("k", "iteration", min = 0, max = 1, value = 0, step = 1),
div(style = "display: flex; gap: 4px;",
ctrl_btn("first", "backward-fast", "Back to the start"),
ctrl_btn("back", "backward-step", "One step back"),
ctrl_btn("play", "play", "Play", class = "btn-primary"),
ctrl_btn("pause", "pause", "Pause"),
ctrl_btn("step", "forward-step", "One step forward"),
ctrl_btn("toend", "forward-fast", "To the end")),
hr(),
helpText("Try gradient descent on the Rosenbrock banana, overlaid ",
"with BFGS or safeguarded Newton: gradient descent zig-zags ",
"across the curved valley, while the curvature-aware methods ",
"follow it. On Himmelblau and Rastrigin, click different ",
"starting points to see which minimum each method finds.")
),
mainPanel(
width = 8,
plotOutput("contour", click = "click", height = "500px"),
## details of the iterations, shown under the plot
hr(),
div(style = "max-width: 560px;",
tableOutput("tab"),
htmlOutput("note"))
)
)
)
## ----------------------------------------------------------------- server
server <- function(input, output, session) {
FN <- reactive(FNS[[input$fn]])
playing <- reactiveVal(FALSE)
play_ms <- 900
set_start <- function(p) {
updateNumericInput(session, "x1", value = round(p[1], 2))
updateNumericInput(session, "x2", value = round(p[2], 2))
}
## a new objective moves the start to its default; clicking the contour
## plot moves it to the clicked point
observeEvent(input$fn, {
set_start(FNS[[input$fn]]$start)
updateNumericInput(session, "eta", value = ETA[[input$fn]])
}, ignoreInit = TRUE)
observeEvent(input$click, {
p <- c(input$click$x, input$click$y)
if (all(is.finite(p))) set_start(p)
})
start <- reactive({
req(is.finite(input$x1), is.finite(input$x2))
c(input$x1, input$x2)
})
## settings of momentum and Adam (ignored by the others)
mom_par <- reactive({
eta <- if (is.finite(input$eta) && input$eta > 0) input$eta else ETA[[input$fn]]
alpha <- if (is.finite(input$alpha) && input$alpha > 0) input$alpha else 0.1
beta <- if (is.finite(input$beta)) min(max(input$beta, 0), 0.999) else 0.9
list(eta = eta, beta = beta, alpha = alpha)
})
path <- reactive(run_alg(input$alg, FN(), start(),
eta = mom_par()$eta, beta = mom_par()$beta,
alpha = mom_par()$alpha))
## a second algorithm from the same start, shown for comparison
ref <- reactive({
if (input$compare == "none" || input$compare == input$alg) return(NULL)
run_alg(input$compare, FN(), start(),
eta = mom_par()$eta, beta = mom_par()$beta,
alpha = mom_par()$alpha)
})
## current iteration, clamped to the length of the path
k <- reactive(min(as.integer(input$k), path()$n - 1))
## a new path restarts the display at iteration 0
observeEvent(path(), {
updateSliderInput(session, "k", max = max(1, path()$n - 1), value = 0)
playing(isTRUE(input$autoplay) && path()$n > 1)
})
go_to <- function(i) {
updateSliderInput(session, "k", value = max(0, min(i, path()$n - 1)))
}
observeEvent(input$play, {
if (k() >= path()$n - 1) go_to(0)
if (path()$n > 1) playing(TRUE)
})
observeEvent(input$pause, playing(FALSE))
observeEvent(input$step, { playing(FALSE); go_to(k() + 1) })
observeEvent(input$back, { playing(FALSE); go_to(k() - 1) })
observeEvent(input$first, { playing(FALSE); go_to(0) })
observeEvent(input$toend, { playing(FALSE); go_to(path()$n - 1) })
observe({
if (!isTRUE(playing())) return()
kk <- isolate(k())
if (kk >= isolate(path()$n) - 1) { playing(FALSE); return() }
invalidateLater(play_ms, session)
isolate(go_to(kk + 1))
})
output$contour <- renderPlot({
FNc <- FN(); P <- path(); RP <- ref(); kk <- k() + 1L
par(mar = c(7, 4, 2, 1)) # room for the legend below
plot.new()
bx <- expand_box(FNc$xlim, FNc$ylim, par("pin"))
plot.window(xlim = bx$xlim, ylim = bx$ylim, xaxs = "i", yaxs = "i")
xs <- seq(bx$xlim[1], bx$xlim[2], length.out = 180)
ys <- seq(bx$ylim[1], bx$ylim[2], length.out = 180)
z <- outer(xs, ys, FNc$fv)
zf <- z[is.finite(z)]
lv <- unique(quantile(zf, probs = seq(0, 1, length.out = 30)^1.7))
contour(xs, ys, z, levels = lv, add = TRUE, col = "grey70",
drawlabels = FALSE)
axis(1); axis(2); box()
title(main = paste0(names(ALGS)[ALGS == input$alg], " on ",
sub("^\\([a-f]\\) ", "", FNc$label)),
xlab = expression(x[1]), ylab = expression(x[2]), cex.main = 1)
points(FNc$xstar[, 1], FNc$xstar[, 2], pch = 3, col = "darkgreen",
lwd = 2, cex = 1.2)
## the comparison path, drawn underneath
if (!is.null(RP)) {
Q <- RP$X[seq_len(min(kk, RP$n)), , drop = FALSE]
if (nrow(Q) > 1) lines(Q[, 1], Q[, 2], col = "grey45", lwd = 2, lty = 2)
points(Q[, 1], Q[, 2], pch = 21, bg = "grey85", col = "grey45",
cex = 0.9)
}
X <- P$X
if (kk > 1) lines(X[1:kk, 1], X[1:kk, 2], col = "steelblue", lwd = 2)
points(X[1:kk, 1], X[1:kk, 2], pch = 21, bg = "steelblue", cex = 1.1)
cur <- X[kk, ]
inside <- cur[1] >= bx$xlim[1] && cur[1] <= bx$xlim[2] &&
cur[2] >= bx$ylim[1] && cur[2] <= bx$ylim[2]
if (inside) {
## Arrow along -grad f (steepest descent), of fixed length on screen.
## The gradient is a covector, so its on-screen components are obtained
## by multiplying by the units-per-inch factors; the box is widened to
## the device aspect ratio, so here the two factors agree anyway.
g <- -P$G[kk, ]
upi <- c(diff(par("usr")[1:2]) / par("pin")[1],
diff(par("usr")[3:4]) / par("pin")[2])
gs <- g * upi
if (sqrt(sum(g^2)) > 1e-6 && sqrt(sum(gs^2)) > 0) {
d <- 0.45 * gs / sqrt(sum(gs^2)) * upi # 0.45 inch long
arrows(cur[1], cur[2], cur[1] + d[1], cur[2] + d[2],
col = "#E8820C", lwd = 3, length = 0.09)
}
points(cur[1], cur[2], pch = 21, bg = "firebrick", cex = 1.8)
} else {
mtext(sprintf("current iterate (%.3g, %.3g) is off the plotted region",
cur[1], cur[2]), side = 3, line = -1.5,
col = "firebrick", cex = 0.9)
}
leg <- list(txt = c("current iterate", "minimum",
"steepest descent (direction)"),
pch = c(21, 3, NA), bg = c("firebrick", NA, NA),
lwd = c(NA, 2, 3), lty = c(NA, NA, 1),
col = c("black", "darkgreen", "#E8820C"))
if (!is.null(RP)) {
leg$txt <- c(leg$txt, names(ALGS)[ALGS == input$compare])
leg$pch <- c(leg$pch, NA); leg$bg <- c(leg$bg, NA)
leg$lwd <- c(leg$lwd, 2); leg$lty <- c(leg$lty, 2)
leg$col <- c(leg$col, "grey45")
}
## legend under the x axis label, so that it never covers the path
y0 <- grconvertY(grconvertY(par("usr")[3], "user", "inches") -
3.2 * par("csi"), "inches", "user")
legend(mean(par("usr")[1:2]), y0, xjust = 0.5, yjust = 1, xpd = NA,
ncol = 2, bty = "n", cex = 0.85,
pch = leg$pch, pt.bg = leg$bg, lwd = leg$lwd, lty = leg$lty,
col = leg$col, legend = leg$txt)
})
## compact numbers: fixed with three decimals, switching to scientific
## for very large or very small values
f3 <- function(x) ifelse(!is.finite(x), "",
ifelse(abs(x) >= 1e5 | (x != 0 & abs(x) < 1e-3),
formatC(x, format = "e", digits = 1),
formatC(x, format = "f", digits = 3)))
## why the run ended, shown as one line under the table
output$note <- renderUI({
P <- path(); RP <- ref()
if (k() + 1 < P$n) return(NULL)
HTML(paste0("<i>", P$note,
if (!is.null(RP)) paste0("; ", names(ALGS)[ALGS == input$compare],
": ", RP$note, " after ", RP$n - 1,
" iterations"),
"</i>"))
})
output$tab <- renderTable({
P <- path(); kk <- k() + 1L
## the step length that led to each iterate (none for the start)
a_in <- c(NA, P$A)[seq_len(P$n)]
i <- seq_len(kk)
d <- data.frame(iteration = as.character(i - 1),
x1 = f3(P$X[i, 1]), x2 = f3(P$X[i, 2]),
f = f3(P$F[i]),
`||grad||` = f3(sqrt(rowSums(P$G[i, , drop = FALSE]^2))),
step = f3(a_in[i]),
check.names = FALSE, stringsAsFactors = FALSE)
tail(d, 5)
}, rownames = FALSE, align = "r", width = "100%")
}
shinyApp(ui, server)
About the app
Lets you compare the paths that gradient descent, momentum, Adam, conjugate gradient, BFGS and safeguarded Newton take on the same objective, to see how curvature information affects speed and stability. Choose an objective and an algorithm, click a starting point, and step or play through the iterations, optionally with a second algorithm overlaid as a dashed grey path.
The app above runs safeguarded Newton, gradient descent, conjugate gradient, BFGS, momentum and Adam on six test functions, ranging from a well-conditioned quadratic to Rastrigin’s many local minima. Its controls match those of the safeguarded Newton–Raphson app (Safeguarded Newton-Raphson). Click in the contour plot (or type values) to choose a starting point, then use the playback buttons to step through the iterations or play the path as an animation. The orange arrow at the current iterate shows the direction of steepest descent, \(-\nabla f\). A second algorithm can be overlaid from the same start as a dashed grey path, and the latest iterations, with the gradient norm and the step length chosen by the line search (\(\eta\) for momentum, \(\alpha\) for Adam), are listed under the plot.
The momentum (heavy-ball) method is the generic optimizer behind much of machine learning: each step is \(v_{k+1} = \beta v_k - \eta \nabla f(x_k)\), \(x_{k+1} = x_k + v_{k+1}\), with a fixed learning rate \(\eta\) instead of a line search, so it needs many more iterations (up to 200) and diverges when \(\eta\) is too large for the function’s curvature. Its \(\eta\) and \(\beta\) can be set when it is chosen, and \(\eta\) resets to a default suited to each function.
Adam applies to any differentiable function in the same way, but rescales the step coordinate by coordinate. It keeps running averages of the gradient and of its square, \(m_{k} = \beta_1 m_{k-1} + (1-\beta_1) g_k\) and \(s_{k} = \beta_2 s_{k-1} + (1-\beta_2) g_k^2\), corrects both for starting at zero (\(\hat m_k = m_k/(1-\beta_1^k)\), \(\hat s_k = s_k/(1-\beta_2^k)\)), and steps \(x_{k+1} = x_k - \alpha\, \hat m_k / (\sqrt{\hat s_k} + \epsilon)\). Dividing by \(\sqrt{\hat s_k}\) makes each coordinate move roughly \(\alpha\) per step whatever the scale of \(f\), so one \(\alpha\) (default 0.1) works on all six functions, where momentum needs its own \(\eta\) for each; \(\beta_1\) is the shared \(\beta\) input and \(\beta_2 = 0.999\).
The app is built the same way as the Newton–Raphson divergence app earlier in this chapter (Safeguarded Newton-Raphson).
library(shiny)
### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
env = parent.frame(), quoted = FALSE) {
func <- shiny::exprToFunction(expr, env, quoted)
shiny::renderImage({
info <- shiny::getCurrentOutputInfo()
w <- if (is.numeric(width)) width else info$width()
h <- if (is.numeric(height)) height else info$height()
shiny::req(w > 0, h > 0)
pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
if (is.null(pr)) pr <- 1
f <- tempfile(fileext = ".png")
dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
on.exit(grDevices::dev.off(dev), add = TRUE)
grDevices::dev.control(displaylist = "enable")
v <- withVisible(func())
if (v$visible) print(v$value)
list(src = f, contentType = "image/png", width = w, height = h,
coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
}, deleteFile = TRUE)
}
## ---------------------------------------------------------------- objectives
mk <- function(label, fv, xlim, ylim, start, xstar) {
force(fv)
list(label = label, fv = fv, f = function(p) fv(p[1], p[2]),
xlim = xlim, ylim = ylim, start = start,
xstar = matrix(xstar, ncol = 2))
}
FNS <- list(
quad = mk(
"(a) Well-conditioned quadratic",
function(x, y) 0.5 * (2 * (x - 1)^2 + 1.6 * (x - 1) * (y - 1) +
2 * (y - 1)^2),
c(-3, 4), c(-3, 4), c(-2, 3), c(1, 1)
),
banana = mk(
"(b) Rosenbrock banana (narrow curved ridge)",
function(x, y) (1 - x)^2 + 100 * (y - x^2)^2,
c(-2, 2), c(-1, 3), c(-1.2, 1), c(1, 1)
),
mix = mk(
"(c) Highly correlated, two modes",
function(x, y) {
rho <- 0.9; den <- 1 - rho^2
q <- function(u, v) (u^2 - 2 * rho * u * v + v^2) / den
-log(exp(-0.5 * q(x - 1.2, y - 1.2)) +
0.6 * exp(-0.5 * q(x + 1.5, y + 1.5) / 1.5) + 1e-12)
},
c(-4, 4), c(-4, 4), c(-3, -0.5), c(1.2, 1.2)
),
himmel = mk(
"(d) Himmelblau (four global minima)",
function(x, y) (x^2 + y - 11)^2 + (x + y^2 - 7)^2,
c(-5, 5), c(-5, 5), c(-4, 4),
rbind(c(3, 2), c(-2.805118, 3.131312),
c(-3.779310, -3.283186), c(3.584428, -1.848126))
),
beale = mk(
"(e) Beale (flat plateau, sharp valley)",
function(x, y) (1.5 - x + x * y)^2 + (2.25 - x + x * y^2)^2 +
(2.625 - x + x * y^3)^2,
c(-4.5, 4.5), c(-4.5, 4.5), c(-1, 1), c(3, 0.5)
),
rastrigin = mk(
"(f) Rastrigin (many local minima)",
function(x, y) 20 + x^2 - 10 * cos(2 * pi * x) +
y^2 - 10 * cos(2 * pi * y),
c(-5.12, 5.12), c(-5.12, 5.12), c(-3.1, 4.2), c(0, 0)
)
)
## default learning rates for the momentum method: a fixed step has to suit
## the scale of each function (larger values diverge on (b), (d) and (e))
ETA <- c(quad = 0.1, banana = 0.002, mix = 0.03, himmel = 0.01,
beale = 0.01, rastrigin = 0.003)
## ------------------------------------------------- numerical derivatives
num_grad <- function(f, x) {
h <- 1e-5 * (1 + abs(x))
g <- numeric(2)
for (i in 1:2) {
e <- numeric(2); e[i] <- h[i]
g[i] <- (f(x + e) - f(x - e)) / (2 * h[i])
}
g
}
num_hess <- function(f, x) {
h <- 1e-4 * (1 + abs(x))
H <- matrix(0, 2, 2)
for (i in 1:2) for (j in i:2) {
ei <- numeric(2); ei[i] <- h[i]
ej <- numeric(2); ej[j] <- h[j]
H[i, j] <- (f(x + ei + ej) - f(x + ei - ej) -
f(x - ei + ej) + f(x - ei - ej)) / (4 * h[i] * h[j])
H[j, i] <- H[i, j]
}
H
}
## --------------------------------------------------- Wolfe line search
line_search <- function(f, g, x, d, a0 = 1, c1 = 1e-4, c2 = 0.9) {
f0 <- f(x); gd0 <- sum(g * d)
if (!is.finite(gd0) || gd0 >= 0) return(list(alpha = 0, ok = FALSE))
lo <- 0; hi <- Inf; a <- a0
for (it in 1:60) {
fa <- f(x + a * d)
if (!is.finite(fa) || fa > f0 + c1 * a * gd0) {
hi <- a; a <- 0.5 * (lo + hi)
} else {
ga <- num_grad(f, x + a * d)
if (sum(ga * d) < c2 * gd0) {
lo <- a
a <- if (is.finite(hi)) 0.5 * (lo + hi) else min(2 * a, 1e4)
} else {
return(list(alpha = a, ok = TRUE))
}
}
if (a < 1e-14) return(list(alpha = 0, ok = FALSE))
}
list(alpha = a, ok = (a > 0))
}
## ------------------------------------------------------------- algorithms
run_alg <- function(alg, FN, x0, maxit = 60, tol = 1e-6,
eta = 0.01, beta = 0.9, alpha = 0.1, beta2 = 0.999) {
f <- FN$f
## no line search: a fixed step needs many more iterations
if (alg %in% c("mom", "adam")) maxit <- 200
X <- matrix(NA_real_, maxit + 1, 2); G <- matrix(NA_real_, maxit + 1, 2)
D <- matrix(NA_real_, maxit + 1, 2); Fv <- rep(NA_real_, maxit + 1)
AL <- rep(NA_real_, maxit + 1)
x <- x0; B <- diag(2)
g_prev <- NULL; d_prev <- NULL; s_prev <- NULL; v <- c(0, 0)
m <- c(0, 0); m2 <- c(0, 0) # Adam's averages of g and g^2
n <- 0; note <- "maximum number of iterations reached"
for (k in seq_len(maxit)) {
if (any(!is.finite(x)) || max(abs(x)) > 1e6) { note <- "diverged"; break }
g <- num_grad(f, x); gn <- sqrt(sum(g^2))
X[k, ] <- x; G[k, ] <- g; Fv[k] <- f(x); n <- k
if (!is.finite(gn)) { note <- "diverged"; break }
if (gn < tol) { note <- "converged (||grad|| < 1e-6)"; break }
if (alg == "mom") {
## heavy ball: the step keeps a fraction beta of the previous step;
## no line search, the learning rate eta is fixed
v <- beta * v - eta * g
D[k, ] <- v; AL[k] <- eta
x <- x + v
next
}
if (alg == "adam") {
## Adam: momentum on g, divided coordinate-wise by the root of a running
## average of g^2, so each coordinate moves about alpha per step
## whatever the scale of f; both averages are bias-corrected
m <- beta * m + (1 - beta) * g
m2 <- beta2 * m2 + (1 - beta2) * g^2
v <- -alpha * (m / (1 - beta^k)) / (sqrt(m2 / (1 - beta2^k)) + 1e-8)
D[k, ] <- v; AL[k] <- alpha
x <- x + v
next
}
if (alg == "nr") {
H <- num_hess(f, x); H <- (H + t(H)) / 2
ev <- eigen(H, symmetric = TRUE, only.values = TRUE)$values
delta <- 1e-3 * max(1, max(abs(ev)))
tau <- max(0, delta - min(ev))
d <- tryCatch(solve(H + tau * diag(2), -g), error = function(e) -g)
} else if (alg == "gd") {
d <- -g
} else if (alg == "cg") {
if (is.null(d_prev)) {
d <- -g
} else {
y <- g - g_prev
beta <- max(0, sum(g * y) / max(sum(g_prev^2), 1e-300)) # PR+
d <- -g + beta * d_prev
}
if (sum(g * d) > -1e-12) d <- -g # restart
} else { # BFGS
if (!is.null(s_prev)) {
y <- g - g_prev; sy <- sum(s_prev * y)
if (sy > 1e-10) {
rho <- 1 / sy
V <- diag(2) - rho * outer(s_prev, y)
B <- V %*% B %*% t(V) + rho * outer(s_prev, s_prev)
}
}
d <- -as.vector(B %*% g)
if (sum(g * d) > -1e-12) { B <- diag(2); d <- -g }
}
ls <- line_search(f, g, x, d)
D[k, ] <- d; AL[k] <- ls$alpha
if (ls$alpha <= 0) { note <- "line search failed (flat or non-descent)"; break }
s_prev <- ls$alpha * d; g_prev <- g; d_prev <- d
x <- x + s_prev
}
list(X = X[1:n, , drop = FALSE], G = G[1:n, , drop = FALSE],
D = D[1:n, , drop = FALSE], F = Fv[1:n], A = AL[1:n],
n = n, note = note)
}
ALGS <- c("Safeguarded Newton (modified Hessian + line search)" = "nr",
"Gradient descent + line search" = "gd",
"Conjugate gradient (PR+)" = "cg",
"BFGS (quasi-Newton)" = "bfgs",
"Momentum (heavy ball, fixed step)" = "mom",
"Adam (step scaled per coordinate)" = "adam")
## ---------------------------- widen the data box to the device aspect ratio
expand_box <- function(xlim, ylim, pin) {
if (length(pin) != 2 || any(!is.finite(pin)) || any(pin <= 0))
return(list(xlim = xlim, ylim = ylim))
r <- pin[1] / pin[2]
wd <- diff(xlim); ht <- diff(ylim)
if (wd / ht < r) {
w <- ht * r; m <- mean(xlim); xlim <- m + c(-0.5, 0.5) * w
} else {
h <- wd / r; m <- mean(ylim); ylim <- m + c(-0.5, 0.5) * h
}
list(xlim = xlim, ylim = ylim)
}
## --------------------------------------------------------------------- UI
## an icon-only playback button; the title shows as a tooltip
ctrl_btn <- function(id, icon_name, title, class = "btn-default")
actionButton(id, NULL, icon = icon(icon_name), title = title, class = class,
style = "flex: 1; padding: 6px 0;")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
width = 4,
selectInput("fn", "objective function",
setNames(names(FNS), sapply(FNS, `[[`, "label"))),
selectInput("alg", "algorithm", ALGS),
div(style = "display: flex; gap: 10px;",
div(style = "flex: 1;",
numericInput("x1", HTML("starting x<sub>1</sub>"),
value = FNS[[1]]$start[1], step = 0.5,
width = "100%")),
div(style = "flex: 1;",
numericInput("x2", HTML("starting x<sub>2</sub>"),
value = FNS[[1]]$start[2], step = 0.5,
width = "100%"))),
helpText("Or click inside the contour plot to choose a new ",
"starting value."),
selectInput("compare", "overlay the path of",
c("none" = "none", ALGS)),
## settings of momentum and Adam, each shown when its method is used;
## beta is shared (Adam's beta_1 plays the role of the momentum beta)
conditionalPanel(
"['mom', 'adam'].includes(input.alg) || ['mom', 'adam'].includes(input.compare)",
div(style = "display: flex; gap: 10px;",
conditionalPanel(
"input.alg == 'mom' || input.compare == 'mom'", style = "flex: 1;",
numericInput("eta", HTML("momentum η"),
value = ETA[[1]], min = 0, step = 0.001,
width = "100%")),
conditionalPanel(
"input.alg == 'adam' || input.compare == 'adam'", style = "flex: 1;",
numericInput("alpha", HTML("Adam α"),
value = 0.1, min = 0, step = 0.01, width = "100%")),
div(style = "flex: 1;",
numericInput("beta", HTML("β (Adam β<sub>1</sub>)"),
value = 0.9, min = 0, max = 0.999, step = 0.05,
width = "100%")))),
checkboxInput("autoplay", "autoplay when the start changes", TRUE),
sliderInput("k", "iteration", min = 0, max = 1, value = 0, step = 1),
div(style = "display: flex; gap: 4px;",
ctrl_btn("first", "backward-fast", "Back to the start"),
ctrl_btn("back", "backward-step", "One step back"),
ctrl_btn("play", "play", "Play", class = "btn-primary"),
ctrl_btn("pause", "pause", "Pause"),
ctrl_btn("step", "forward-step", "One step forward"),
ctrl_btn("toend", "forward-fast", "To the end")),
hr(),
helpText("Try gradient descent on the Rosenbrock banana, overlaid ",
"with BFGS or safeguarded Newton: gradient descent zig-zags ",
"across the curved valley, while the curvature-aware methods ",
"follow it. On Himmelblau and Rastrigin, click different ",
"starting points to see which minimum each method finds.")
),
mainPanel(
width = 8,
plotOutput("contour", click = "click", height = "500px"),
## details of the iterations, shown under the plot
hr(),
div(style = "max-width: 560px;",
tableOutput("tab"),
htmlOutput("note"))
)
)
)
## ----------------------------------------------------------------- server
server <- function(input, output, session) {
FN <- reactive(FNS[[input$fn]])
playing <- reactiveVal(FALSE)
play_ms <- 900
set_start <- function(p) {
updateNumericInput(session, "x1", value = round(p[1], 2))
updateNumericInput(session, "x2", value = round(p[2], 2))
}
## a new objective moves the start to its default; clicking the contour
## plot moves it to the clicked point
observeEvent(input$fn, {
set_start(FNS[[input$fn]]$start)
updateNumericInput(session, "eta", value = ETA[[input$fn]])
}, ignoreInit = TRUE)
observeEvent(input$click, {
p <- c(input$click$x, input$click$y)
if (all(is.finite(p))) set_start(p)
})
start <- reactive({
req(is.finite(input$x1), is.finite(input$x2))
c(input$x1, input$x2)
})
## settings of momentum and Adam (ignored by the others)
mom_par <- reactive({
eta <- if (is.finite(input$eta) && input$eta > 0) input$eta else ETA[[input$fn]]
alpha <- if (is.finite(input$alpha) && input$alpha > 0) input$alpha else 0.1
beta <- if (is.finite(input$beta)) min(max(input$beta, 0), 0.999) else 0.9
list(eta = eta, beta = beta, alpha = alpha)
})
path <- reactive(run_alg(input$alg, FN(), start(),
eta = mom_par()$eta, beta = mom_par()$beta,
alpha = mom_par()$alpha))
## a second algorithm from the same start, shown for comparison
ref <- reactive({
if (input$compare == "none" || input$compare == input$alg) return(NULL)
run_alg(input$compare, FN(), start(),
eta = mom_par()$eta, beta = mom_par()$beta,
alpha = mom_par()$alpha)
})
## current iteration, clamped to the length of the path
k <- reactive(min(as.integer(input$k), path()$n - 1))
## a new path restarts the display at iteration 0
observeEvent(path(), {
updateSliderInput(session, "k", max = max(1, path()$n - 1), value = 0)
playing(isTRUE(input$autoplay) && path()$n > 1)
})
go_to <- function(i) {
updateSliderInput(session, "k", value = max(0, min(i, path()$n - 1)))
}
observeEvent(input$play, {
if (k() >= path()$n - 1) go_to(0)
if (path()$n > 1) playing(TRUE)
})
observeEvent(input$pause, playing(FALSE))
observeEvent(input$step, { playing(FALSE); go_to(k() + 1) })
observeEvent(input$back, { playing(FALSE); go_to(k() - 1) })
observeEvent(input$first, { playing(FALSE); go_to(0) })
observeEvent(input$toend, { playing(FALSE); go_to(path()$n - 1) })
observe({
if (!isTRUE(playing())) return()
kk <- isolate(k())
if (kk >= isolate(path()$n) - 1) { playing(FALSE); return() }
invalidateLater(play_ms, session)
isolate(go_to(kk + 1))
})
output$contour <- renderPlot({
FNc <- FN(); P <- path(); RP <- ref(); kk <- k() + 1L
par(mar = c(7, 4, 2, 1)) # room for the legend below
plot.new()
bx <- expand_box(FNc$xlim, FNc$ylim, par("pin"))
plot.window(xlim = bx$xlim, ylim = bx$ylim, xaxs = "i", yaxs = "i")
xs <- seq(bx$xlim[1], bx$xlim[2], length.out = 180)
ys <- seq(bx$ylim[1], bx$ylim[2], length.out = 180)
z <- outer(xs, ys, FNc$fv)
zf <- z[is.finite(z)]
lv <- unique(quantile(zf, probs = seq(0, 1, length.out = 30)^1.7))
contour(xs, ys, z, levels = lv, add = TRUE, col = "grey70",
drawlabels = FALSE)
axis(1); axis(2); box()
title(main = paste0(names(ALGS)[ALGS == input$alg], " on ",
sub("^\\([a-f]\\) ", "", FNc$label)),
xlab = expression(x[1]), ylab = expression(x[2]), cex.main = 1)
points(FNc$xstar[, 1], FNc$xstar[, 2], pch = 3, col = "darkgreen",
lwd = 2, cex = 1.2)
## the comparison path, drawn underneath
if (!is.null(RP)) {
Q <- RP$X[seq_len(min(kk, RP$n)), , drop = FALSE]
if (nrow(Q) > 1) lines(Q[, 1], Q[, 2], col = "grey45", lwd = 2, lty = 2)
points(Q[, 1], Q[, 2], pch = 21, bg = "grey85", col = "grey45",
cex = 0.9)
}
X <- P$X
if (kk > 1) lines(X[1:kk, 1], X[1:kk, 2], col = "steelblue", lwd = 2)
points(X[1:kk, 1], X[1:kk, 2], pch = 21, bg = "steelblue", cex = 1.1)
cur <- X[kk, ]
inside <- cur[1] >= bx$xlim[1] && cur[1] <= bx$xlim[2] &&
cur[2] >= bx$ylim[1] && cur[2] <= bx$ylim[2]
if (inside) {
## Arrow along -grad f (steepest descent), of fixed length on screen.
## The gradient is a covector, so its on-screen components are obtained
## by multiplying by the units-per-inch factors; the box is widened to
## the device aspect ratio, so here the two factors agree anyway.
g <- -P$G[kk, ]
upi <- c(diff(par("usr")[1:2]) / par("pin")[1],
diff(par("usr")[3:4]) / par("pin")[2])
gs <- g * upi
if (sqrt(sum(g^2)) > 1e-6 && sqrt(sum(gs^2)) > 0) {
d <- 0.45 * gs / sqrt(sum(gs^2)) * upi # 0.45 inch long
arrows(cur[1], cur[2], cur[1] + d[1], cur[2] + d[2],
col = "#E8820C", lwd = 3, length = 0.09)
}
points(cur[1], cur[2], pch = 21, bg = "firebrick", cex = 1.8)
} else {
mtext(sprintf("current iterate (%.3g, %.3g) is off the plotted region",
cur[1], cur[2]), side = 3, line = -1.5,
col = "firebrick", cex = 0.9)
}
leg <- list(txt = c("current iterate", "minimum",
"steepest descent (direction)"),
pch = c(21, 3, NA), bg = c("firebrick", NA, NA),
lwd = c(NA, 2, 3), lty = c(NA, NA, 1),
col = c("black", "darkgreen", "#E8820C"))
if (!is.null(RP)) {
leg$txt <- c(leg$txt, names(ALGS)[ALGS == input$compare])
leg$pch <- c(leg$pch, NA); leg$bg <- c(leg$bg, NA)
leg$lwd <- c(leg$lwd, 2); leg$lty <- c(leg$lty, 2)
leg$col <- c(leg$col, "grey45")
}
## legend under the x axis label, so that it never covers the path
y0 <- grconvertY(grconvertY(par("usr")[3], "user", "inches") -
3.2 * par("csi"), "inches", "user")
legend(mean(par("usr")[1:2]), y0, xjust = 0.5, yjust = 1, xpd = NA,
ncol = 2, bty = "n", cex = 0.85,
pch = leg$pch, pt.bg = leg$bg, lwd = leg$lwd, lty = leg$lty,
col = leg$col, legend = leg$txt)
})
## compact numbers: fixed with three decimals, switching to scientific
## for very large or very small values
f3 <- function(x) ifelse(!is.finite(x), "",
ifelse(abs(x) >= 1e5 | (x != 0 & abs(x) < 1e-3),
formatC(x, format = "e", digits = 1),
formatC(x, format = "f", digits = 3)))
## why the run ended, shown as one line under the table
output$note <- renderUI({
P <- path(); RP <- ref()
if (k() + 1 < P$n) return(NULL)
HTML(paste0("<i>", P$note,
if (!is.null(RP)) paste0("; ", names(ALGS)[ALGS == input$compare],
": ", RP$note, " after ", RP$n - 1,
" iterations"),
"</i>"))
})
output$tab <- renderTable({
P <- path(); kk <- k() + 1L
## the step length that led to each iterate (none for the start)
a_in <- c(NA, P$A)[seq_len(P$n)]
i <- seq_len(kk)
d <- data.frame(iteration = as.character(i - 1),
x1 = f3(P$X[i, 1]), x2 = f3(P$X[i, 2]),
f = f3(P$F[i]),
`||grad||` = f3(sqrt(rowSums(P$G[i, , drop = FALSE]^2))),
step = f3(a_in[i]),
check.names = FALSE, stringsAsFactors = FALSE)
tail(d, 5)
}, rownames = FALSE, align = "r", width = "100%")
}
shinyApp(ui, server)This app accompanies Optimization for Maximum Likelihood Estimation in the book.