{"slug": "hierarchical-bayesian-neural-networks-when-structure-meets-flexibility", "title": "Hierarchical Bayesian Neural Networks: When Structure Meets Flexibility", "summary": "A new blog post compares four Bayesian modeling approaches — Bayesian hierarchical models (BHMs), Bayesian neural networks (BNNs), a hierarchical Bayesian neural network (HBNN), and an ensemble of BHM and BNN — across three simulated data-generating processes. The HBNN, implemented in Stan with non-centered group intercepts added to a tanh hidden layer, combines partial pooling over groups with a flexible neural network function class, but the post finds the BHM wins on grouped linear data and the BNN wins on complex nonlinear data with no real group structure. The HBNN places close second in both cases, with partial pooling driving unnecessary group intercepts toward zero when group labels are noise.", "body_md": "In a [previous post](https://statwonk.com/bayesian-hierarchical-vs-neural-network-ensemble.html),\n                    we showed that Bayesian hierarchical models (BHMs) win when group structure is describable,\n                    Bayesian neural networks (BNNs) win when the signal is complex, and their ensemble hedges\n                    across both scenarios.\n\nBut what about the case where your data has *both* — known group structure **and**\n                    complex nonlinear signal? Neither the BHM nor the BNN is ideal:\n\n- The **BHM** captures group heterogeneity but can't represent the nonlinear\n                        signal\n- The **BNN** learns the nonlinear function but ignores group structure\n\nEnter the **hierarchical Bayesian neural network (HBNN)** — a model that combines\n                    partial pooling over groups with a flexible neural network function class. This post adds the HBNN\n                    to our comparison and shows when each of the four approaches excels.\n\n## The Four Models\n\n| Model | Group Structure | Nonlinear Flexibility | \n|---|---|---|\n| **BHM** | ✅ Group-varying intercept + slope | ❌ Linear in x | \n| **BNN** | ❌ No group information | ✅ tanh hidden layer | \n| **HBNN** | ✅ Group-varying intercepts | ✅ tanh hidden layer | \n| **Ensemble** | Partial (via BHM component) | Partial (via BNN component) | \n\n## The Hierarchical BNN in Stan\n\nThe HBNN adds partially-pooled group intercepts to the neural network. The non-centered parameterization lets Stan explore the posterior efficiently:\n\n```\nparameters {\n  real alpha_0;               // population intercept\n  real sigma_alpha;  // group intercept spread\n  vector[J] alpha_raw;        // non-centered group deviations\n\n  vector[H] w1;     // input→hidden weights\n  vector[H] b1;     // hidden biases\n  vector[H] w2;     // hidden→output weights\n  real b2;           // output bias\n  real sigma;\n}\ntransformed parameters {\n  vector[J] alpha = alpha_0 + sigma_alpha * alpha_raw;\n}\nmodel {\n  ...\n  for (n in 1:N) {\n    vector[H] h = tanh(w1 * x[n] + b1);\n    mu[n] = alpha[g[n]] + b2 + dot_product(w2, h);\n  }\n  y ~ normal(mu, sigma);\n}\n```\n\nLine by line, this is a BNN with one addition: `alpha[g[n]]` — a group-specific\n                    intercept drawn from a learned population distribution. The neural network learns the shared\n                    nonlinear signal `f(x)`, and the hierarchical intercepts capture group-level shifts.\n                    Each component does what it's best at.\n\n## Three Data-Generating Processes\n\n### DGP 1: Grouped Linear — BHM Excels\n\n```\n# Group-specific intercepts and slopes, linear signal\nalpha_true <- rnorm(J, 0, 1.5)\nbeta_true  <- rnorm(J, 2, 0.8)\nd1 <- tibble(g = rep(1:J, each = n_per), x = runif(N, -2, 2)) %>%\n  mutate(mu = alpha_true[g] + beta_true[g] * x,\n         y  = rnorm(n(), mu, 0.5))\n```\n\nThe signal is linear and the heterogeneity is in group-specific intercepts and slopes. The BHM is\n                    **perfectly specified** — its functional form matches the DGP exactly. The HBNN's\n                    neural network component adds unnecessary flexibility here, making it a close second but slightly\n                    less efficient due to the additional parameters.\n\n**Winner: BHM.** When the functional form is simple enough to specify, the hierarchical model's parsimony is an advantage.\n\n### DGP 2: Complex Nonlinear, No Groups — BNN Excels\n\n```\n# Nonlinear signal, group labels are arbitrary\nd2 <- tibble(g = rep(1:J, length.out = N), x = runif(N, -3, 3)) %>%\n  mutate(mu = 2 * sin(1.5 * x) + 0.5 * cos(3 * x),\n         y  = rnorm(n(), mu, 0.4))\n```\n\nNo group-level heterogeneity — the group labels are noise. Both the BHM and the HBNN waste capacity estimating group intercepts that don't exist, but the BNN focuses entirely on learning the nonlinear signal. The HBNN is close because partial pooling drives the unnecessary group intercepts toward zero, but the BNN's simpler parameterization gives it an edge.\n\n**Winner: BNN.** When there's no group structure, the simplest flexible model wins.\n\n### DGP 3: Grouped + Complex Nonlinear — HBNN Excels\n\n```\n# Group offsets PLUS nonlinear signal\nalpha_true3 <- rnorm(J, 0, 1.5)\nd3 <- tibble(g = rep(1:J, each = n_per), x = runif(N, -3, 3)) %>%\n  mutate(mu = alpha_true3[g] + 2 * sin(1.5 * x) + 0.5 * cos(3 * x),\n         y  = rnorm(n(), mu, 0.4))\n```\n\nNow the data has **both** group-specific offsets and a complex nonlinear signal.\n                    This is the scenario the HBNN was built for:\n\n- The **BHM** handles the group offsets but can't capture the nonlinear signal\n- The **BNN** learns the nonlinear signal but conflates it with group\n                        variation — effectively trying to learn 10 different shifted copies of the same curve\n                        without knowing they're shifted\n- The **HBNN** separates concerns: the neural network learns the shared curve,\n                        and the hierarchical intercepts handle the per-group shifts\n\n**Winner: HBNN.** When the data has both describable structure and complex signal, the hierarchical neural network combines both advantages and achieves the lowest prediction error.\n\n## Summary: When Does Each Model Excel?\n\n| Scenario | Best Model | Why | \n|---|---|---|\n| Simple structure, known form | **BHM** | Parsimony wins when the model matches the DGP | \n| Complex signal, no structure | **BNN** | Flexible function class without wasted capacity | \n| Complex signal + group structure | **HBNN** | Separates structural and functional components | \n| Unknown or mixed regime | **Ensemble** | Insurance against misspecification | \n\n**↓ Lower CRPS = lower out-of-sample prediction error (winner)**\n\n```\n# CRPS results (lower = better out-of-sample prediction):\n#\n# DGP                              BHM    BNN    HBNN   Ensemble\n# Grouped linear                   0.31★  1.07   0.84   0.49\n# Complex nonlinear (no groups)    0.93   0.22★  0.22★  0.41\n# Grouped + complex nonlinear      0.87   0.84   0.26★  0.73\n#\n# ★ = lowest CRPS (best out-of-sample predictions)\n```\n\n## The Takeaway\n\n**The practitioner's job is to match model architecture to data structure:**\n\n- **BHM** — use when the functional form is known and group structure\n                            dominates. Maximum efficiency, minimum waste.\n- **BNN** — use when the signal is complex and there's no exploitable group\n                            structure. Let the network learn what you can't specify.\n- **HBNN** — use when you have both: known groups and unknown functional\n                            forms. Encode what you know, learn what you don't.\n- **Ensemble** — use when you're uncertain about the regime. Pay a small\n                            premium for robustness.\n\nThe HBNN isn't always the best model — it's the best model\n                        *when the data has the structure it's designed for*. That's the No Free Lunch theorem\n                        in action: every model has a niche, and the art is matching the model to the problem.\n\nIn domains like **portfolio optimization**, **clinical trials**, and\n                    **marketing mix modeling**, the data often has exactly this structure: known grouping\n                    variables (sectors, treatment arms, channels) with complex nonlinear effects. The HBNN\n                    architecture — encoding the structure you know and learning the rest — represents a principled\n                    middle ground between pure specification and pure flexibility.\n\n## Full Reprex\n\nThe complete R script is available at\n                    [hbnn_comparison_reprex.R](https://gist.github.com/statwonk/ead845b7811dd5347b80d0fb68c7757c).\n                    It requires `cmdstanr`, `scoringRules`, and tidyverse. Runtime is\n                    approximately 4–5 minutes.", "url": "https://wpnews.pro/news/hierarchical-bayesian-neural-networks-when-structure-meets-flexibility", "canonical_source": "https://statwonk.com/hierarchical-bayesian-neural-network.html", "published_at": "2026-11-23 02:10:39+00:00", "updated_at": "2026-11-23 02:44:27.261597+00:00", "lang": "en", "topics": ["machine-learning", "neural-networks", "ai-research"], "entities": ["Stan", "Bayesian hierarchical model", "Bayesian neural network", "hierarchical Bayesian neural network"], "also_reported_by": [], "takeaway": "Adding partially-pooled group intercepts (alpha[g[n]] = alpha_0 + sigma_alpha * alpha_raw) to a tanh BNN in Stan handles data with both group structure and nonlinear signal, but a plain BHM stays more efficient when the functional form is linear and a plain BNN wins when group labels are noise.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/hierarchical-bayesian-neural-networks-when-structure-meets-flexibility", "markdown": "https://wpnews.pro/news/hierarchical-bayesian-neural-networks-when-structure-meets-flexibility.md", "text": "https://wpnews.pro/news/hierarchical-bayesian-neural-networks-when-structure-meets-flexibility.txt", "jsonld": "https://wpnews.pro/news/hierarchical-bayesian-neural-networks-when-structure-meets-flexibility.jsonld"}}