net_picture <- function(cols, first_colour = v_blue, first_type = "solid", heads = NULL) {
nodes <- imap_dfr(cols, function(lab, j) tibble(col = j, x = 1.6 * (j - 1), lab = lab,
y = if (length(lab) == 1) 1.5 else seq(3, 0, length.out = length(lab))))
real <- filter(nodes, lab != "...")
edges <- map_dfr(seq_len(length(cols) - 1), function(j) {
a <- filter(real, col == j); b <- filter(real, col == j + 1)
expand_grid(i = seq_len(nrow(a)), k = seq_len(nrow(b))) |>
transmute(x = a$x[i], y = a$y[i], xend = b$x[k], yend = b$y[k], layer = j)
})
last <- length(cols)
ggplot() +
geom_segment(data = filter(edges, layer == 1), aes(x, y, xend = xend, yend = yend),
colour = first_colour, linetype = first_type, alpha = 0.7, linewidth = 0.6) +
geom_segment(data = filter(edges, layer > 1), aes(x, y, xend = xend, yend = yend),
colour = m_pink, alpha = 0.7, linewidth = 0.6) +
geom_point(data = filter(real, col == 1), aes(x, y), size = 10, colour = "grey35", fill = "white", shape = 21, stroke = 0.9) +
geom_point(data = filter(real, col > 1, col < last), aes(x, y), size = 11, colour = v_blue, fill = "#e8f0f7", shape = 21, stroke = 1) +
geom_point(data = filter(real, col == last), aes(x, y), size = 11, colour = m_pink, fill = "#fbe9f1", shape = 21, stroke = 1) +
geom_text(data = nodes, aes(x, y, label = lab), parse = TRUE, size = 2.9) +
{ if (!is.null(heads)) annotate("text", x = 1.6 * (seq_along(heads) - 1), y = 3.75, label = heads, size = 3.2, colour = "grey30") } +
coord_cartesian(xlim = c(-0.4, 1.6 * (last - 1) + 0.4), ylim = c(-0.5, 4), clip = "off") +
theme_void()
}
net_picture(list(c("x[1]", "x[2]", "...", "x[p]"), c("h[1]", "h[2]", "h[M]"), "f(x)"),
first_colour = "grey55", first_type = "dashed", heads = c("inputs", "M hidden units", "output"))