Gradient-Based Methods for Fitting a Poisson Neural Network
#| '!! shinylive warning !!': |
#| shinylive does not work in self-contained HTML documents.
#| Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 1440
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)
}
## ------------------------------------------------------------------- model
## One covariate x, four tanh hidden units, log link, Poisson counts:
## a_j = w_j1 x + w_j0, h_j = tanh(a_j), eta = v_0 + sum_j v_j h_j,
## lambda = exp(eta).
## The data come from four units; the fitted network has J >= 4 units (chosen in the app).
## theta = (w11..wJ1, w10..wJ0, v1..vJ, v0), so p = 3 J + 1 weights
nunits <- function(th) (length(th) - 1) %/% 3
## two bumps in the mean: units 1, 2 switch on and off over (-2.2, -0.8),
## units 3, 4 over (0.8, 2.2), so lambda(x) has two modes
TRUE_THETA <- c(2.5, 2.5, 2.5, 2.5, 5.5, 2, -2, -5.5, 1.2, -1.2, 1.0, -1.0, -0.5)
## the same function as a network of J units: units 5 to J get output weight 0, and
## fixed random input weights (with zero input weights too they could never move)
embed_theta <- function(th4, J) {
if (J <= 4) return(th4)
set.seed(77); e <- J - 4
c(th4[1:4], rnorm(e), th4[5:8], rnorm(e), th4[9:12], rep(0, e), th4[13])
}
fwd <- function(th, x) {
J <- nunits(th)
H <- tanh(outer(x, th[1:J]) + rep(th[J + 1:J], each = length(x)))
list(H = H, eta = as.vector(th[3 * J + 1] + H %*% th[2 * J + 1:J]))
}
lambda_fun <- function(th, x) exp(fwd(th, x)$eta)
## the scaled units v_j h_j(x), one column per hidden unit
unit_terms <- function(th, x) { J <- nunits(th); sweep(fwd(th, x)$H, 2, th[2 * J + 1:J], "*") }
## average Poisson negative log-likelihood, with the log y! term: it does not depend on
## the weights, but without it the training and test losses would differ by a constant
nll <- function(th, x, y) {
e <- fwd(th, x)$eta
v <- mean(exp(e) - y * e + lfactorial(y))
if (is.finite(v)) v else Inf
}
## its gradient by backpropagation: delta_eta -> delta_a -> weights
nll_grad <- function(th, x, y) {
J <- nunits(th)
E <- fwd(th, x)
d_eta <- exp(E$eta) - y # n
d_a <- (1 - E$H^2) * outer(d_eta, th[2 * J + 1:J]) # n x J
c(colSums(d_a * x), # w_j1
colSums(d_a), # w_j0
as.vector(crossprod(E$H, d_eta)), # v_j
sum(d_eta)) / length(x) # v_0
}
## the L1 penalty lambda * sum |w| applies to the weights w_j1 and v_j, not to the intercepts
pen_mask <- function(th) { J <- nunits(th); r <- rep(1, length(th)); r[c(J + 1:J, 3 * J + 1)] <- 0; r }
make_data <- function(n, seed) {
set.seed(100 + seed)
x <- runif(n, -3, 3)
y <- rpois(n, lambda_fun(TRUE_THETA, x))
## a fixed vertical offset, drawn once with the data, so the points stay put
list(x = x, y = y, yj = y + runif(n, -0.12, 0.12))
}
## random starting weights: the output weights v_j have sd 2 / sqrt(J), so the
## starting curve has about the same size whatever the number of units
rand_start <- function(seed, J) {
set.seed(2000 + seed)
c(rnorm(2 * J), rnorm(J, 0, 2 / sqrt(J)), 0)
}
## ------------------------------------------------------- Wolfe line search
line_search <- function(f, g, x, d, a0 = 1, c1 = 1e-4, c2 = 0.9) {
f0 <- f(x); gd0 <- sum(g(x) * 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 {
if (sum(g(x + a * d) * 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
## the methods that step through mini-batches: one iteration is one epoch
MINIBATCH <- c("sgdls", "sgdls2", "mom", "adam")
## Row k of P (the weights), and element k of F (the objective), L (the loss
## without the penalty) and GN (the gradient norm), is the state after k - 1 steps;
## A[k] is the step length that led to it. The objective is the loss plus the L1
## penalty lam * sum |w|, whose gradient is taken as lam * sign(w) (a subgradient).
run_alg <- function(alg, th0, x, y, maxit, lr = 0.1, mom = 0.9, m = 20,
tol = 1e-6, patience = Inf, rtol = 1e-5, lmem = 10, lam = 0) {
p <- length(th0)
pm <- lam * pen_mask(th0)
f <- function(th) nll(th, x, y) + sum(pm * abs(th))
g <- function(th) nll_grad(th, x, y) + pm * sign(th)
n <- 0; note <- "maximum number of iterations reached"
if (alg == "bfgs" && p > 2000) { # B alone would take p^2 numbers
return(list(P = matrix(th0, 1), F = f(th0), L = nll(th0, x, y),
GN = sqrt(sum(g(th0)^2)), A = NA_real_, n = 1,
note = paste0("BFGS not run: its p x p matrix would hold ",
format(p^2, big.mark = ","), " numbers (p = ", p,
"); use L-BFGS")))
}
## state for the fixed-rate rules
n_obs <- length(x); m <- max(1, min(m, n_obs))
capped <- FALSE
if (alg %in% MINIBATCH) { # keep the number of mini-batch steps in check
cap <- max(1, floor(100000 / ceiling(n_obs / m)))
if (maxit > cap) { maxit <- cap; capped <- TRUE }
}
stored <- FALSE # keep the stored path to 4 million numbers
if ((maxit + 1) * p > 4e6) { maxit <- floor(4e6 / p) - 1; stored <- TRUE }
P <- matrix(NA_real_, maxit + 1, p)
Fv <- Lv <- GN <- AL <- rep(NA_real_, maxit + 1)
th <- th0; B <- if (alg == "bfgs") diag(p) else NULL
g_prev <- d_prev <- s_prev <- NULL
Sh <- Yh <- list() # the stored pairs of L-BFGS
best_f <- Inf; best_k <- 1 # the best loss so far, and when it was reached
vel <- m1 <- m2 <- numeric(p) # momentum velocity; Adam moments
a_prev <- lr / 2; nrej <- 0; nsteps <- 0 # the independent-batch line search
tt <- 0 # mini-batch updates so far (Adam)
if (alg %in% MINIBATCH) set.seed(11)
for (k in 1:(maxit + 1)) {
gk <- g(th); lk <- nll(th, x, y); fk <- lk + sum(pm * abs(th))
P[k, ] <- th; GN[k] <- sqrt(sum(gk^2)); Fv[k] <- fk; Lv[k] <- lk; n <- k
if (!is.finite(fk) || !all(is.finite(gk))) { note <- "diverged"; break }
if (tol > 0 && sqrt(sum(gk^2)) < tol) {
note <- paste0("converged: gradient norm < ", format(tol)); break
}
## no stopping rule can be exact for a noisy method, so every method also stops when the
## full-data loss has not improved by a fraction rtol for `patience` iterations
if (k == 1 || fk < best_f - rtol * abs(best_f)) { best_f <- fk; best_k <- k }
if (k - best_k >= patience) {
note <- paste0("stopped: the loss has not improved by ", 100 * rtol, "% in ",
patience, " iterations"); break
}
if (k > maxit) break
if (alg == "gdfix") { # full-batch gradient, fixed learning rate
AL[k + 1] <- lr
th <- th - lr * gk
next
}
if (alg %in% MINIBATCH) { # one iteration is one epoch: a shuffled pass
perm <- sample.int(n_obs) # of mini-batch steps over all the data, so
al <- numeric(0) # it costs about one full-batch gradient
for (s0 in seq(1, n_obs, by = m)) {
idx <- perm[s0:min(s0 + m - 1, n_obs)]
xb <- x[idx]; yb <- y[idx]
gb <- nll_grad(th, xb, yb) + pm * sign(th) # the gradient of mini-batch B_k
if (alg == "sgdls") { # backtracking line search on the batch objective
fb <- nll(th, xb, yb) + sum(pm * abs(th)); a <- lr; gg <- sum(gb^2)
for (j in 1:30) {
fa <- nll(th - a * gb, xb, yb) + sum(pm * abs(th - a * gb))
if (is.finite(fa) && fa <= fb - 1e-4 * a * gg) break
a <- a / 2
}
al <- c(al, a)
th <- th - a * gb
} else if (alg == "sgdls2") { # the same search, judged on an independent batch C:
ic <- sample.int(n_obs, length(idx)) # the step is checked on cases it was not fitted to,
xc <- x[ic]; yc <- y[ic] # with the same cases at both points (a paired estimate)
fc <- nll(th, xc, yc) + sum(pm * abs(th)); gg <- sum(gb^2)
a <- min(2 * a_prev, 1e3); ok <- FALSE # start from twice the last accepted step
for (j in 1:30) {
fa <- nll(th - a * gb, xc, yc) + sum(pm * abs(th - a * gb))
if (is.finite(fa) && fa <= fc - 1e-4 * a * gg) { ok <- TRUE; break }
a <- a / 2
}
nsteps <- nsteps + 1
if (ok) { th <- th - a * gb; a_prev <- a; al <- c(al, a) } else nrej <- nrej + 1
} else if (alg == "mom") { # heavy ball on the batch gradient
vel <- mom * vel - lr * gb
th <- th + vel
} else { # Adam on the batch gradient
tt <- tt + 1
m1 <- 0.9 * m1 + 0.1 * gb
m2 <- 0.999 * m2 + 0.001 * gb^2
th <- th - lr * (m1 / (1 - 0.9^tt)) / (sqrt(m2 / (1 - 0.999^tt)) + 1e-8)
}
}
AL[k + 1] <- if (alg %in% c("sgdls", "sgdls2")) (if (length(al)) mean(al) else 0) else lr
next
}
if (alg == "gd") {
d <- -gk
} else if (alg == "cg") {
if (is.null(d_prev)) {
d <- -gk
} else {
yk <- gk - g_prev
beta <- max(0, sum(gk * yk) / max(sum(g_prev^2), 1e-300)) # PR+
d <- -gk + beta * d_prev
}
if (sum(gk * d) > -1e-12) d <- -gk # restart
} else if (alg == "lbfgs") { # L-BFGS: two-loop recursion
if (!is.null(s_prev)) {
yk <- gk - g_prev; sy <- sum(s_prev * yk)
if (sy > 1e-10) {
Sh <- c(Sh, list(s_prev)); Yh <- c(Yh, list(yk))
if (length(Sh) > lmem) { Sh <- Sh[-1]; Yh <- Yh[-1] }
}
}
q <- gk; nh <- length(Sh); al <- numeric(nh)
for (i in rev(seq_len(nh))) {
al[i] <- sum(Sh[[i]] * q) / sum(Yh[[i]] * Sh[[i]])
q <- q - al[i] * Yh[[i]]
}
if (nh > 0) q <- q * sum(Sh[[nh]] * Yh[[nh]]) / sum(Yh[[nh]]^2) # initial scaling
for (i in seq_len(nh)) {
be <- sum(Yh[[i]] * q) / sum(Yh[[i]] * Sh[[i]])
q <- q + Sh[[i]] * (al[i] - be)
}
d <- -q
if (sum(gk * d) > -1e-12) { Sh <- Yh <- list(); d <- -gk }
} else { # BFGS
if (!is.null(s_prev)) {
yk <- gk - g_prev; sy <- sum(s_prev * yk)
if (sy > 1e-10) {
if (k == 2) B <- (sy / sum(yk^2)) * diag(p) # scale the first B
## B <- (I - rho s y') B (I - rho y s') + rho s s', in O(p^2) operations
rho <- 1 / sy; By <- as.vector(B %*% yk)
B <- B + (rho^2 * (sy + sum(yk * By))) * outer(s_prev, s_prev) -
rho * (outer(By, s_prev) + outer(s_prev, By))
}
}
d <- -as.vector(B %*% gk)
if (sum(gk * d) > -1e-12) { B <- diag(p); d <- -gk }
}
a0 <- if (alg %in% c("bfgs", "lbfgs") && k > 1) 1 else min(1, 1 / sqrt(sum(d^2)))
ls <- line_search(f, g, th, d, a0)
if (!ls$ok && alg != "gd") { # restart from steepest descent before giving up
d <- -gk; if (alg == "bfgs") B <- diag(p)
d_prev <- s_prev <- g_prev <- NULL; Sh <- Yh <- list()
ls <- line_search(f, g, th, d, min(1, 1 / sqrt(sum(d^2))))
}
if (!ls$ok) { note <- "line search failed"; break }
AL[k + 1] <- ls$alpha
s_prev <- ls$alpha * d; g_prev <- gk; d_prev <- d
th <- th + s_prev
}
if (capped && grepl("^maximum", note))
note <- paste0("stopped after ", maxit, " epochs (100000 mini-batch steps)")
if (stored && grepl("^maximum", note))
note <- paste0("stopped after ", maxit, " iterations, to keep the stored path of the ",
p, " weights within 4 million numbers")
if (alg == "sgdls2" && nsteps > 0)
note <- paste0(note, "; ", round(100 * nrej / nsteps), "% of the mini-batch steps were not ",
"taken (no sufficient decrease on the check batch)")
i <- seq_len(n)
list(P = P[i, , drop = FALSE], F = Fv[i], L = Lv[i], GN = GN[i],
A = AL[i], n = n, note = note)
}
ALGS <- c("Gradient descent, fixed learning rate" = "gdfix",
"Gradient descent + line search" = "gd",
"Conjugate gradient (Polak-Ribiere+)" = "cg",
"BFGS (quasi-Newton)" = "bfgs",
"L-BFGS (limited memory)" = "lbfgs",
"SGD + line search (on each mini-batch)" = "sgdls",
"SGD + line search (on an independent batch)" = "sgdls2",
"SGD + momentum" = "mom",
"SGD + Adam" = "adam")
alg_name <- function(a) if (a == "none") "none" else names(ALGS)[ALGS == a]
## --------------------------------------------------------- network layout
## Weights sit on the edges; each intercept is a node of its own, a box with
## the value and its arrows, hung on the neuron it shifts. Only the first JS = 4
## hidden units are drawn, with vertical dots below them for any others. A slot is
## one drawn weight; show_idx(J) gives the position of each slot in theta.
JS <- 4
NPS <- 3 * JS + 1 # weights drawn
NAMES <- c(paste0("w", 1:JS, "1"), paste0("w", 1:JS, "0"), paste0("v", 1:JS), "v0")
BIASIDX <- c(JS + 1:JS, NPS) # the intercept slots
show_idx <- function(J) c(1:JS, J + 1:JS, 2 * J + 1:JS, 3 * J + 1)
NX <- c(0.07, 0.50) # (x, y) of the input node
YH <- seq(0.88, 0.12, length.out = JS); XH <- 0.60 # hidden nodes
NO <- c(1.13, 0.50) # output node
at <- function(p, q, f) p + f * (q - p) # a point along an edge
## hidden intercepts hang above the upper half of the hidden nodes and below the rest
YB <- YH + rep(c(0.14, -0.14), each = JS / 2)
BIAS <- c(rep(0.56, JS), 1.00) # x of the intercept boxes
BIASY <- c(YB, 0.17) # y of the intercept boxes
## where each weight's value and arrows sit
ADJ <- local({
hj <- lapply(1:JS, function(j) c(XH, YH[j]))
pos <- c(lapply(1:JS, function(j) at(NX, hj[[j]], 0.50)), # w_j1: x -> h_j
lapply(1:JS, function(j) c(BIAS[j], BIASY[j])), # w_j0: box on h_j
lapply(1:JS, function(j) at(hj[[j]], NO, 0.50)), # v_j: h_j -> out
list(c(BIAS[JS + 1], BIASY[JS + 1]))) # v_0: box on output
data.frame(idx = 1:NPS, sym = NAMES,
x = sapply(pos, `[`, 1), y = sapply(pos, `[`, 2),
stringsAsFactors = FALSE)
})
## the arrows beside each value (also the click targets): up / down beside an
## edge weight, left / right beside an intercept box
AX <- 0.104 # arrow offset from the value
isb <- ADJ$idx %in% BIASIDX
ARROWS <- rbind(
data.frame(idx = ADJ$idx, dir = +1, horiz = isb,
ax = ifelse(isb, ADJ$x + AX, ADJ$x + AX),
ay = ifelse(isb, ADJ$y, ADJ$y + 0.028)),
data.frame(idx = ADJ$idx, dir = -1, horiz = isb,
ax = ifelse(isb, ADJ$x - AX, ADJ$x + AX),
ay = ifelse(isb, ADJ$y, ADJ$y - 0.028)))
## ---------------------------------------------------------------- colours
## Diverging ramp: blue = negative, red = positive, depth by magnitude.
DIV <- colorRampPalette(c("#08306B", "#2171B5", "#6BAED6", "#DEEBF7",
"#F7F7F7",
"#FEE0D2", "#FC9272", "#CB181D", "#67000D"))(201)
## compander: maps v in [-vmax, vmax] to [-1, 1], boosting small values
tone <- function(v, vmax, k) {
u <- pmax(-1, pmin(1, v / vmax))
sign(u) * log1p(k * abs(u)) / log1p(k)
}
hcol <- function(v, vmax, k) DIV[round((tone(v, vmax, k) + 1) * 100) + 1]
## th is the full weight vector; the first JS units and v0 are drawn, and the
## other units, if any, are marked by vertical dots below unit JS
draw_net <- function(th, vmax, k, main, arrows = TRUE, digits = 2) {
J <- nunits(th); more <- J - JS; v <- th[show_idx(J)]
col <- hcol(v, vmax, k); lw <- 0.8 + 6 * abs(tone(v, vmax, k))
yb <- if (more > 0) -0.17 else 0 # the colour bar moves down for the dots
plot.new(); plot.window(c(0, 1.2), c(-0.25 + yb, 1.08))
title(main = main, cex.main = 1.05)
H <- cbind(XH, YH)
if (more > 0) { # the units not drawn: faint edges and dots
yd <- -0.14
segments(NX[1], NX[2], XH, yd + 0.04, col = "grey75", lty = 2)
segments(XH, yd + 0.04, NO[1], NO[2], col = "grey75", lty = 2)
points(rep(XH, 3), yd + c(0.03, -0.01, -0.05), pch = 19, cex = 0.7)
text(XH + 0.05, yd - 0.01, adj = 0, cex = 0.8, col = "grey25",
sprintf("units %d to %d not shown (%d more)", JS + 1, J, more))
}
## edges, each carrying one weight: x -> h_j (w_j1), h_j -> output (v_j)
for (j in 1:JS) {
segments(NX[1], NX[2], H[j, 1], H[j, 2], col = col[j], lwd = lw[j], lend = 1)
segments(H[j, 1], H[j, 2], NO[1], NO[2], col = col[2 * JS + j], lwd = lw[2 * JS + j], lend = 1)
}
## intercept nodes: a thin arrow from each box to the neuron it shifts
tgt <- rbind(H, NO)
for (i in seq_along(BIASIDX)) {
b <- ADJ[BIASIDX[i], ]
dy <- sign(tgt[i, 2] - b$y)
if (i == JS + 1) arrows(b$x, b$y + 0.03, NO[1] - 0.03, NO[2] - 0.03, length = 0.08,
col = "grey45", lwd = 1.4)
else arrows(b$x, b$y + dy * 0.035, tgt[i, 1], tgt[i, 2] - dy * 0.035,
length = 0.08, col = "grey45", lwd = 1.4)
}
## nodes
points(rbind(NX, H, NO), pch = 21, cex = 3.2, bg = "white", lwd = 1.6)
text(NX[1], NX[2], "x", font = 2)
text(H[, 1], H[, 2], paste0("h", 1:JS), cex = 0.8)
text(NO[1], NO[2], expression(lambda), cex = 1.1)
## values: an intercept is a box coloured by its value; an edge weight is
## plain text on a white patch so the edge does not strike through it
for (i in 1:NPS) {
b <- ADJ[i, ]; isb <- i %in% BIASIDX
if (isb) rect(b$x - 0.075, b$y - 0.036, b$x + 0.075, b$y + 0.036,
col = col[i], border = "grey35")
else rect(b$x - 0.072, b$y - 0.028, b$x + 0.072, b$y + 0.028,
col = adjustcolor("white", 0.8), border = NA)
dark <- abs(tone(v[i], vmax, k)) > 0.62
text(b$x, b$y, sprintf(paste0("%s=%.", digits, "f"), b$sym, v[i]),
cex = 0.85, font = if (isb) 1 else 2,
col = if (isb) { if (dark) "white" else "black" }
else if (dark) col[i] else "grey20")
}
if (arrows) for (r in seq_len(nrow(ARROWS))) {
a <- ARROWS[r, ]
if (a$horiz) # left / right: -, +
polygon(a$ax + a$dir * c(-0.013, -0.013, 0.015),
a$ay + c(-0.033, 0.033, 0), col = "grey30", border = NA)
else # down / up: -, +
polygon(a$ax + c(-0.026, 0.026, 0), a$ay + a$dir * c(-0.016, -0.016, 0.02),
col = "grey30", border = NA)
}
## signed colour bar
xs <- seq(0.12, 1.08, length.out = 201)
rect(xs, -0.24 + yb, xs + diff(xs)[1], -0.19 + yb, col = DIV, border = NA)
lab <- formatC(vmax, format = "g", digits = 2)
text(c(0.12, 0.60, 1.08), -0.16 + yb, c(paste0("-", lab), "0", paste0("+", lab)),
cex = 0.72)
}
## --------------------------------------------------------------------- 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;")
row_label <- function(txt)
column(1, div(style = "padding-top: 28px;", tags$b(txt)))
## learning rates on a roughly logarithmic grid (rates need to range over orders of magnitude)
LRGRID <- c(1e-5, 3e-5, 1e-4, 3e-4, 1e-3, 3e-3, 0.01, 0.03, 0.1, 0.3, 1)
LRCHOICES <- setNames(as.character(LRGRID), format(LRGRID, scientific = FALSE, drop0trailing = TRUE))
## one optimizer: its menu, then the parameters that belong to the chosen method
opt_row <- function(s, selected, col, none = FALSE) {
a <- paste0("input.alg", s)
has_lr <- paste0("['gdfix', 'sgdls', 'sgdls2', 'mom', 'adam'].indexOf(", a, ") >= 0")
has_b <- paste0("['sgdls', 'sgdls2', 'mom', 'adam'].indexOf(", a, ") >= 0")
fluidRow(
column(1, div(style = paste0("padding-top: 28px; font-size: 20px; color: ", col, ";"),
tags$b(s))),
column(3, selectInput(paste0("alg", s), "Optimizer",
choices = if (none) c("None" = "none", ALGS) else ALGS,
selected = selected, width = "100%")),
column(8,
conditionalPanel(has_lr,
div(class = "steprule",
div(class = "lrbox", selectInput(paste0("lr", s), "Learning rate (first step if line search)",
choices = LRCHOICES, selected = "0.3", width = "100%")),
conditionalPanel(paste0(a, " == 'mom'"),
div(sliderInput(paste0("mom", s), "Momentum", min = 0, max = 0.99,
value = 0.9, step = 0.01, width = "100%"))),
conditionalPanel(has_b,
div(selectInput(paste0("batch", s), "Mini-batch size",
choices = c("5" = 5, "10" = 10, "20" = 20, "50" = 50,
"100" = 100, "all n (full batch)" = 1e6),
selected = 20, width = "100%"))))),
conditionalPanel(paste0(a, " == 'lbfgs'"),
div(class = "steprule",
div(selectInput(paste0("mem", s), "Memory (pairs kept)",
choices = c(2, 5, 10, 20), selected = 10, width = "100%")),
div(style = "padding-top: 28px;",
helpText("The step length comes from a Wolfe line search.")))),
conditionalPanel(paste0(has_lr, " == false && ", a, " != 'none' && ", a, " != 'lbfgs'"),
div(style = "padding-top: 28px;",
helpText("The step length comes from a Wolfe line search."))))
)
}
ui <- fluidPage(
## the iteration slider is the only state: the browser moves it (play timer, buttons,
## dragging), and the server just reads input$kshow
tags$head(tags$script(HTML("
var ktimer = null, kdrag = false, kself = false, kuser = 0;
function kcur() { return parseInt($('#kshow').val()); }
function kslider() { return $('#kshow').data('ionRangeSlider'); }
function kset(v) {
var s = kslider(); if (!s) return;
kself = true;
s.update({from: Math.max(s.options.min, Math.min(s.options.max, v))});
$('#kshow').trigger('change'); kself = false; }
function kplay(on) {
if (ktimer) { clearInterval(ktimer); ktimer = null; }
$('#play i').removeClass('fa-play fa-pause').addClass(on ? 'fa-pause' : 'fa-play');
if (!on) return;
var s = kslider(); if (s && kcur() >= s.options.max) kset(0);
ktimer = setInterval(function() {
if (kdrag || Date.now() - kuser < 600) return; // the user is on the slider
var s = kslider();
if (kcur() >= s.options.max) kplay(false); else kset(kcur() + 1);
}, 300); }
['mousedown', 'touchstart', 'pointerdown'].forEach(function(ev) {
document.addEventListener(ev, function(e) {
if ($(e.target).closest('.shiny-input-container').find('#kshow').length) {
kdrag = true; kuser = Date.now(); } }, true); });
['mouseup', 'touchend', 'pointerup'].forEach(function(ev) {
document.addEventListener(ev, function() { kdrag = false; kuser = Date.now(); }, true); });
$(document).on('change', '#kshow', function() { if (!kself) kuser = Date.now(); });
$(document).on('click', '#play', function() { kplay(!ktimer); });
$(document).on('click', '#step', function() { kplay(false); kset(kcur() + 1); });
$(document).on('click', '#back', function() { kplay(false); kset(kcur() - 1); });
$(document).on('click', '#first', function() { kplay(false); kset(0); });
$(document).on('click', '#toend', function() { kplay(false); kset(kslider().options.max); });
Shiny.addCustomMessageHandler('krun', function(m) {
kplay(false);
// a new run is shown at its last iteration, or at the start if the box is unticked
var s = kslider(); if (s) { s.update({max: m.max, from: m.last ? m.max : 0}); $('#kshow').trigger('change'); }
if (m.play) kplay(true); });
"))),
## small text for the row of weight buttons; labels kept to one line
tags$head(tags$style(HTML("
.wbar .btn { font-size: 12px; padding: 3px 10px; }
.wbar label { font-size: 12px; margin-bottom: 1px; }
.wbar .form-group { margin-bottom: 0; }
.wbar .selectize-input, .wbar select { font-size: 12px; min-height: 26px;
padding: 3px 8px; }
.steprule { display: flex; gap: 14px; }
.steprule > div { flex: 1; min-width: 0; }
.steprule > div.lrbox { flex: 2; }
.infotab { border-collapse: collapse; font-size: 13px; margin: 6px 0; }
.infotab th, .infotab td { padding: 3px 8px; text-align: right; white-space: nowrap;
border-bottom: 1px solid #ddd; }
.infotab th { border-bottom: 2px solid #999; }
.infotab th:first-child, .infotab td:first-child { text-align: left; }
.control-label { display: block; max-width: 100%; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis; }"))),
## a label cut off by its box shows in full on hover
tags$head(tags$script(HTML("
$(document).on('mouseenter', '.control-label', function() {
if (this.scrollWidth > this.clientWidth) this.title = this.textContent;
else this.removeAttribute('title'); });"))),
## ---- control panel, at the top -------------------------------------------
wellPanel(
## the data
fluidRow(
row_label("Setup"),
column(2, sliderInput("n", "Sample size n", min = 50, max = 2000,
value = 150, step = 50, width = "100%")),
column(1, selectInput("xscale", "Scale of x", choices = c("0.1" = 0.1, "1" = 1, "10" = 10, "100" = 100),
selected = 1, width = "100%")),
column(1, numericInput("J", "Hidden units", value = 4, min = 4, max = 2000, step = 1,
width = "100%")),
column(2, selectInput("lam", "L1 penalty \u03bb on the weights",
choices = c("0 (none)" = 0, "1e-5" = 1e-5, "1e-4" = 1e-4,
"1e-3" = 1e-3, "0.01" = 0.01, "0.1" = 0.1),
selected = 0, width = "100%")),
column(2, div(style = "padding-top: 25px;",
actionButton("newdata", "Regenerate data",
class = "btn-warning", style = "width:100%;")))
),
hr(style = "margin: 4px 0 8px;"),
## two optimizers, each with its own settings: A (green) and B (blue)
opt_row("A", "adam", "#2E8B57"),
opt_row("B", "gd", "#1F5FBF", none = TRUE),
hr(style = "margin: 4px 0 8px;"),
## how long to run them, the colour scale, the play buttons, the iteration shown
fluidRow(
row_label("Run"),
column(1, selectInput("maxit", "Max iterations",
choices = c(10, 20, 50, 100, 200, 500, 1000, 2000, 5000),
selected = 100, width = "100%")),
column(1, selectInput("ctr", "Contrast",
choices = c(1, 2, 4, 8, 16, 32), selected = 8,
width = "100%")),
column(1, selectInput("gtol", "Stop: ||g|| <",
choices = c("0.1" = 0.1, "0.01" = 0.01, "1e-3" = 0.001,
"1e-4" = 1e-4, "1e-6" = 1e-6, "1e-8" = 1e-8,
"never" = 0),
selected = 1e-6, width = "100%")),
column(1, selectInput("stall", "Stop if flat for",
choices = c("never" = Inf, "100 its" = 100, "50 its" = 50, "20 its" = 20),
selected = Inf, width = "100%")),
column(3, div(style = "display: flex; gap: 4px; padding-top: 22px;",
ctrl_btn("first", "backward-fast", "Back to the start"),
ctrl_btn("back", "backward-step", "One iteration back"),
ctrl_btn("play", "play", "Play / pause",
class = "btn-primary"),
ctrl_btn("step", "forward-step", "One iteration forward"),
ctrl_btn("toend", "forward-fast", "To the end")),
checkboxInput("autoplay", "Autoplay on change", FALSE),
checkboxInput("autolast", "Auto Display of Last Iteration", TRUE)),
column(3, sliderInput("kshow", "Iteration shown", min = 0, max = 100,
value = 0, step = 1, width = "100%"))
)
), fluidRow(
## ---- left: the fitted mean, and below it the network of weights -----
## (the two plots together are about as tall as the loss and rate plots)
column(6,
checkboxInput("showparts", "Show the units on the log scale", FALSE),
plotOutput("fit", height = "280px"),
conditionalPanel("input.showparts", plotOutput("eta", height = "250px")),
div(class = "wbar",
style = "display: flex; gap: 6px; align-items: flex-end; margin: 8px 0 4px 0;",
actionButton("settrue", "True Value", class = "btn-success"),
actionButton("newstart", "Random"),
actionButton("setzero", "Zero"),
div(style = "width: 110px; margin-left: 6px;",
selectInput("astep", "Adjust Size",
choices = c(0.05, 0.1, 0.25, 0.5, 1),
selected = 0.25, width = "100%")),
div(style = "width: 90px; margin-left: 6px;",
selectInput("netsel", "Network of", choices = c("A", "B"), width = "100%")),
div(style = "margin-left: 10px; white-space: nowrap;",
checkboxInput("runopt", "Run Optimizations", TRUE))),
plotOutput("netv", height = "350px", click = "netv_click")),
## ---- right: how the optimizer is doing: the loss and the rate ---------
column(6,
plotOutput("conv", height = "340px"),
radioButtons("lscale", NULL, inline = TRUE,
choices = c("log10 loss" = "log", "log10 (loss - smallest reached)" = "exc",
"loss" = "lin")),
plotOutput("rate", height = "250px"),
htmlOutput("info"))
)
)
## ----------------------------------------------------------------- server
server <- function(input, output, session) {
dseed <- reactiveVal(1); rseed <- reactiveVal(1)
theta0 <- reactiveVal(rand_start(1, 4)) # the starting weights
## the number of hidden units, read once typing has paused
Jr <- debounce(reactive({
v <- suppressWarnings(as.integer(input$J))
if (length(v) != 1 || is.na(v)) 4L else max(4L, min(2000L, v))
}), 800)
## a new number of units starts again from random weights of that size
observeEvent(Jr(), {
th <- rand_start(rseed(), Jr()); J <- Jr(); th[1:J] <- th[1:J] / xsc(); theta0(th)
}, ignoreInit = TRUE)
lam <- reactive(if (is.null(input$lam)) 0 else as.numeric(input$lam))
observeEvent(input$newdata, dseed(dseed() + 1))
## a sensible starting learning rate for each fixed-rate method
## a sensible learning rate for the method and the scale of x: the curvature in a slope
## weight grows like s^2, and Adam's step is measured in the weight, which shrinks like 1 / s.
## The output adds up J units, so its curvature in the output weights grows like J, and an
## Adam step of about lr in every weight moves the output by up to about J lr: all three
## fixed rates are also multiplied by 4 / J
for (s in c("A", "B")) local({
s <- s
observeEvent(list(input[[paste0("alg", s)]], input$xscale, Jr()), {
a <- input[[paste0("alg", s)]]
base <- c(gdfix = 0.1, sgdls = 0.1, sgdls2 = 0.1, mom = 0.03, adam = 0.1)[a]
if (!is.null(a) && !is.na(base)) {
v <- unname(base) / xsc()^(if (a == "adam") 1 else 2) *
(if (a %in% c("sgdls", "sgdls2")) 1 else 4 / Jr())
r <- LRGRID[which.min(abs(log(LRGRID) - log(v)))]
updateSelectInput(session, paste0("lr", s), selected = as.character(r))
}
})
})
observeEvent(input$setzero, theta0(rep(0, 3 * Jr() + 1)))
observeEvent(input$newstart, {
rseed(rseed() + 1); J <- Jr()
th <- rand_start(rseed(), J); th[1:J] <- th[1:J] / xsc() # random weights for x / s
theta0(th)
})
## an arrow click moves the nearest arrow's weight by one step
observeEvent(input$netv_click, {
cl <- input$netv_click
d <- ((cl$x - ARROWS$ax) / 0.05)^2 + ((cl$y - ARROWS$ay) / 0.04)^2
i <- which.min(d)
if (d[i] < 2) {
th <- theta0(); j <- show_idx(nunits(th))[ARROWS$idx[i]] # the slot's place in theta
th[j] <- th[j] + ARROWS$dir[i] * as.numeric(input$astep)
theta0(th)
}
})
## the predictor on a different scale: x -> s x, with the slope weights of the generating
## network divided by s, so the true curve is the same function of x / s
xsc <- reactive(if (is.null(input$xscale)) 1 else as.numeric(input$xscale))
TT <- reactive({ th <- TRUE_THETA; th[1:4] <- th[1:4] / xsc(); th })
## the true weights, with units 5 to J switched off (output weight 0)
observeEvent(input$settrue, {
J <- Jr(); th <- embed_theta(TRUE_THETA, J); th[1:J] <- th[1:J] / xsc(); theta0(th)
})
## a new scale of x keeps the starting curve: the slope weights change with it
xprev <- reactiveVal(1)
observeEvent(input$xscale, {
th <- theta0(); J <- nunits(th)
th[1:J] <- th[1:J] * xprev() / xsc(); xprev(xsc()); theta0(th)
}, ignoreInit = TRUE)
DAT <- reactive({
D <- make_data(input$n, dseed())
D$x <- D$x * xsc()
D
})
## a test sample from the same process, the same for both optimizers
DTE <- reactive({
D <- make_data(1000, dseed() + 5000)
D$x <- D$x * xsc()
D
})
## the loss on the test sample at every iteration of a run
## (at most 100 iterations are evaluated, and the rest interpolated, to keep large
## networks quick)
tcurve <- function(R) {
Dt <- DTE()
ks <- unique(round(seq(1, R$n, length.out = min(R$n, 100))))
te <- apply(R$P[ks, , drop = FALSE], 1, function(th) nll(th, Dt$x, Dt$y))
if (length(ks) == R$n) te else approx(ks, te, xout = seq_len(R$n))$y
}
## one run for each optimizer, from the same start on the same data
## its settings are read once they have been still for 0.4 s: a new number of units also
## resets the learning rate, which reaches the server a moment later, and a large network
## should not be fitted twice
mkrun <- function(s) {
pars <- debounce(reactive({
a <- input[[paste0("alg", s)]]
if (is.null(a) || a == "none") return(NULL)
list(a = a, th0 = theta0(), D = DAT(),
maxit = if (isFALSE(input$runopt)) 0 else as.numeric(input$maxit),
tol = if (is.null(input$gtol)) 1e-6 else as.numeric(input$gtol),
patience = if (is.null(input$stall)) Inf else as.numeric(input$stall),
lr = input[[paste0("lr", s)]], mom = input[[paste0("mom", s)]],
m = input[[paste0("batch", s)]], mem = input[[paste0("mem", s)]], lam = lam())
}), 400)
reactive({
S <- pars(); if (is.null(S)) return(NULL); a <- S$a
fixed <- a %in% c("gdfix", "sgdls", "sgdls2", "mom", "adam")
req(!fixed || !is.null(S$lr))
r <- run_alg(a, S$th0, S$D$x, S$D$y, S$maxit, tol = S$tol, patience = S$patience,
lr = if (fixed) as.numeric(S$lr) else NA,
mom = if (a == "mom") S$mom else NA,
m = if (a %in% MINIBATCH) as.numeric(S$m) else NA,
lmem = if (a == "lbfgs" && !is.null(S$mem)) as.numeric(S$mem) else 10,
lam = S$lam)
if (S$maxit == 0) r$note <- "optimization is off: Run Optimizations is unticked"
r
})
}
runA <- mkrun("A"); runB <- mkrun("B")
## the test loss along each run, computed once per run
testA <- reactive(tcurve(runA()))
testB <- reactive(if (is.null(runB())) NULL else tcurve(runB()))
## the network panels show the run chosen in "Network of"
netsel <- reactive(if (identical(input$netsel, "B") && !is.null(runB())) "B" else "A")
run <- reactive(if (netsel() == "B") runB() else runA())
## the browser owns the iteration (slider, play timer, buttons); a new run is shown at its end
observeEvent(list(runA(), runB()), {
nmax <- max(runA()$n, if (is.null(runB())) 0L else runB()$n)
session$sendCustomMessage("krun", list(max = nmax - 1L,
last = !isFALSE(input$autolast),
play = isTRUE(input$autoplay) && nmax > 1))
})
kraw <- reactive(as.integer(if (is.null(input$kshow)) 0L else input$kshow))
kpos <- reactive(min(kraw(), run()$n - 1L))
cur <- reactive({
R <- run(); k <- min(kpos(), R$n - 1L) + 1L
list(R = R, k = k, th = R$P[k, ])
})
## the colour scale of a run, from (a sample of) all its weights along the path
vmaxr <- reactive({
a <- abs(run()$P); if (length(a) > 1e5) a <- a[sample.int(length(a), 1e5)]
max(3, quantile(a, 0.95))
})
output$netv <- renderPlot({
C <- cur(); R <- C$R
vmax <- vmaxr()
par(mar = c(1, 1, 3, 1))
draw_net(C$th, vmax, as.numeric(input$ctr),
sprintf("%s: weights, iteration %d (loss %.4f)", netsel(), C$k - 1L, R$L[C$k]))
})
## one clearly different colour per hidden unit
PCOL <- c("#F28E00", "#1F5FBF", "black", "#00B5CC")
output$fit <- renderPlot({
RA <- runA(); RB <- runB(); R <- RA; D <- DAT(); kk <- kraw()
xg <- seq(-3, 3, length.out = 300) * xsc()
par(mar = c(4, 4.2, 2.5, 1))
plot(D$x, D$yj, pch = 19, cex = 0.7,
col = adjustcolor("#E8820C", 0.5), ylim = c(0, max(D$y) + 1),
xlab = "x", ylab = expression(lambda(x) ~ "and counts y"),
main = "fitted mean and the generated data")
lines(xg, lambda_fun(TT(), xg), col = "red", lty = 2, lwd = 2)
lines(xg, lambda_fun(R$P[1, ], xg), col = "grey60", lwd = 2)
lines(xg, lambda_fun(RA$P[min(kk, RA$n - 1L) + 1L, ], xg), col = "#2E8B57", lwd = 3)
if (!is.null(RB))
lines(xg, lambda_fun(RB$P[min(kk, RB$n - 1L) + 1L, ], xg), col = "#1F5FBF", lwd = 2.5)
leg <- data.frame(
lab = c("true mean", "starting weights", paste("A:", alg_name(input$algA)), "counts"),
lwd = c(2, 2, 3, NA), lty = c(2, 1, 1, NA), pch = c(NA, NA, NA, 19),
col = c("red", "grey60", "#2E8B57", adjustcolor("#E8820C", 0.7)),
stringsAsFactors = FALSE)
if (!is.null(RB))
leg <- rbind(leg, data.frame(lab = paste("B:", alg_name(input$algB)), lwd = 2.5, lty = 1,
pch = NA, col = "#1F5FBF", stringsAsFactors = FALSE))
legend("topright", bty = "n", cex = 0.78, lwd = leg$lwd, lty = leg$lty,
pch = leg$pch, col = leg$col, legend = leg$lab)
})
## the same fit on the log scale, where the units simply add up
output$eta <- renderPlot({
C <- cur(); xg <- seq(-3, 3, length.out = 300) * xsc()
VH <- unit_terms(C$th, xg); J <- ncol(VH)
## the units not drawn in the network are added up into one curve
if (J > JS) VH <- cbind(VH[, 1:JS], rowSums(VH[, -(1:JS), drop = FALSE]))
eta <- C$th[length(C$th)] + rowSums(VH)
eta_true <- log(lambda_fun(TT(), xg))
par(mar = c(4, 4.2, 2.5, 1))
matplot(xg, VH, type = "l", lty = 3, lwd = 2.5, col = c(PCOL, "grey50"),
ylim = pmax(-8, pmin(8, range(VH, eta, eta_true))),
xlab = "x", ylab = expression(log ~ lambda(x)),
main = "log scale: the scaled units v_j h_j add up to the fit")
abline(h = 0, lty = 3, col = "grey70")
lines(xg, eta_true, col = "red", lty = 2, lwd = 2)
lines(xg, eta, col = "#2E8B57", lwd = 3)
ul <- c(paste0("v", 1:JS, " h", 1:JS), if (J > JS) paste0("units ", JS + 1, "-", J, ", added"))
legend("topright", bty = "n", cex = 0.78, ncol = 2,
lwd = c(rep(2.5, ncol(VH)), 3, 2), lty = c(rep(3, ncol(VH)), 1, 2),
col = c(PCOL, if (J > JS) "grey50", "#2E8B57", "red"),
legend = c(ul, "sum + v0 (fit)", "true"))
})
output$conv <- renderPlot({
R <- runA(); RF <- runB(); kk <- kraw()
TA <- testA(); TB <- testB()
## the loss on the scale chosen below: as is, its log10, or the log10 of its excess
## over the smallest value any curve reaches (so differences near the floor show)
sc <- if (is.null(input$lscale)) "log" else input$lscale
best <- min(c(R$L, RF$L, TA, TB), na.rm = TRUE)
ls_fun <- function(v) switch(sc, lin = v, log = if (best > 0) log10(v) else log10(pmax(v - best, 1e-12)),
exc = log10(pmax(v - best, 1e-12)))
ls_lab <- switch(sc, lin = "loss",
log = if (best > 0) expression(log[10] ~ "loss") else expression(log[10] ~ "(loss - smallest reached)"),
exc = expression(log[10] ~ "(loss - smallest reached)"))
xl <- c(0, max(R$n, if (is.null(RF)) 0 else RF$n) - 1)
par(mar = c(4, 4.2, 2.5, 1))
plot(0:(R$n - 1), ls_fun(R$L), type = "n", xlab = "iteration", ylab = ls_lab,
xlim = xl, ylim = range(ls_fun(c(R$L, RF$L, TA, TB)), finite = TRUE),
main = paste0("average negative log-likelihood", if (lam() > 0) " (without the penalty)",
": training (solid) and test (dashed)"))
lines(0:(R$n - 1), ls_fun(R$L), col = "#2E8B57", lwd = 2)
lines(0:(R$n - 1), ls_fun(TA), col = "#2E8B57", lwd = 2, lty = 2)
ka <- min(kk, R$n - 1L)
points(ka, ls_fun(R$L[ka + 1L]), pch = 19, col = "#2E8B57", cex = 1.5)
points(ka, ls_fun(TA[ka + 1L]), pch = 1, col = "#2E8B57", cex = 1.5, lwd = 2)
if (!is.null(RF)) {
lines(0:(RF$n - 1), ls_fun(RF$L), col = "#1F5FBF", lwd = 2)
lines(0:(RF$n - 1), ls_fun(TB), col = "#1F5FBF", lwd = 2, lty = 2)
kb <- min(kk, RF$n - 1L)
points(kb, ls_fun(RF$L[kb + 1L]), pch = 19, col = "#1F5FBF", cex = 1.5)
points(kb, ls_fun(TB[kb + 1L]), pch = 1, col = "#1F5FBF", cex = 1.5, lwd = 2)
}
legend("topright", bty = "n", cex = 0.85, lwd = 2, lty = c(1, 2, if (!is.null(RF)) c(1, 2)),
col = c("#2E8B57", "#2E8B57", if (!is.null(RF)) c("#1F5FBF", "#1F5FBF")),
legend = c(paste("A:", alg_name(input$algA), "train"), "A: test",
if (!is.null(RF)) c(paste("B:", alg_name(input$algB), "train"), "B: test")))
})
## the learning rate (or the mean accepted step) of each run in each iteration
output$rate <- renderPlot({
kk <- kraw()
runs <- Filter(Negate(is.null), list(list(R = runA(), col = "#2E8B57", a = input$algA, s = "A"),
if (!is.null(runB())) list(R = runB(), col = "#1F5FBF", a = input$algB, s = "B")))
vals <- unlist(lapply(runs, function(u) u$R$A))
vals <- vals[is.finite(vals) & vals > 0]
par(mar = c(4, 4.2, 2.5, 1))
if (!length(vals)) { plot.new(); return(invisible()) }
xl <- c(0, max(sapply(runs, function(u) u$R$n)) - 1)
yl <- range(log10(vals)); if (diff(yl) < 0.5) yl <- mean(yl) + c(-0.5, 0.5)
plot(NA, xlim = xl, ylim = yl, xlab = "iteration", ylab = expression(log[10] ~ "rate"),
main = "learning rate (or step length) in each iteration")
for (u in runs) {
R <- u$R; it <- 0:(R$n - 1)
lines(it, log10(R$A), type = "s", col = u$col, lwd = 2)
k <- min(kk, R$n - 1L) + 1L
if (is.finite(R$A[k])) points(k - 1, log10(R$A[k]), pch = 19, col = u$col, cex = 1.4)
}
legend("topright", bty = "n", cex = 0.8,
col = sapply(runs, `[[`, "col"), lwd = 2,
legend = sapply(runs, function(u) paste0(u$s, ": ", alg_name(u$a))))
})
output$info <- renderUI({
D <- DAT(); kk <- kraw()
f5 <- function(v) formatC(v, digits = 5, format = "f")
## one row of the summary table per optimizer, with its run's note kept for below the table
row <- function(R, te, a, tag, col) {
k <- min(kk, R$n - 1L) + 1L; al <- R$A[k]
cells <- c(paste0("<b style='color:", col, "'>", tag, "</b>"), # the name goes below the table
paste0(if (a %in% MINIBATCH) "epoch " else "iteration ", k - 1L, " of ", R$n - 1L),
f5(R$L[k]),
if (lam() > 0) f5(R$F[k] - R$L[k]),
f5(te[k]),
paste0(f5(min(te)), " at ", which.min(te) - 1L),
formatC(R$GN[k], digits = 3, format = "g"),
if (is.finite(al)) paste0(formatC(al, digits = 3, format = "g"),
if (a %in% c("gdfix", "mom", "adam")) "" else " (step)")
else "–")
list(tr = paste0("<tr>", paste0("<td>", cells, "</td>", collapse = ""), "</tr>"),
note = paste0("<b style='color:", col, "'>", tag, ": ", alg_name(a), ".</b> <i>", R$note, "</i>"))
}
rows <- list(row(runA(), testA(), input$algA, "A", "#2E8B57"),
if (!is.null(runB())) row(runB(), testB(), input$algB, "B", "#1F5FBF"))
rows <- Filter(Negate(is.null), rows)
heads <- c("", "Iteration", "Loss", if (lam() > 0) "L1 penalty", "Test loss",
"Lowest test loss", "||gradient||", "Learning rate")
HTML(paste0(
"<b>p</b> = ", length(theta0()), " weights (", nunits(theta0()), " hidden units)",
"<div style='overflow-x: auto;'><table class='infotab'><tr>",
paste0("<th>", heads, "</th>", collapse = ""), "</tr>",
paste(sapply(rows, `[[`, "tr"), collapse = ""), "</table></div>",
paste(sapply(rows, `[[`, "note"), collapse = "<br>")))
})
}
shinyApp(ui, server)
About the app
Fits a Poisson neural network like the one in the book’s backpropagation section, with one covariate and \(J\) tanh hidden units (four by default, and up to 2000), to counts generated from known weights, and lets you watch nine optimizers work on it: gradient descent with a fixed learning rate, gradient descent with a line search, conjugate gradient, BFGS and L-BFGS, which use the full data, and SGD with a line search on each mini-batch, SGD with a line search judged on an independent batch, SGD with momentum and SGD with Adam, which step through mini-batches. The four units are enough for a mean with two modes: the true weights switch units 1 and 2 on and off around \(x \in (-2.2, -0.8)\), and units 3 and 4 around \((0.8, 2.2)\). The data always come from this four-unit network, whatever the number of units fitted.
Many hidden units and the L1 penalty. Hidden units sets the number \(J\) of units in the fitted network, from 4 to 2000, so the number of weights \(p = 3J + 1\) goes from 13 to 6001. The data still come from the four-unit network, so a large network is heavily overparameterized (with the default \(n = 150\), \(p > n\) from \(J = 50\)). This shows how the methods scale. A gradient costs \(O(nJ)\) for every method, but BFGS stores and updates a \(p \times p\) matrix, \(O(p^2)\) memory and work per iteration, and is not run for \(p > 2000\), that is for \(J \ge 667\): the network then keeps its starting weights, and the summary table says why. This limit is set for the browser, not by R. Each update creates several \(p \times p\) temporary matrices, more than a gigabyte at \(J = 2000\), which a webR session cannot reliably get, and webR runs the update about 30 times slower than R on a desktop, where BFGS fits even \(J = 2000\) (\(p = 6001\), a 275 MB matrix) in about 30 seconds for 100 iterations; L-BFGS and CG keep only a few vectors of length \(p\) and run for any \(J\). A fixed learning rate has to shrink as \(J\) grows: the output adds up \(J\) units, so its curvature in the output weights grows like \(J\), and an Adam step of about \(\alpha\) in every weight can move the output by about \(J\alpha\). When \(J\) changes, the app therefore sets the learning rates of fixed-rate GD, momentum and Adam to their defaults multiplied by \(4/J\), and starts from new random weights; raise a rate to see the run diverge. L1 penalty λ adds \(\lambda\sum|w|\), over the weights \(w_{j1}\) and \(v_j\) but not the intercepts, to the average loss, and every optimizer then minimizes this objective. Its gradient is taken as \(\lambda\,\mathrm{sign}(w)\), a subgradient, so the objective is no longer smooth: the weights shrink toward zero and many end near it, but a gradient method does not set them exactly to zero (that needs a proximal step, which soft-thresholds the weights), and the line-search methods, which assume a smooth objective, can stall. The training loss in the loss plot and the summary table is the loss without the penalty, so it compares directly with the test loss; the summary table gives the penalty separately. Compare the test loss of a large network with and without the penalty. To keep the browser responsive, a run stores at most 4 million numbers of its path, so a large network may stop earlier (the summary table reports it), and the test loss is computed at up to 100 iterations and interpolated between them. In the browser, R runs as WebAssembly and is many times slower than on a desktop: with the default settings, the two runs take about half a minute for 256 units and about two minutes for 1000; lower Max iterations for a quicker look.
The weights. The network panels belong to one optimizer, chosen by Network of above them. The network shows the weights of hidden units 1 to 4 and the output intercept at the current iteration (all thirteen weights when \(J = 4\)). With more units, the vertical dots below unit 4 stand for units 5 to \(J\), which are fitted in the same way but not drawn; their weights still count in the colour scale. The eight weights on edges (w11, …, w41 from \(x\) to the hidden units and v1, …, v4 from the hidden units to the output) are written on their edges, and each intercept (w10, …, w40 and v0) is a node of its own, a box hung on the neuron it shifts. Colour shows the value (blue negative, red positive; on an edge it also sets the width). The arrows beside a value change that weight (up and down on an edge, right to increase and left to decrease on an intercept box), and the starting point of the run changes with it. True Value loads the weights that generated the data (with more than four units, units 5 to \(J\) get output weight 0 and random input weights, so the starting curve is the true one), Random draws a new set (for the scaled predictor, drawn for \(x\) divided by the scale; the output weights have standard deviation \(2/\sqrt{J}\), so the starting curve has about the same size for any \(J\)), and Zero sets every weight to 0 (a saddle point of the loss: with all hidden weights at zero, only \(v_0\) has a nonzero gradient). Adjust Size sets how much one click on an arrow changes a weight.
The methods. Write \(g_k = \nabla L(\theta_k)\) for the gradient of the average loss \(L\) over all \(n\) observations at the current weights, \(\ell_i\) for the loss of observation \(i\), and \(g_k^{(B_k)} = \frac{1}{m}\sum_{i \in B_k} \nabla \ell_i(\theta_k)\) for the gradient of the mini-batch \(B_k\) of \(m\) observations used at update \(k\) (the superscript names the batch, the subscript the iteration). The first five optimizers in the menu use the full data; the last four step through mini-batches. All of them can be written as one update
\[\theta_{k+1} = \theta_k - \alpha_k\, P_k\, m_k ,\]
where \(m_k\) is the gradient actually used (the full gradient, a mini-batch gradient, or an average of past ones), \(P_k\) is a preconditioner that rescales or rotates the step, and \(\alpha_k\) is the step size.
| Optimizer | Gradient used, \(m_k\) | Preconditioner, \(P_k\) | Step size, \(\alpha_k\) |
|---|---|---|---|
| GD, fixed rate | \(g_k\) | \(I\) | \(\alpha\), set by hand |
| GD + line search | \(g_k\) | \(I\) | \(\alpha_k\) from a Wolfe line search |
| Conjugate gradient (PR+) | \(d_k = -g_k + \beta_k d_{k-1}\), with \(\beta_k = \max\!\Big(0, \dfrac{g_k^\top (g_k - g_{k-1})}{g_{k-1}^\top g_{k-1}}\Big)\) | implicit: the new gradient is combined with the previous direction | \(\alpha_k\) from a Wolfe line search |
| BFGS | \(g_k\) | \(B_k \approx H^{-1}\), a full matrix, updated by \(B_{k+1} = (I - \rho\, s y^\top) B_k (I - \rho\, y s^\top) + \rho\, s s^\top\) with \(s = \theta_{k+1} - \theta_k\), \(y = g_{k+1} - g_k\), \(\rho = 1/(s^\top y)\); not run for \(p > 2000\) | \(\alpha_k\) from a Wolfe line search |
| L-BFGS | \(g_k\) | \(H_k\), never formed: the product \(H_k g_k\) is computed from the last \(\ell\) pairs \((s_i, y_i)\) by a two-loop recursion, starting from a scalar multiple \(\gamma_k I\) with \(\gamma_k = s^\top y / y^\top y\) (memory \(\ell\) is the Memory selector) | \(\alpha_k\) from a Wolfe line search |
| SGD + line search | \(g_k^{(B_k)}\), with \(E\,g_k^{(B_k)} = g_k\) | \(I\) | \(\alpha_k\) by backtracking on the loss of the mini-batch \(B_k\): start at the learning rate and halve until \(L^{(B_k)}(\theta_k - \alpha g_k^{(B_k)}) \le L^{(B_k)}(\theta_k) - c_1 \alpha \|g_k^{(B_k)}\|^2\) |
| SGD + line search, independent batch | \(g_k^{(B_k)}\) | \(I\) | \(\alpha_k\) by backtracking on the loss of a second random mini-batch \(C_k\) of \(m\) cases, the same cases at both points: start at twice the last accepted step and halve until \(L^{(C_k)}(\theta_k - \alpha g_k^{(B_k)}) \le L^{(C_k)}(\theta_k) - c_1 \alpha \|g_k^{(B_k)}\|^2\); no step if none is found |
| SGD + momentum | \(v_k = \mu\, v_{k-1} + g_k^{(B_k)}\), an exponentially weighted sum of past mini-batch gradients | \(I\) | \(\alpha\), set by hand |
| SGD + Adam | \(\hat m_k = \dfrac{(1-\beta_1)\sum_{j \le k} \beta_1^{k-j} g_j^{(B_j)}}{1-\beta_1^{k}}\), a bias-corrected average of past mini-batch gradients | \(\mathrm{diag}\big(1/(\sqrt{\hat v_k} + \epsilon)\big)\), with \(\hat v_k = \dfrac{(1-\beta_2)\sum_{j \le k} \beta_2^{k-j} g_j^{(B_j)} \odot g_j^{(B_j)}}{1-\beta_2^{k}}\) | \(\alpha\), set by hand |
In the app \(\beta_1 = 0.9\), \(\beta_2 = 0.999\) and \(\epsilon = 10^{-8}\) for Adam, and \(k\) counts mini-batch updates. Momentum is coded as \(v \leftarrow \mu v - \alpha g^{(B)}\), \(\theta \leftarrow \theta + v\), the same update written with the sign and \(\alpha\) absorbed into \(v\). A Wolfe line search takes the step \(\alpha\) along \(d_k = -P_k m_k\) that satisfies both \(L(\theta_k + \alpha d_k) \le L(\theta_k) + c_1 \alpha\, g_k^\top d_k\) (sufficient decrease) and \(\nabla L(\theta_k + \alpha d_k)^\top d_k \ge c_2\, g_k^\top d_k\) (curvature), with \(c_1 = 10^{-4}\) and \(c_2 = 0.9\).
What each one changes. Fixed-rate GD and the line-search methods use the exact gradient. A line search removes the learning rate to tune; conjugate gradient and BFGS also change the direction, CG by combining the gradient with the previous direction and BFGS by learning an approximation of the inverse Hessian from gradient differences, a full-matrix preconditioner (compare Newton’s method, \(P_k = H^{-1}\)); L-BFGS keeps only the last few difference pairs, which costs \(O(\ell p)\) instead of \(O(p^2)\) storage and is the practical form for large \(p\). The four SGD methods replace the gradient by a cheap and noisy mini-batch gradient. SGD with a line search chooses each step by backtracking on the loss of the batch itself, so the step is adapted to the batch and not to the whole loss. The direction was fitted to that batch, so the batch overstates how much the step helps, much as a model’s training loss overstates its fit. The independent-batch version judges the step on a second random batch \(C_k\) instead, using the same cases at the current and the trial weights, so the change in loss is estimated precisely (a paired comparison, as in a panel survey); a step that does not reduce the loss of \(C_k\) enough is not taken. Each search starts from twice the last accepted step, so the learning rate sets only the first step. The check costs loss evaluations on \(C_k\) but no gradients, and about a third of the steps are typically rejected, which the summary table reports. Both are steepest-descent methods, so neither removes the zig-zag across a narrow valley: with four units both do poorly, while with many units the independent check is clearly better and hardly depends on the learning rate. Momentum averages the mini-batch gradients, which damps their noise and the zig-zag across a valley. Adam also divides each coordinate by the square root of a running average of its squared gradients, a per-coordinate step size; why this helps so much is not fully understood (see the book’s discussion).
The learning rate plot. The plot under the loss plot shows the learning rate of each run in each iteration; for the line-search methods it shows the mean accepted step length.
When a run stops. A run ends at the first of: the full-data gradient norm falls below the tolerance in Stop: ||g|| <; if Stop if flat for is set, the full-data loss has not improved by 0.001% in that many consecutive iterations (a patience rule, off by default, the only kind that can stop a noisy method, whose gradient norm never gets small; it also ends a method that has stalled on a plateau, so read the message in the summary table); or the maximum number of iterations. The summary table says which one applied. A mini-batch run is also capped at 100000 mini-batch updates, which it reports. A conjugate-gradient or BFGS run whose line search fails first restarts from steepest descent, and ends only if that fails too.
Test loss. A method is judged by how well the fit predicts new observations, not by the training loss, which a flexible network can drive below the noise floor by fitting the noise. The test loss is computed on 1000 observations drawn once from the same generating process (with the same scale of \(x\)), at every iteration, so you can see where it is lowest (given in the summary table) and how it rises after that if the training loss keeps falling, the signature of overfitting and the reason for early stopping.
Epochs and mini-batches. For the four SGD methods one iteration is one epoch: a shuffled pass of \(\lceil n/m \rceil\) mini-batch updates over all the data. An iteration therefore costs about as many gradient evaluations as one full-batch step of the other methods, and the iteration axes are directly comparable. This is the point of the comparison. After the same number of passes through the data, the mini-batch methods have made \(n/m\) updates per pass where gradient descent has made one, so on a large sample they are well ahead of a full-batch method such as GD + line search in the plots. With the batch size equal to \(n\) the four methods use the full gradient. The loss and gradient norm shown are always those of the full data. The sample size goes up to 2000: the larger \(n\) is, the more mini-batch updates an epoch holds (\(n/m\)), and the clearer the advantage over the full-batch methods becomes. With four units (thirteen parameters) and a small sample, BFGS is hard to beat; SGD, momentum and Adam are what larger networks use, where a Hessian approximation is too expensive and a pass through all the data is rarely made. To keep the browser responsive a mini-batch run stops after 100000 updates in all, which the summary table reports.
Scale of \(x\). The predictor is multiplied by this factor and the slope weights of the generating network are divided by it, so the true curve is the same function of \(x\) divided by the scale and only the parameterization changes. The gradient with respect to a slope weight \(w_{j1}\) carries a factor \(x\) and the gradient with respect to an intercept does not, so a scale far from 1 makes the gradients of the weights differ by orders of magnitude. A single learning rate is then right for some weights and wrong for others: fixed-rate GD and momentum must shrink it to suit the most sensitive weight, which makes the other weights crawl, while Adam, which rescales each weight separately, needs a smaller change. When the scale changes, the app resets each learning rate to a value divided by \(s^2\) for fixed-rate GD, SGD and momentum (the curvature in a slope weight grows like \(s^2\)) and by \(s\) for Adam (its step is measured in the weight itself, which shrinks like \(1/s\)), and multiplied by \(4/J\) for the number of units; raise the rate again to see the instability, and use True Value as the start to see the noise of the mini-batch methods around a good fit. The line-search methods are less sensitive, because the step length adapts, but BFGS and CG slow down when the problem is badly scaled. Changing the scale restarts the run.
The fit. The panel above the network shows the generated counts, the true mean curve (dashed red, with its two modes), the mean curve at the starting weights (grey) and the current fit (green). Two optimizers, A (green) and B (blue, or None), are run from the same start on the same data, each with its own settings, and both fits are drawn at the same iteration, so any two of the methods can be compared; the loss plot shows both paths. The default pair is SGD with Adam against gradient descent with a line search, which shows what the mini-batch updates buy per pass through the data. Because \(\log\lambda = v_0 + \sum_j v_j h_j\), the units combine by adding in the exponent, not by adding curves, so the second plot shows the fit on the log scale: the scaled units \(v_j h_j\) (dotted; orange, blue, black and cyan for units 1 to 4, and grey for units 5 to \(J\) added together) simply add up to \(\log\lambda\) (green), and the true \(\log\lambda\) (dashed red) is the target. The box above the plots shows or hides this second plot; it is off by default. Beneath the fit is the loss per iteration, for the training sample (solid) and for an independent test sample (dashed). The loss is the full average negative log-likelihood, \(\frac1n\sum_i \big(\lambda_i - y_i \log\lambda_i + \log y_i!\big)\): the \(\log y_i!\) term does not depend on the weights and does not change the fit, but without it the training and test losses would sit on different baselines, because the two samples have different counts. The loss plot is on a log10 scale by default, since the loss is often close to its floor and the methods differ only in the last digits; the buttons under it switch to the loss itself, or to the log of the loss minus the smallest value either run reaches, which makes the rate of convergence readable. The first row of controls sets up the data and the model (sample size, scale of \(x\), number of hidden units, L1 penalty, and a new dataset); the next two rows choose optimizers A and B and the settings of each (learning rate, momentum, mini-batch size); the last row holds the maximum number of iterations, the colour contrast, the playback buttons, and a slider that shows the fit at any iteration of the run (it follows the playback, and you can drag it to scrub through the run). A new run is shown at its last iteration; untick Auto Display of Last Iteration (under the playback buttons) to show it at iteration 0 instead, with the starting weights and the starting curve, which is the better view for seeing how the network is built. The box Run Optimizations at the end of the row of weight buttons is ticked by default; untick it to freeze the optimization, so that the plots show the starting weights only (use True Value, Random, Zero and the network plot to change them, with Show the units ticked to see how the units add up to the curve). The loss is not convex, so different starts can end at different fits; try Random a few times.
A Gaussian version of this app, for regression with normal noise, is Fitting a Gaussian Neural Network by Gradient Methods.
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)
}
## ------------------------------------------------------------------- model
## One covariate x, four tanh hidden units, log link, Poisson counts:
## a_j = w_j1 x + w_j0, h_j = tanh(a_j), eta = v_0 + sum_j v_j h_j,
## lambda = exp(eta).
## The data come from four units; the fitted network has J >= 4 units (chosen in the app).
## theta = (w11..wJ1, w10..wJ0, v1..vJ, v0), so p = 3 J + 1 weights
nunits <- function(th) (length(th) - 1) %/% 3
## two bumps in the mean: units 1, 2 switch on and off over (-2.2, -0.8),
## units 3, 4 over (0.8, 2.2), so lambda(x) has two modes
TRUE_THETA <- c(2.5, 2.5, 2.5, 2.5, 5.5, 2, -2, -5.5, 1.2, -1.2, 1.0, -1.0, -0.5)
## the same function as a network of J units: units 5 to J get output weight 0, and
## fixed random input weights (with zero input weights too they could never move)
embed_theta <- function(th4, J) {
if (J <= 4) return(th4)
set.seed(77); e <- J - 4
c(th4[1:4], rnorm(e), th4[5:8], rnorm(e), th4[9:12], rep(0, e), th4[13])
}
fwd <- function(th, x) {
J <- nunits(th)
H <- tanh(outer(x, th[1:J]) + rep(th[J + 1:J], each = length(x)))
list(H = H, eta = as.vector(th[3 * J + 1] + H %*% th[2 * J + 1:J]))
}
lambda_fun <- function(th, x) exp(fwd(th, x)$eta)
## the scaled units v_j h_j(x), one column per hidden unit
unit_terms <- function(th, x) { J <- nunits(th); sweep(fwd(th, x)$H, 2, th[2 * J + 1:J], "*") }
## average Poisson negative log-likelihood, with the log y! term: it does not depend on
## the weights, but without it the training and test losses would differ by a constant
nll <- function(th, x, y) {
e <- fwd(th, x)$eta
v <- mean(exp(e) - y * e + lfactorial(y))
if (is.finite(v)) v else Inf
}
## its gradient by backpropagation: delta_eta -> delta_a -> weights
nll_grad <- function(th, x, y) {
J <- nunits(th)
E <- fwd(th, x)
d_eta <- exp(E$eta) - y # n
d_a <- (1 - E$H^2) * outer(d_eta, th[2 * J + 1:J]) # n x J
c(colSums(d_a * x), # w_j1
colSums(d_a), # w_j0
as.vector(crossprod(E$H, d_eta)), # v_j
sum(d_eta)) / length(x) # v_0
}
## the L1 penalty lambda * sum |w| applies to the weights w_j1 and v_j, not to the intercepts
pen_mask <- function(th) { J <- nunits(th); r <- rep(1, length(th)); r[c(J + 1:J, 3 * J + 1)] <- 0; r }
make_data <- function(n, seed) {
set.seed(100 + seed)
x <- runif(n, -3, 3)
y <- rpois(n, lambda_fun(TRUE_THETA, x))
## a fixed vertical offset, drawn once with the data, so the points stay put
list(x = x, y = y, yj = y + runif(n, -0.12, 0.12))
}
## random starting weights: the output weights v_j have sd 2 / sqrt(J), so the
## starting curve has about the same size whatever the number of units
rand_start <- function(seed, J) {
set.seed(2000 + seed)
c(rnorm(2 * J), rnorm(J, 0, 2 / sqrt(J)), 0)
}
## ------------------------------------------------------- Wolfe line search
line_search <- function(f, g, x, d, a0 = 1, c1 = 1e-4, c2 = 0.9) {
f0 <- f(x); gd0 <- sum(g(x) * 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 {
if (sum(g(x + a * d) * 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
## the methods that step through mini-batches: one iteration is one epoch
MINIBATCH <- c("sgdls", "sgdls2", "mom", "adam")
## Row k of P (the weights), and element k of F (the objective), L (the loss
## without the penalty) and GN (the gradient norm), is the state after k - 1 steps;
## A[k] is the step length that led to it. The objective is the loss plus the L1
## penalty lam * sum |w|, whose gradient is taken as lam * sign(w) (a subgradient).
run_alg <- function(alg, th0, x, y, maxit, lr = 0.1, mom = 0.9, m = 20,
tol = 1e-6, patience = Inf, rtol = 1e-5, lmem = 10, lam = 0) {
p <- length(th0)
pm <- lam * pen_mask(th0)
f <- function(th) nll(th, x, y) + sum(pm * abs(th))
g <- function(th) nll_grad(th, x, y) + pm * sign(th)
n <- 0; note <- "maximum number of iterations reached"
if (alg == "bfgs" && p > 2000) { # B alone would take p^2 numbers
return(list(P = matrix(th0, 1), F = f(th0), L = nll(th0, x, y),
GN = sqrt(sum(g(th0)^2)), A = NA_real_, n = 1,
note = paste0("BFGS not run: its p x p matrix would hold ",
format(p^2, big.mark = ","), " numbers (p = ", p,
"); use L-BFGS")))
}
## state for the fixed-rate rules
n_obs <- length(x); m <- max(1, min(m, n_obs))
capped <- FALSE
if (alg %in% MINIBATCH) { # keep the number of mini-batch steps in check
cap <- max(1, floor(100000 / ceiling(n_obs / m)))
if (maxit > cap) { maxit <- cap; capped <- TRUE }
}
stored <- FALSE # keep the stored path to 4 million numbers
if ((maxit + 1) * p > 4e6) { maxit <- floor(4e6 / p) - 1; stored <- TRUE }
P <- matrix(NA_real_, maxit + 1, p)
Fv <- Lv <- GN <- AL <- rep(NA_real_, maxit + 1)
th <- th0; B <- if (alg == "bfgs") diag(p) else NULL
g_prev <- d_prev <- s_prev <- NULL
Sh <- Yh <- list() # the stored pairs of L-BFGS
best_f <- Inf; best_k <- 1 # the best loss so far, and when it was reached
vel <- m1 <- m2 <- numeric(p) # momentum velocity; Adam moments
a_prev <- lr / 2; nrej <- 0; nsteps <- 0 # the independent-batch line search
tt <- 0 # mini-batch updates so far (Adam)
if (alg %in% MINIBATCH) set.seed(11)
for (k in 1:(maxit + 1)) {
gk <- g(th); lk <- nll(th, x, y); fk <- lk + sum(pm * abs(th))
P[k, ] <- th; GN[k] <- sqrt(sum(gk^2)); Fv[k] <- fk; Lv[k] <- lk; n <- k
if (!is.finite(fk) || !all(is.finite(gk))) { note <- "diverged"; break }
if (tol > 0 && sqrt(sum(gk^2)) < tol) {
note <- paste0("converged: gradient norm < ", format(tol)); break
}
## no stopping rule can be exact for a noisy method, so every method also stops when the
## full-data loss has not improved by a fraction rtol for `patience` iterations
if (k == 1 || fk < best_f - rtol * abs(best_f)) { best_f <- fk; best_k <- k }
if (k - best_k >= patience) {
note <- paste0("stopped: the loss has not improved by ", 100 * rtol, "% in ",
patience, " iterations"); break
}
if (k > maxit) break
if (alg == "gdfix") { # full-batch gradient, fixed learning rate
AL[k + 1] <- lr
th <- th - lr * gk
next
}
if (alg %in% MINIBATCH) { # one iteration is one epoch: a shuffled pass
perm <- sample.int(n_obs) # of mini-batch steps over all the data, so
al <- numeric(0) # it costs about one full-batch gradient
for (s0 in seq(1, n_obs, by = m)) {
idx <- perm[s0:min(s0 + m - 1, n_obs)]
xb <- x[idx]; yb <- y[idx]
gb <- nll_grad(th, xb, yb) + pm * sign(th) # the gradient of mini-batch B_k
if (alg == "sgdls") { # backtracking line search on the batch objective
fb <- nll(th, xb, yb) + sum(pm * abs(th)); a <- lr; gg <- sum(gb^2)
for (j in 1:30) {
fa <- nll(th - a * gb, xb, yb) + sum(pm * abs(th - a * gb))
if (is.finite(fa) && fa <= fb - 1e-4 * a * gg) break
a <- a / 2
}
al <- c(al, a)
th <- th - a * gb
} else if (alg == "sgdls2") { # the same search, judged on an independent batch C:
ic <- sample.int(n_obs, length(idx)) # the step is checked on cases it was not fitted to,
xc <- x[ic]; yc <- y[ic] # with the same cases at both points (a paired estimate)
fc <- nll(th, xc, yc) + sum(pm * abs(th)); gg <- sum(gb^2)
a <- min(2 * a_prev, 1e3); ok <- FALSE # start from twice the last accepted step
for (j in 1:30) {
fa <- nll(th - a * gb, xc, yc) + sum(pm * abs(th - a * gb))
if (is.finite(fa) && fa <= fc - 1e-4 * a * gg) { ok <- TRUE; break }
a <- a / 2
}
nsteps <- nsteps + 1
if (ok) { th <- th - a * gb; a_prev <- a; al <- c(al, a) } else nrej <- nrej + 1
} else if (alg == "mom") { # heavy ball on the batch gradient
vel <- mom * vel - lr * gb
th <- th + vel
} else { # Adam on the batch gradient
tt <- tt + 1
m1 <- 0.9 * m1 + 0.1 * gb
m2 <- 0.999 * m2 + 0.001 * gb^2
th <- th - lr * (m1 / (1 - 0.9^tt)) / (sqrt(m2 / (1 - 0.999^tt)) + 1e-8)
}
}
AL[k + 1] <- if (alg %in% c("sgdls", "sgdls2")) (if (length(al)) mean(al) else 0) else lr
next
}
if (alg == "gd") {
d <- -gk
} else if (alg == "cg") {
if (is.null(d_prev)) {
d <- -gk
} else {
yk <- gk - g_prev
beta <- max(0, sum(gk * yk) / max(sum(g_prev^2), 1e-300)) # PR+
d <- -gk + beta * d_prev
}
if (sum(gk * d) > -1e-12) d <- -gk # restart
} else if (alg == "lbfgs") { # L-BFGS: two-loop recursion
if (!is.null(s_prev)) {
yk <- gk - g_prev; sy <- sum(s_prev * yk)
if (sy > 1e-10) {
Sh <- c(Sh, list(s_prev)); Yh <- c(Yh, list(yk))
if (length(Sh) > lmem) { Sh <- Sh[-1]; Yh <- Yh[-1] }
}
}
q <- gk; nh <- length(Sh); al <- numeric(nh)
for (i in rev(seq_len(nh))) {
al[i] <- sum(Sh[[i]] * q) / sum(Yh[[i]] * Sh[[i]])
q <- q - al[i] * Yh[[i]]
}
if (nh > 0) q <- q * sum(Sh[[nh]] * Yh[[nh]]) / sum(Yh[[nh]]^2) # initial scaling
for (i in seq_len(nh)) {
be <- sum(Yh[[i]] * q) / sum(Yh[[i]] * Sh[[i]])
q <- q + Sh[[i]] * (al[i] - be)
}
d <- -q
if (sum(gk * d) > -1e-12) { Sh <- Yh <- list(); d <- -gk }
} else { # BFGS
if (!is.null(s_prev)) {
yk <- gk - g_prev; sy <- sum(s_prev * yk)
if (sy > 1e-10) {
if (k == 2) B <- (sy / sum(yk^2)) * diag(p) # scale the first B
## B <- (I - rho s y') B (I - rho y s') + rho s s', in O(p^2) operations
rho <- 1 / sy; By <- as.vector(B %*% yk)
B <- B + (rho^2 * (sy + sum(yk * By))) * outer(s_prev, s_prev) -
rho * (outer(By, s_prev) + outer(s_prev, By))
}
}
d <- -as.vector(B %*% gk)
if (sum(gk * d) > -1e-12) { B <- diag(p); d <- -gk }
}
a0 <- if (alg %in% c("bfgs", "lbfgs") && k > 1) 1 else min(1, 1 / sqrt(sum(d^2)))
ls <- line_search(f, g, th, d, a0)
if (!ls$ok && alg != "gd") { # restart from steepest descent before giving up
d <- -gk; if (alg == "bfgs") B <- diag(p)
d_prev <- s_prev <- g_prev <- NULL; Sh <- Yh <- list()
ls <- line_search(f, g, th, d, min(1, 1 / sqrt(sum(d^2))))
}
if (!ls$ok) { note <- "line search failed"; break }
AL[k + 1] <- ls$alpha
s_prev <- ls$alpha * d; g_prev <- gk; d_prev <- d
th <- th + s_prev
}
if (capped && grepl("^maximum", note))
note <- paste0("stopped after ", maxit, " epochs (100000 mini-batch steps)")
if (stored && grepl("^maximum", note))
note <- paste0("stopped after ", maxit, " iterations, to keep the stored path of the ",
p, " weights within 4 million numbers")
if (alg == "sgdls2" && nsteps > 0)
note <- paste0(note, "; ", round(100 * nrej / nsteps), "% of the mini-batch steps were not ",
"taken (no sufficient decrease on the check batch)")
i <- seq_len(n)
list(P = P[i, , drop = FALSE], F = Fv[i], L = Lv[i], GN = GN[i],
A = AL[i], n = n, note = note)
}
ALGS <- c("Gradient descent, fixed learning rate" = "gdfix",
"Gradient descent + line search" = "gd",
"Conjugate gradient (Polak-Ribiere+)" = "cg",
"BFGS (quasi-Newton)" = "bfgs",
"L-BFGS (limited memory)" = "lbfgs",
"SGD + line search (on each mini-batch)" = "sgdls",
"SGD + line search (on an independent batch)" = "sgdls2",
"SGD + momentum" = "mom",
"SGD + Adam" = "adam")
alg_name <- function(a) if (a == "none") "none" else names(ALGS)[ALGS == a]
## --------------------------------------------------------- network layout
## Weights sit on the edges; each intercept is a node of its own, a box with
## the value and its arrows, hung on the neuron it shifts. Only the first JS = 4
## hidden units are drawn, with vertical dots below them for any others. A slot is
## one drawn weight; show_idx(J) gives the position of each slot in theta.
JS <- 4
NPS <- 3 * JS + 1 # weights drawn
NAMES <- c(paste0("w", 1:JS, "1"), paste0("w", 1:JS, "0"), paste0("v", 1:JS), "v0")
BIASIDX <- c(JS + 1:JS, NPS) # the intercept slots
show_idx <- function(J) c(1:JS, J + 1:JS, 2 * J + 1:JS, 3 * J + 1)
NX <- c(0.07, 0.50) # (x, y) of the input node
YH <- seq(0.88, 0.12, length.out = JS); XH <- 0.60 # hidden nodes
NO <- c(1.13, 0.50) # output node
at <- function(p, q, f) p + f * (q - p) # a point along an edge
## hidden intercepts hang above the upper half of the hidden nodes and below the rest
YB <- YH + rep(c(0.14, -0.14), each = JS / 2)
BIAS <- c(rep(0.56, JS), 1.00) # x of the intercept boxes
BIASY <- c(YB, 0.17) # y of the intercept boxes
## where each weight's value and arrows sit
ADJ <- local({
hj <- lapply(1:JS, function(j) c(XH, YH[j]))
pos <- c(lapply(1:JS, function(j) at(NX, hj[[j]], 0.50)), # w_j1: x -> h_j
lapply(1:JS, function(j) c(BIAS[j], BIASY[j])), # w_j0: box on h_j
lapply(1:JS, function(j) at(hj[[j]], NO, 0.50)), # v_j: h_j -> out
list(c(BIAS[JS + 1], BIASY[JS + 1]))) # v_0: box on output
data.frame(idx = 1:NPS, sym = NAMES,
x = sapply(pos, `[`, 1), y = sapply(pos, `[`, 2),
stringsAsFactors = FALSE)
})
## the arrows beside each value (also the click targets): up / down beside an
## edge weight, left / right beside an intercept box
AX <- 0.104 # arrow offset from the value
isb <- ADJ$idx %in% BIASIDX
ARROWS <- rbind(
data.frame(idx = ADJ$idx, dir = +1, horiz = isb,
ax = ifelse(isb, ADJ$x + AX, ADJ$x + AX),
ay = ifelse(isb, ADJ$y, ADJ$y + 0.028)),
data.frame(idx = ADJ$idx, dir = -1, horiz = isb,
ax = ifelse(isb, ADJ$x - AX, ADJ$x + AX),
ay = ifelse(isb, ADJ$y, ADJ$y - 0.028)))
## ---------------------------------------------------------------- colours
## Diverging ramp: blue = negative, red = positive, depth by magnitude.
DIV <- colorRampPalette(c("#08306B", "#2171B5", "#6BAED6", "#DEEBF7",
"#F7F7F7",
"#FEE0D2", "#FC9272", "#CB181D", "#67000D"))(201)
## compander: maps v in [-vmax, vmax] to [-1, 1], boosting small values
tone <- function(v, vmax, k) {
u <- pmax(-1, pmin(1, v / vmax))
sign(u) * log1p(k * abs(u)) / log1p(k)
}
hcol <- function(v, vmax, k) DIV[round((tone(v, vmax, k) + 1) * 100) + 1]
## th is the full weight vector; the first JS units and v0 are drawn, and the
## other units, if any, are marked by vertical dots below unit JS
draw_net <- function(th, vmax, k, main, arrows = TRUE, digits = 2) {
J <- nunits(th); more <- J - JS; v <- th[show_idx(J)]
col <- hcol(v, vmax, k); lw <- 0.8 + 6 * abs(tone(v, vmax, k))
yb <- if (more > 0) -0.17 else 0 # the colour bar moves down for the dots
plot.new(); plot.window(c(0, 1.2), c(-0.25 + yb, 1.08))
title(main = main, cex.main = 1.05)
H <- cbind(XH, YH)
if (more > 0) { # the units not drawn: faint edges and dots
yd <- -0.14
segments(NX[1], NX[2], XH, yd + 0.04, col = "grey75", lty = 2)
segments(XH, yd + 0.04, NO[1], NO[2], col = "grey75", lty = 2)
points(rep(XH, 3), yd + c(0.03, -0.01, -0.05), pch = 19, cex = 0.7)
text(XH + 0.05, yd - 0.01, adj = 0, cex = 0.8, col = "grey25",
sprintf("units %d to %d not shown (%d more)", JS + 1, J, more))
}
## edges, each carrying one weight: x -> h_j (w_j1), h_j -> output (v_j)
for (j in 1:JS) {
segments(NX[1], NX[2], H[j, 1], H[j, 2], col = col[j], lwd = lw[j], lend = 1)
segments(H[j, 1], H[j, 2], NO[1], NO[2], col = col[2 * JS + j], lwd = lw[2 * JS + j], lend = 1)
}
## intercept nodes: a thin arrow from each box to the neuron it shifts
tgt <- rbind(H, NO)
for (i in seq_along(BIASIDX)) {
b <- ADJ[BIASIDX[i], ]
dy <- sign(tgt[i, 2] - b$y)
if (i == JS + 1) arrows(b$x, b$y + 0.03, NO[1] - 0.03, NO[2] - 0.03, length = 0.08,
col = "grey45", lwd = 1.4)
else arrows(b$x, b$y + dy * 0.035, tgt[i, 1], tgt[i, 2] - dy * 0.035,
length = 0.08, col = "grey45", lwd = 1.4)
}
## nodes
points(rbind(NX, H, NO), pch = 21, cex = 3.2, bg = "white", lwd = 1.6)
text(NX[1], NX[2], "x", font = 2)
text(H[, 1], H[, 2], paste0("h", 1:JS), cex = 0.8)
text(NO[1], NO[2], expression(lambda), cex = 1.1)
## values: an intercept is a box coloured by its value; an edge weight is
## plain text on a white patch so the edge does not strike through it
for (i in 1:NPS) {
b <- ADJ[i, ]; isb <- i %in% BIASIDX
if (isb) rect(b$x - 0.075, b$y - 0.036, b$x + 0.075, b$y + 0.036,
col = col[i], border = "grey35")
else rect(b$x - 0.072, b$y - 0.028, b$x + 0.072, b$y + 0.028,
col = adjustcolor("white", 0.8), border = NA)
dark <- abs(tone(v[i], vmax, k)) > 0.62
text(b$x, b$y, sprintf(paste0("%s=%.", digits, "f"), b$sym, v[i]),
cex = 0.85, font = if (isb) 1 else 2,
col = if (isb) { if (dark) "white" else "black" }
else if (dark) col[i] else "grey20")
}
if (arrows) for (r in seq_len(nrow(ARROWS))) {
a <- ARROWS[r, ]
if (a$horiz) # left / right: -, +
polygon(a$ax + a$dir * c(-0.013, -0.013, 0.015),
a$ay + c(-0.033, 0.033, 0), col = "grey30", border = NA)
else # down / up: -, +
polygon(a$ax + c(-0.026, 0.026, 0), a$ay + a$dir * c(-0.016, -0.016, 0.02),
col = "grey30", border = NA)
}
## signed colour bar
xs <- seq(0.12, 1.08, length.out = 201)
rect(xs, -0.24 + yb, xs + diff(xs)[1], -0.19 + yb, col = DIV, border = NA)
lab <- formatC(vmax, format = "g", digits = 2)
text(c(0.12, 0.60, 1.08), -0.16 + yb, c(paste0("-", lab), "0", paste0("+", lab)),
cex = 0.72)
}
## --------------------------------------------------------------------- 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;")
row_label <- function(txt)
column(1, div(style = "padding-top: 28px;", tags$b(txt)))
## learning rates on a roughly logarithmic grid (rates need to range over orders of magnitude)
LRGRID <- c(1e-5, 3e-5, 1e-4, 3e-4, 1e-3, 3e-3, 0.01, 0.03, 0.1, 0.3, 1)
LRCHOICES <- setNames(as.character(LRGRID), format(LRGRID, scientific = FALSE, drop0trailing = TRUE))
## one optimizer: its menu, then the parameters that belong to the chosen method
opt_row <- function(s, selected, col, none = FALSE) {
a <- paste0("input.alg", s)
has_lr <- paste0("['gdfix', 'sgdls', 'sgdls2', 'mom', 'adam'].indexOf(", a, ") >= 0")
has_b <- paste0("['sgdls', 'sgdls2', 'mom', 'adam'].indexOf(", a, ") >= 0")
fluidRow(
column(1, div(style = paste0("padding-top: 28px; font-size: 20px; color: ", col, ";"),
tags$b(s))),
column(3, selectInput(paste0("alg", s), "Optimizer",
choices = if (none) c("None" = "none", ALGS) else ALGS,
selected = selected, width = "100%")),
column(8,
conditionalPanel(has_lr,
div(class = "steprule",
div(class = "lrbox", selectInput(paste0("lr", s), "Learning rate (first step if line search)",
choices = LRCHOICES, selected = "0.3", width = "100%")),
conditionalPanel(paste0(a, " == 'mom'"),
div(sliderInput(paste0("mom", s), "Momentum", min = 0, max = 0.99,
value = 0.9, step = 0.01, width = "100%"))),
conditionalPanel(has_b,
div(selectInput(paste0("batch", s), "Mini-batch size",
choices = c("5" = 5, "10" = 10, "20" = 20, "50" = 50,
"100" = 100, "all n (full batch)" = 1e6),
selected = 20, width = "100%"))))),
conditionalPanel(paste0(a, " == 'lbfgs'"),
div(class = "steprule",
div(selectInput(paste0("mem", s), "Memory (pairs kept)",
choices = c(2, 5, 10, 20), selected = 10, width = "100%")),
div(style = "padding-top: 28px;",
helpText("The step length comes from a Wolfe line search.")))),
conditionalPanel(paste0(has_lr, " == false && ", a, " != 'none' && ", a, " != 'lbfgs'"),
div(style = "padding-top: 28px;",
helpText("The step length comes from a Wolfe line search."))))
)
}
ui <- fluidPage(
## the iteration slider is the only state: the browser moves it (play timer, buttons,
## dragging), and the server just reads input$kshow
tags$head(tags$script(HTML("
var ktimer = null, kdrag = false, kself = false, kuser = 0;
function kcur() { return parseInt($('#kshow').val()); }
function kslider() { return $('#kshow').data('ionRangeSlider'); }
function kset(v) {
var s = kslider(); if (!s) return;
kself = true;
s.update({from: Math.max(s.options.min, Math.min(s.options.max, v))});
$('#kshow').trigger('change'); kself = false; }
function kplay(on) {
if (ktimer) { clearInterval(ktimer); ktimer = null; }
$('#play i').removeClass('fa-play fa-pause').addClass(on ? 'fa-pause' : 'fa-play');
if (!on) return;
var s = kslider(); if (s && kcur() >= s.options.max) kset(0);
ktimer = setInterval(function() {
if (kdrag || Date.now() - kuser < 600) return; // the user is on the slider
var s = kslider();
if (kcur() >= s.options.max) kplay(false); else kset(kcur() + 1);
}, 300); }
['mousedown', 'touchstart', 'pointerdown'].forEach(function(ev) {
document.addEventListener(ev, function(e) {
if ($(e.target).closest('.shiny-input-container').find('#kshow').length) {
kdrag = true; kuser = Date.now(); } }, true); });
['mouseup', 'touchend', 'pointerup'].forEach(function(ev) {
document.addEventListener(ev, function() { kdrag = false; kuser = Date.now(); }, true); });
$(document).on('change', '#kshow', function() { if (!kself) kuser = Date.now(); });
$(document).on('click', '#play', function() { kplay(!ktimer); });
$(document).on('click', '#step', function() { kplay(false); kset(kcur() + 1); });
$(document).on('click', '#back', function() { kplay(false); kset(kcur() - 1); });
$(document).on('click', '#first', function() { kplay(false); kset(0); });
$(document).on('click', '#toend', function() { kplay(false); kset(kslider().options.max); });
Shiny.addCustomMessageHandler('krun', function(m) {
kplay(false);
// a new run is shown at its last iteration, or at the start if the box is unticked
var s = kslider(); if (s) { s.update({max: m.max, from: m.last ? m.max : 0}); $('#kshow').trigger('change'); }
if (m.play) kplay(true); });
"))),
## small text for the row of weight buttons; labels kept to one line
tags$head(tags$style(HTML("
.wbar .btn { font-size: 12px; padding: 3px 10px; }
.wbar label { font-size: 12px; margin-bottom: 1px; }
.wbar .form-group { margin-bottom: 0; }
.wbar .selectize-input, .wbar select { font-size: 12px; min-height: 26px;
padding: 3px 8px; }
.steprule { display: flex; gap: 14px; }
.steprule > div { flex: 1; min-width: 0; }
.steprule > div.lrbox { flex: 2; }
.infotab { border-collapse: collapse; font-size: 13px; margin: 6px 0; }
.infotab th, .infotab td { padding: 3px 8px; text-align: right; white-space: nowrap;
border-bottom: 1px solid #ddd; }
.infotab th { border-bottom: 2px solid #999; }
.infotab th:first-child, .infotab td:first-child { text-align: left; }
.control-label { display: block; max-width: 100%; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis; }"))),
## a label cut off by its box shows in full on hover
tags$head(tags$script(HTML("
$(document).on('mouseenter', '.control-label', function() {
if (this.scrollWidth > this.clientWidth) this.title = this.textContent;
else this.removeAttribute('title'); });"))),
## ---- control panel, at the top -------------------------------------------
wellPanel(
## the data
fluidRow(
row_label("Setup"),
column(2, sliderInput("n", "Sample size n", min = 50, max = 2000,
value = 150, step = 50, width = "100%")),
column(1, selectInput("xscale", "Scale of x", choices = c("0.1" = 0.1, "1" = 1, "10" = 10, "100" = 100),
selected = 1, width = "100%")),
column(1, numericInput("J", "Hidden units", value = 4, min = 4, max = 2000, step = 1,
width = "100%")),
column(2, selectInput("lam", "L1 penalty \u03bb on the weights",
choices = c("0 (none)" = 0, "1e-5" = 1e-5, "1e-4" = 1e-4,
"1e-3" = 1e-3, "0.01" = 0.01, "0.1" = 0.1),
selected = 0, width = "100%")),
column(2, div(style = "padding-top: 25px;",
actionButton("newdata", "Regenerate data",
class = "btn-warning", style = "width:100%;")))
),
hr(style = "margin: 4px 0 8px;"),
## two optimizers, each with its own settings: A (green) and B (blue)
opt_row("A", "adam", "#2E8B57"),
opt_row("B", "gd", "#1F5FBF", none = TRUE),
hr(style = "margin: 4px 0 8px;"),
## how long to run them, the colour scale, the play buttons, the iteration shown
fluidRow(
row_label("Run"),
column(1, selectInput("maxit", "Max iterations",
choices = c(10, 20, 50, 100, 200, 500, 1000, 2000, 5000),
selected = 100, width = "100%")),
column(1, selectInput("ctr", "Contrast",
choices = c(1, 2, 4, 8, 16, 32), selected = 8,
width = "100%")),
column(1, selectInput("gtol", "Stop: ||g|| <",
choices = c("0.1" = 0.1, "0.01" = 0.01, "1e-3" = 0.001,
"1e-4" = 1e-4, "1e-6" = 1e-6, "1e-8" = 1e-8,
"never" = 0),
selected = 1e-6, width = "100%")),
column(1, selectInput("stall", "Stop if flat for",
choices = c("never" = Inf, "100 its" = 100, "50 its" = 50, "20 its" = 20),
selected = Inf, width = "100%")),
column(3, div(style = "display: flex; gap: 4px; padding-top: 22px;",
ctrl_btn("first", "backward-fast", "Back to the start"),
ctrl_btn("back", "backward-step", "One iteration back"),
ctrl_btn("play", "play", "Play / pause",
class = "btn-primary"),
ctrl_btn("step", "forward-step", "One iteration forward"),
ctrl_btn("toend", "forward-fast", "To the end")),
checkboxInput("autoplay", "Autoplay on change", FALSE),
checkboxInput("autolast", "Auto Display of Last Iteration", TRUE)),
column(3, sliderInput("kshow", "Iteration shown", min = 0, max = 100,
value = 0, step = 1, width = "100%"))
)
), fluidRow(
## ---- left: the fitted mean, and below it the network of weights -----
## (the two plots together are about as tall as the loss and rate plots)
column(6,
checkboxInput("showparts", "Show the units on the log scale", FALSE),
plotOutput("fit", height = "280px"),
conditionalPanel("input.showparts", plotOutput("eta", height = "250px")),
div(class = "wbar",
style = "display: flex; gap: 6px; align-items: flex-end; margin: 8px 0 4px 0;",
actionButton("settrue", "True Value", class = "btn-success"),
actionButton("newstart", "Random"),
actionButton("setzero", "Zero"),
div(style = "width: 110px; margin-left: 6px;",
selectInput("astep", "Adjust Size",
choices = c(0.05, 0.1, 0.25, 0.5, 1),
selected = 0.25, width = "100%")),
div(style = "width: 90px; margin-left: 6px;",
selectInput("netsel", "Network of", choices = c("A", "B"), width = "100%")),
div(style = "margin-left: 10px; white-space: nowrap;",
checkboxInput("runopt", "Run Optimizations", TRUE))),
plotOutput("netv", height = "350px", click = "netv_click")),
## ---- right: how the optimizer is doing: the loss and the rate ---------
column(6,
plotOutput("conv", height = "340px"),
radioButtons("lscale", NULL, inline = TRUE,
choices = c("log10 loss" = "log", "log10 (loss - smallest reached)" = "exc",
"loss" = "lin")),
plotOutput("rate", height = "250px"),
htmlOutput("info"))
)
)
## ----------------------------------------------------------------- server
server <- function(input, output, session) {
dseed <- reactiveVal(1); rseed <- reactiveVal(1)
theta0 <- reactiveVal(rand_start(1, 4)) # the starting weights
## the number of hidden units, read once typing has paused
Jr <- debounce(reactive({
v <- suppressWarnings(as.integer(input$J))
if (length(v) != 1 || is.na(v)) 4L else max(4L, min(2000L, v))
}), 800)
## a new number of units starts again from random weights of that size
observeEvent(Jr(), {
th <- rand_start(rseed(), Jr()); J <- Jr(); th[1:J] <- th[1:J] / xsc(); theta0(th)
}, ignoreInit = TRUE)
lam <- reactive(if (is.null(input$lam)) 0 else as.numeric(input$lam))
observeEvent(input$newdata, dseed(dseed() + 1))
## a sensible starting learning rate for each fixed-rate method
## a sensible learning rate for the method and the scale of x: the curvature in a slope
## weight grows like s^2, and Adam's step is measured in the weight, which shrinks like 1 / s.
## The output adds up J units, so its curvature in the output weights grows like J, and an
## Adam step of about lr in every weight moves the output by up to about J lr: all three
## fixed rates are also multiplied by 4 / J
for (s in c("A", "B")) local({
s <- s
observeEvent(list(input[[paste0("alg", s)]], input$xscale, Jr()), {
a <- input[[paste0("alg", s)]]
base <- c(gdfix = 0.1, sgdls = 0.1, sgdls2 = 0.1, mom = 0.03, adam = 0.1)[a]
if (!is.null(a) && !is.na(base)) {
v <- unname(base) / xsc()^(if (a == "adam") 1 else 2) *
(if (a %in% c("sgdls", "sgdls2")) 1 else 4 / Jr())
r <- LRGRID[which.min(abs(log(LRGRID) - log(v)))]
updateSelectInput(session, paste0("lr", s), selected = as.character(r))
}
})
})
observeEvent(input$setzero, theta0(rep(0, 3 * Jr() + 1)))
observeEvent(input$newstart, {
rseed(rseed() + 1); J <- Jr()
th <- rand_start(rseed(), J); th[1:J] <- th[1:J] / xsc() # random weights for x / s
theta0(th)
})
## an arrow click moves the nearest arrow's weight by one step
observeEvent(input$netv_click, {
cl <- input$netv_click
d <- ((cl$x - ARROWS$ax) / 0.05)^2 + ((cl$y - ARROWS$ay) / 0.04)^2
i <- which.min(d)
if (d[i] < 2) {
th <- theta0(); j <- show_idx(nunits(th))[ARROWS$idx[i]] # the slot's place in theta
th[j] <- th[j] + ARROWS$dir[i] * as.numeric(input$astep)
theta0(th)
}
})
## the predictor on a different scale: x -> s x, with the slope weights of the generating
## network divided by s, so the true curve is the same function of x / s
xsc <- reactive(if (is.null(input$xscale)) 1 else as.numeric(input$xscale))
TT <- reactive({ th <- TRUE_THETA; th[1:4] <- th[1:4] / xsc(); th })
## the true weights, with units 5 to J switched off (output weight 0)
observeEvent(input$settrue, {
J <- Jr(); th <- embed_theta(TRUE_THETA, J); th[1:J] <- th[1:J] / xsc(); theta0(th)
})
## a new scale of x keeps the starting curve: the slope weights change with it
xprev <- reactiveVal(1)
observeEvent(input$xscale, {
th <- theta0(); J <- nunits(th)
th[1:J] <- th[1:J] * xprev() / xsc(); xprev(xsc()); theta0(th)
}, ignoreInit = TRUE)
DAT <- reactive({
D <- make_data(input$n, dseed())
D$x <- D$x * xsc()
D
})
## a test sample from the same process, the same for both optimizers
DTE <- reactive({
D <- make_data(1000, dseed() + 5000)
D$x <- D$x * xsc()
D
})
## the loss on the test sample at every iteration of a run
## (at most 100 iterations are evaluated, and the rest interpolated, to keep large
## networks quick)
tcurve <- function(R) {
Dt <- DTE()
ks <- unique(round(seq(1, R$n, length.out = min(R$n, 100))))
te <- apply(R$P[ks, , drop = FALSE], 1, function(th) nll(th, Dt$x, Dt$y))
if (length(ks) == R$n) te else approx(ks, te, xout = seq_len(R$n))$y
}
## one run for each optimizer, from the same start on the same data
## its settings are read once they have been still for 0.4 s: a new number of units also
## resets the learning rate, which reaches the server a moment later, and a large network
## should not be fitted twice
mkrun <- function(s) {
pars <- debounce(reactive({
a <- input[[paste0("alg", s)]]
if (is.null(a) || a == "none") return(NULL)
list(a = a, th0 = theta0(), D = DAT(),
maxit = if (isFALSE(input$runopt)) 0 else as.numeric(input$maxit),
tol = if (is.null(input$gtol)) 1e-6 else as.numeric(input$gtol),
patience = if (is.null(input$stall)) Inf else as.numeric(input$stall),
lr = input[[paste0("lr", s)]], mom = input[[paste0("mom", s)]],
m = input[[paste0("batch", s)]], mem = input[[paste0("mem", s)]], lam = lam())
}), 400)
reactive({
S <- pars(); if (is.null(S)) return(NULL); a <- S$a
fixed <- a %in% c("gdfix", "sgdls", "sgdls2", "mom", "adam")
req(!fixed || !is.null(S$lr))
r <- run_alg(a, S$th0, S$D$x, S$D$y, S$maxit, tol = S$tol, patience = S$patience,
lr = if (fixed) as.numeric(S$lr) else NA,
mom = if (a == "mom") S$mom else NA,
m = if (a %in% MINIBATCH) as.numeric(S$m) else NA,
lmem = if (a == "lbfgs" && !is.null(S$mem)) as.numeric(S$mem) else 10,
lam = S$lam)
if (S$maxit == 0) r$note <- "optimization is off: Run Optimizations is unticked"
r
})
}
runA <- mkrun("A"); runB <- mkrun("B")
## the test loss along each run, computed once per run
testA <- reactive(tcurve(runA()))
testB <- reactive(if (is.null(runB())) NULL else tcurve(runB()))
## the network panels show the run chosen in "Network of"
netsel <- reactive(if (identical(input$netsel, "B") && !is.null(runB())) "B" else "A")
run <- reactive(if (netsel() == "B") runB() else runA())
## the browser owns the iteration (slider, play timer, buttons); a new run is shown at its end
observeEvent(list(runA(), runB()), {
nmax <- max(runA()$n, if (is.null(runB())) 0L else runB()$n)
session$sendCustomMessage("krun", list(max = nmax - 1L,
last = !isFALSE(input$autolast),
play = isTRUE(input$autoplay) && nmax > 1))
})
kraw <- reactive(as.integer(if (is.null(input$kshow)) 0L else input$kshow))
kpos <- reactive(min(kraw(), run()$n - 1L))
cur <- reactive({
R <- run(); k <- min(kpos(), R$n - 1L) + 1L
list(R = R, k = k, th = R$P[k, ])
})
## the colour scale of a run, from (a sample of) all its weights along the path
vmaxr <- reactive({
a <- abs(run()$P); if (length(a) > 1e5) a <- a[sample.int(length(a), 1e5)]
max(3, quantile(a, 0.95))
})
output$netv <- renderPlot({
C <- cur(); R <- C$R
vmax <- vmaxr()
par(mar = c(1, 1, 3, 1))
draw_net(C$th, vmax, as.numeric(input$ctr),
sprintf("%s: weights, iteration %d (loss %.4f)", netsel(), C$k - 1L, R$L[C$k]))
})
## one clearly different colour per hidden unit
PCOL <- c("#F28E00", "#1F5FBF", "black", "#00B5CC")
output$fit <- renderPlot({
RA <- runA(); RB <- runB(); R <- RA; D <- DAT(); kk <- kraw()
xg <- seq(-3, 3, length.out = 300) * xsc()
par(mar = c(4, 4.2, 2.5, 1))
plot(D$x, D$yj, pch = 19, cex = 0.7,
col = adjustcolor("#E8820C", 0.5), ylim = c(0, max(D$y) + 1),
xlab = "x", ylab = expression(lambda(x) ~ "and counts y"),
main = "fitted mean and the generated data")
lines(xg, lambda_fun(TT(), xg), col = "red", lty = 2, lwd = 2)
lines(xg, lambda_fun(R$P[1, ], xg), col = "grey60", lwd = 2)
lines(xg, lambda_fun(RA$P[min(kk, RA$n - 1L) + 1L, ], xg), col = "#2E8B57", lwd = 3)
if (!is.null(RB))
lines(xg, lambda_fun(RB$P[min(kk, RB$n - 1L) + 1L, ], xg), col = "#1F5FBF", lwd = 2.5)
leg <- data.frame(
lab = c("true mean", "starting weights", paste("A:", alg_name(input$algA)), "counts"),
lwd = c(2, 2, 3, NA), lty = c(2, 1, 1, NA), pch = c(NA, NA, NA, 19),
col = c("red", "grey60", "#2E8B57", adjustcolor("#E8820C", 0.7)),
stringsAsFactors = FALSE)
if (!is.null(RB))
leg <- rbind(leg, data.frame(lab = paste("B:", alg_name(input$algB)), lwd = 2.5, lty = 1,
pch = NA, col = "#1F5FBF", stringsAsFactors = FALSE))
legend("topright", bty = "n", cex = 0.78, lwd = leg$lwd, lty = leg$lty,
pch = leg$pch, col = leg$col, legend = leg$lab)
})
## the same fit on the log scale, where the units simply add up
output$eta <- renderPlot({
C <- cur(); xg <- seq(-3, 3, length.out = 300) * xsc()
VH <- unit_terms(C$th, xg); J <- ncol(VH)
## the units not drawn in the network are added up into one curve
if (J > JS) VH <- cbind(VH[, 1:JS], rowSums(VH[, -(1:JS), drop = FALSE]))
eta <- C$th[length(C$th)] + rowSums(VH)
eta_true <- log(lambda_fun(TT(), xg))
par(mar = c(4, 4.2, 2.5, 1))
matplot(xg, VH, type = "l", lty = 3, lwd = 2.5, col = c(PCOL, "grey50"),
ylim = pmax(-8, pmin(8, range(VH, eta, eta_true))),
xlab = "x", ylab = expression(log ~ lambda(x)),
main = "log scale: the scaled units v_j h_j add up to the fit")
abline(h = 0, lty = 3, col = "grey70")
lines(xg, eta_true, col = "red", lty = 2, lwd = 2)
lines(xg, eta, col = "#2E8B57", lwd = 3)
ul <- c(paste0("v", 1:JS, " h", 1:JS), if (J > JS) paste0("units ", JS + 1, "-", J, ", added"))
legend("topright", bty = "n", cex = 0.78, ncol = 2,
lwd = c(rep(2.5, ncol(VH)), 3, 2), lty = c(rep(3, ncol(VH)), 1, 2),
col = c(PCOL, if (J > JS) "grey50", "#2E8B57", "red"),
legend = c(ul, "sum + v0 (fit)", "true"))
})
output$conv <- renderPlot({
R <- runA(); RF <- runB(); kk <- kraw()
TA <- testA(); TB <- testB()
## the loss on the scale chosen below: as is, its log10, or the log10 of its excess
## over the smallest value any curve reaches (so differences near the floor show)
sc <- if (is.null(input$lscale)) "log" else input$lscale
best <- min(c(R$L, RF$L, TA, TB), na.rm = TRUE)
ls_fun <- function(v) switch(sc, lin = v, log = if (best > 0) log10(v) else log10(pmax(v - best, 1e-12)),
exc = log10(pmax(v - best, 1e-12)))
ls_lab <- switch(sc, lin = "loss",
log = if (best > 0) expression(log[10] ~ "loss") else expression(log[10] ~ "(loss - smallest reached)"),
exc = expression(log[10] ~ "(loss - smallest reached)"))
xl <- c(0, max(R$n, if (is.null(RF)) 0 else RF$n) - 1)
par(mar = c(4, 4.2, 2.5, 1))
plot(0:(R$n - 1), ls_fun(R$L), type = "n", xlab = "iteration", ylab = ls_lab,
xlim = xl, ylim = range(ls_fun(c(R$L, RF$L, TA, TB)), finite = TRUE),
main = paste0("average negative log-likelihood", if (lam() > 0) " (without the penalty)",
": training (solid) and test (dashed)"))
lines(0:(R$n - 1), ls_fun(R$L), col = "#2E8B57", lwd = 2)
lines(0:(R$n - 1), ls_fun(TA), col = "#2E8B57", lwd = 2, lty = 2)
ka <- min(kk, R$n - 1L)
points(ka, ls_fun(R$L[ka + 1L]), pch = 19, col = "#2E8B57", cex = 1.5)
points(ka, ls_fun(TA[ka + 1L]), pch = 1, col = "#2E8B57", cex = 1.5, lwd = 2)
if (!is.null(RF)) {
lines(0:(RF$n - 1), ls_fun(RF$L), col = "#1F5FBF", lwd = 2)
lines(0:(RF$n - 1), ls_fun(TB), col = "#1F5FBF", lwd = 2, lty = 2)
kb <- min(kk, RF$n - 1L)
points(kb, ls_fun(RF$L[kb + 1L]), pch = 19, col = "#1F5FBF", cex = 1.5)
points(kb, ls_fun(TB[kb + 1L]), pch = 1, col = "#1F5FBF", cex = 1.5, lwd = 2)
}
legend("topright", bty = "n", cex = 0.85, lwd = 2, lty = c(1, 2, if (!is.null(RF)) c(1, 2)),
col = c("#2E8B57", "#2E8B57", if (!is.null(RF)) c("#1F5FBF", "#1F5FBF")),
legend = c(paste("A:", alg_name(input$algA), "train"), "A: test",
if (!is.null(RF)) c(paste("B:", alg_name(input$algB), "train"), "B: test")))
})
## the learning rate (or the mean accepted step) of each run in each iteration
output$rate <- renderPlot({
kk <- kraw()
runs <- Filter(Negate(is.null), list(list(R = runA(), col = "#2E8B57", a = input$algA, s = "A"),
if (!is.null(runB())) list(R = runB(), col = "#1F5FBF", a = input$algB, s = "B")))
vals <- unlist(lapply(runs, function(u) u$R$A))
vals <- vals[is.finite(vals) & vals > 0]
par(mar = c(4, 4.2, 2.5, 1))
if (!length(vals)) { plot.new(); return(invisible()) }
xl <- c(0, max(sapply(runs, function(u) u$R$n)) - 1)
yl <- range(log10(vals)); if (diff(yl) < 0.5) yl <- mean(yl) + c(-0.5, 0.5)
plot(NA, xlim = xl, ylim = yl, xlab = "iteration", ylab = expression(log[10] ~ "rate"),
main = "learning rate (or step length) in each iteration")
for (u in runs) {
R <- u$R; it <- 0:(R$n - 1)
lines(it, log10(R$A), type = "s", col = u$col, lwd = 2)
k <- min(kk, R$n - 1L) + 1L
if (is.finite(R$A[k])) points(k - 1, log10(R$A[k]), pch = 19, col = u$col, cex = 1.4)
}
legend("topright", bty = "n", cex = 0.8,
col = sapply(runs, `[[`, "col"), lwd = 2,
legend = sapply(runs, function(u) paste0(u$s, ": ", alg_name(u$a))))
})
output$info <- renderUI({
D <- DAT(); kk <- kraw()
f5 <- function(v) formatC(v, digits = 5, format = "f")
## one row of the summary table per optimizer, with its run's note kept for below the table
row <- function(R, te, a, tag, col) {
k <- min(kk, R$n - 1L) + 1L; al <- R$A[k]
cells <- c(paste0("<b style='color:", col, "'>", tag, "</b>"), # the name goes below the table
paste0(if (a %in% MINIBATCH) "epoch " else "iteration ", k - 1L, " of ", R$n - 1L),
f5(R$L[k]),
if (lam() > 0) f5(R$F[k] - R$L[k]),
f5(te[k]),
paste0(f5(min(te)), " at ", which.min(te) - 1L),
formatC(R$GN[k], digits = 3, format = "g"),
if (is.finite(al)) paste0(formatC(al, digits = 3, format = "g"),
if (a %in% c("gdfix", "mom", "adam")) "" else " (step)")
else "–")
list(tr = paste0("<tr>", paste0("<td>", cells, "</td>", collapse = ""), "</tr>"),
note = paste0("<b style='color:", col, "'>", tag, ": ", alg_name(a), ".</b> <i>", R$note, "</i>"))
}
rows <- list(row(runA(), testA(), input$algA, "A", "#2E8B57"),
if (!is.null(runB())) row(runB(), testB(), input$algB, "B", "#1F5FBF"))
rows <- Filter(Negate(is.null), rows)
heads <- c("", "Iteration", "Loss", if (lam() > 0) "L1 penalty", "Test loss",
"Lowest test loss", "||gradient||", "Learning rate")
HTML(paste0(
"<b>p</b> = ", length(theta0()), " weights (", nunits(theta0()), " hidden units)",
"<div style='overflow-x: auto;'><table class='infotab'><tr>",
paste0("<th>", heads, "</th>", collapse = ""), "</tr>",
paste(sapply(rows, `[[`, "tr"), collapse = ""), "</table></div>",
paste(sapply(rows, `[[`, "note"), collapse = "<br>")))
})
}
shinyApp(ui, server)This app accompanies Optimization for Maximum Likelihood Estimation in the book.