Neural and pretrained forecasters: N-BEATS, N-HiTS and Chronos
Forecast the whole horizon at once with N-BEATS and N-HiTS, read their parts, try a pretrained Chronos model without training, and judge all three on the same backtest as the baselines.
What runs in CodeSplash
- N-BEATS neural forecast Verified in Python and R
- N-HiTS neural forecast Verified in Python and R
- Chronos zero-shot forecast Checked in one engine
You will be able to
- Explain how N-BEATS blocks build a forecast from backcasts and parts
- Say what N-HiTS's pooling and knots change, and when that helps
- Use a pretrained forecaster without training, and check its intervals in a backtest
The whole horizon at once
ReadThe recurrent network in the previous lesson predicted one step and fed it back. N-BEATSN-BEATSA deep network of fully connected blocks that forecasts the whole horizon at once, each block adding its share of the forecast. works differently: it reads a lookback windowLookback windowHow many past values a neural forecaster reads to make one forecast; it is cut from the series again at every training step. and outputs every step of the horizon in one pass.
The network is a chain of blocks. Each block explains part of the window, its backcastBackcastThe part of the past window a block reconstructs; the next block only sees what is left, so blocks explain different things., and adds its own share to the forecast. The next block only sees what is left. This doubly residual stackingDoubly residual stackingEach block removes its backcast from the input and adds its forecast to the total, so the forecast is a sum of parts. makes the forecast a sum of parts.
Trend and season you can look at
PredictPredict first
The interpretable N-BEATS has two stacks. What does each stack's part of the forecast describe?
Reveal
A polynomial trend and a Fourier seasonality. Each stack's output is a basis expansionBasis expansionWriting a curve as a weighted sum of fixed shapes, such as powers of time or sine and cosine waves, so a few weights describe it.: a weighted sum of fixed shapes, so its part can only be a smooth trend or a repeating season.
Fit N-BEATS
In the appN-BEATS-I (trend + seasonality): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 17.3 over 1 origin.
- MAE
- 17.346
- RMSE
- 20.715
- MAPE
- 0.0366
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | month | passengers |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | −662,688,000,000 | 112 |
| — | — | actual | — | — | −660,009,600,000 | 118 |
| — | — | actual | — | — | −657,590,400,000 | 132 |
| — | — | actual | — | — | −654,912,000,000 | 129 |
| — | — | actual | — | — | −652,320,000,000 | 121 |
| — | — | actual | — | — | −649,641,600,000 | 135 |
| — | — | actual | — | — | −647,049,600,000 | 148 |
| — | — | actual | — | — | −644,371,200,000 | 148 |
| — | — | actual | — | — | −641,692,800,000 | 136 |
| — | — | actual | — | — | −639,100,800,000 | 119 |
| — | — | actual | — | — | −636,422,400,000 | 104 |
| — | — | actual | — | — | −633,830,400,000 | 118 |
| — | — | actual | — | — | −631,152,000,000 | 115 |
| — | — | actual | — | — | −628,473,600,000 | 126 |
| — | — | actual | — | — | −626,054,400,000 | 141 |
| — | — | actual | — | — | −623,376,000,000 | 135 |
| — | — | actual | — | — | −620,784,000,000 | 125 |
| — | — | actual | — | — | −618,105,600,000 | 149 |
| — | — | actual | — | — | −615,513,600,000 | 170 |
| — | — | actual | — | — | −612,835,200,000 | 170 |
| — | — | actual | — | — | −610,156,800,000 | 158 |
| — | — | actual | — | — | −607,564,800,000 | 133 |
| — | — | actual | — | — | −604,886,400,000 | 114 |
| — | — | actual | — | — | −602,294,400,000 | 140 |
| — | — | actual | — | — | −599,616,000,000 | 145 |
| — | — | actual | — | — | −596,937,600,000 | 150 |
| — | — | actual | — | — | −594,518,400,000 | 178 |
| — | — | actual | — | — | −591,840,000,000 | 163 |
| — | — | actual | — | — | −589,248,000,000 | 172 |
| — | — | actual | — | — | −586,569,600,000 | 178 |
| — | — | actual | — | — | −583,977,600,000 | 199 |
| — | — | actual | — | — | −581,299,200,000 | 199 |
| — | — | actual | — | — | −578,620,800,000 | 184 |
| — | — | actual | — | — | −576,028,800,000 | 162 |
| — | — | actual | — | — | −573,350,400,000 | 146 |
| — | — | actual | — | — | −570,758,400,000 | 166 |
| — | — | actual | — | — | −568,080,000,000 | 171 |
| — | — | actual | — | — | −565,401,600,000 | 180 |
| — | — | actual | — | — | −562,896,000,000 | 193 |
| — | — | actual | — | — | −560,217,600,000 | 181 |
| — | — | actual | — | — | −557,625,600,000 | 183 |
| — | — | actual | — | — | −554,947,200,000 | 218 |
| — | — | actual | — | — | −552,355,200,000 | 230 |
| — | — | actual | — | — | −549,676,800,000 | 242 |
| — | — | actual | — | — | −546,998,400,000 | 209 |
| — | — | actual | — | — | −544,406,400,000 | 191 |
| — | — | actual | — | — | −541,728,000,000 | 172 |
| — | — | actual | — | — | −539,136,000,000 | 194 |
| — | — | actual | — | — | −536,457,600,000 | 196 |
| — | — | actual | — | — | −533,779,200,000 | 196 |
| — | — | actual | — | — | −531,360,000,000 | 236 |
| — | — | actual | — | — | −528,681,600,000 | 235 |
| — | — | actual | — | — | −526,089,600,000 | 229 |
| — | — | actual | — | — | −523,411,200,000 | 243 |
| — | — | actual | — | — | −520,819,200,000 | 264 |
| — | — | actual | — | — | −518,140,800,000 | 272 |
| — | — | actual | — | — | −515,462,400,000 | 237 |
| — | — | actual | — | — | −512,870,400,000 | 211 |
| — | — | actual | — | — | −510,192,000,000 | 180 |
| — | — | actual | — | — | −507,600,000,000 | 201 |
First 60 of 156 rows.
View data
| error | horizon | origin |
|---|---|---|
| 6.376 | 1 | 1959-12-01 |
| −3.259 | 2 | 1959-12-01 |
| −37.032 | 3 | 1959-12-01 |
| 18.305 | 4 | 1959-12-01 |
| 6.027 | 5 | 1959-12-01 |
| −9.312 | 6 | 1959-12-01 |
| −29.123 | 7 | 1959-12-01 |
| −23.112 | 8 | 1959-12-01 |
| −23.966 | 9 | 1959-12-01 |
| 0.8761 | 10 | 1959-12-01 |
| −21.999 | 11 | 1959-12-01 |
| −28.763 | 12 | 1959-12-01 |
View data
| ACF | bound | lag |
|---|---|---|
| −0.0584 | 0.1886 | 1 |
| 0.1179 | 0.1886 | 2 |
| 0.0194 | 0.1886 | 3 |
| −0.0549 | 0.1886 | 4 |
| 0.0143 | 0.1886 | 5 |
| 0.0421 | 0.1886 | 6 |
| −0.1642 | 0.1886 | 7 |
| −0.0146 | 0.1886 | 8 |
| −0.0836 | 0.1886 | 9 |
| −0.1003 | 0.1886 | 10 |
| 0.0194 | 0.1886 | 11 |
| 0.1076 | 0.1886 | 12 |
| −0.0483 | 0.1886 | 13 |
| 0.0960 | 0.1886 | 14 |
| 0.0755 | 0.1886 | 15 |
| −0.0988 | 0.1886 | 16 |
| 0.0554 | 0.1886 | 17 |
| −0.0488 | 0.1886 | 18 |
| −0.0099 | 0.1886 | 19 |
| −0.0385 | 0.1886 | 20 |
| 0.0210 | 0.1886 | 21 |
| −0.0564 | 0.1886 | 22 |
| −0.0054 | 0.1886 | 23 |
| −0.0005 | 0.1886 | 24 |
View data
| part | month | passengers |
|---|---|---|
| trend | −283,996,800,000 | 409.77 |
| trend | −281,318,400,000 | 410.19 |
| trend | −278,899,200,000 | 410.82 |
| trend | −276,220,800,000 | 411.66 |
| trend | −273,628,800,000 | 412.69 |
| trend | −270,950,400,000 | 413.94 |
| trend | −268,358,400,000 | 415.38 |
| trend | −265,680,000,000 | 417.03 |
| trend | −263,001,600,000 | 418.88 |
| trend | −260,409,600,000 | 420.94 |
| trend | −257,731,200,000 | 423.20 |
| trend | −255,139,200,000 | 425.67 |
| seasonality | −283,996,800,000 | 40.871 |
| seasonality | −281,318,400,000 | 8.626 |
| seasonality | −278,899,200,000 | 65.722 |
| seasonality | −276,220,800,000 | 70.684 |
| seasonality | −273,628,800,000 | 96.773 |
| seasonality | −270,950,400,000 | 152.85 |
| seasonality | −268,358,400,000 | 244.02 |
| seasonality | −265,680,000,000 | 243.04 |
| seasonality | −263,001,600,000 | 142.09 |
| seasonality | −260,409,600,000 | 69.912 |
| seasonality | −257,731,200,000 | 11.256 |
| seasonality | −255,139,200,000 | 55.623 |
Assumptions
- Enough windows to learn from — 97 training windows for 2560 weights. That is little data for a neural network: compare it with ETS and the seasonal naive forecast on the same backtest.
- Beats the seasonal naive forecast — Backtest MAE is 0.36 times the seasonal naive forecast's from the same origins.
- Residuals look uncorrelated — Ljung–Box at 21 lags: p = 0.882.
Backtest accuracy (1 origin, horizon 12)
| Metric | Value |
|---|---|
| MAE | 17.346 |
| RMSE | 20.715 |
| MAPE | 0.0366 |
| sMAPE | 0.0358 |
| MASE | 0.5696 |
| WAPE | 0.0364 |
| Coverage of the 80% interval | 0.4167 |
| Coverage of the 95% interval | 0.5000 |
Forecast by part (they add up to the forecast; the first part carries the last value)
| month | trend | seasonality |
|---|---|---|
| 1961-01-01 | 409.77 | 40.871 |
| 1961-02-01 | 410.19 | 8.626 |
| 1961-03-01 | 410.82 | 65.722 |
| 1961-04-01 | 411.66 | 70.684 |
| 1961-05-01 | 412.69 | 96.773 |
| 1961-06-01 | 413.94 | 152.85 |
| 1961-07-01 | 415.38 | 244.02 |
| 1961-08-01 | 417.03 | 243.04 |
| 1961-09-01 | 418.88 | 142.09 |
| 1961-10-01 | 420.94 | 69.912 |
| 1961-11-01 | 423.20 | 11.256 |
| 1961-12-01 | 425.67 | 55.623 |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1961-01-01 | 450.64 | 439.52 | 461.77 | 433.63 | 467.65 |
| 1961-02-01 | 418.82 | 408.93 | 428.71 | 403.70 | 433.95 |
| 1961-03-01 | 476.55 | 464.53 | 488.56 | 458.17 | 494.92 |
| 1961-04-01 | 482.34 | 468.96 | 495.73 | 461.87 | 502.81 |
| 1961-05-01 | 509.47 | 496.40 | 522.53 | 489.49 | 529.45 |
| 1961-06-01 | 566.78 | 553.80 | 579.76 | 546.93 | 586.63 |
| 1961-07-01 | 659.40 | 644.17 | 674.64 | 636.10 | 682.70 |
| 1961-08-01 | 660.07 | 645.24 | 674.90 | 637.39 | 682.75 |
| 1961-09-01 | 560.98 | 547.08 | 574.87 | 539.72 | 582.23 |
| 1961-10-01 | 490.86 | 474.99 | 506.72 | 466.60 | 515.11 |
| 1961-11-01 | 434.46 | 417.46 | 451.46 | 408.46 | 460.46 |
| 1961-12-01 | 481.29 | 463.74 | 498.84 | 454.46 | 508.13 |
The exact R script · R R version 4.5.1 (2025-06-13)
# N-BEATS neural forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.nbeats 1.2.0 · spec 8037dba215b0dcf0
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network is built by codesplashr's cs_nb_* twins.
# %% Data
TIME <- "month"
VALUE <- "passengers"
SERIES <- NULL
H <- 12
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 1
STEP <- NULL # NULL = the horizon
OFFSETS <- NULL # the host's BacktestPlan: distance of each origin from the end of the series; NULL = windows and step
TRAIN_WINDOW <- NULL # NULL = train on all values before each origin
TRAIN_START <- NULL # rows before this time are left out (for example, before a structural break)
SEED <- 42
XREG <- character(0)
PARAMS <- list(
architecture = "interpretable",
blocks = 2,
layers = 2,
width = 16,
degree = 2,
window = NULL,
loss = "mse",
epochs = 120,
learning_rate = 0.005,
batch_size = NULL,
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", col_select = unique(c(TIME, VALUE, SERIES, XREG))))
cs_check_finite_columns(df, c(TIME, VALUE, XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
warnings <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
x_all <- if (length(XREG)) do.call(cbind, lapply(XREG, function(c) suppressWarnings(as.numeric(df[[c]])))) else NULL
n_early <- 0L
if (!is.null(TRAIN_START)) {
cut <- cs_ml_fc_parse_time(TRAIN_START, TEMPORAL)
early <- !is.na(times_all) & times_all < cut
n_early <- sum(early)
if (n_early > 0) {
warnings <- c(warnings, sprintf("%d rows before %s were left out of training.", n_early, as.character(TRAIN_START)))
times_all[early] <- NA
}
}
keys_all <- if (!is.null(SERIES)) as.character(df[[SERIES]]) else rep(NA_character_, nrow(df))
dropped <- sum(is.na(times_all)) - n_early
if (dropped > 0) warnings <- c(warnings, sprintf("%d rows without a time were left out.", dropped))
series_keys <- if (!is.null(SERIES)) sort(unique(keys_all[!is.na(keys_all)]), method = "radix") else list(NULL)
if (!is.null(SERIES) && anyNA(keys_all)) warnings <- c(warnings, "Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the Python driver.
if (all(is.na(values_all))) cs_error("CS_E_ALL_MISSING", column = VALUE)
if (!any(!is.na(times_all) & !is.na(values_all))) cs_error("CS_E_NO_ROWS")
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.nbeats/interpretable_monthly/out-r")
extra_tables <- list() # model blocks may add result tables (assign with <<-)
extra_assumptions <- list() # … and assumption rows
current_series <- NULL
X_TRAIN <- NULL # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE <- NULL # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[[current_series, or "_"]] <<- list(resid = ..., fitdf = k, lags = L) from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG <- list()
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/forecast.nbeats/interpretable_monthly/out-r")
# N-BEATS (Oreshkin et al. 2020) on torch for R (float64, one thread): windows of past values, scaled around their last
# value, run through chained basis-expansion blocks that forecast every horizon step at once. Python's torch trains the
# same network from the same initial weights with the same Adam steps.
FINAL <- list()
LB3_PARTS <- PARAMS$architecture == "interpretable"
min_train <- function(m) H + 11L # a lookback of at least 2 and at least 10 training windows
prepare_series <- function(y, t, m, freq) NULL
fit_forecast <- function(y, t, h, m, levels, spec) {
res <- cs_nb_fit_forecast(
y, h, m, levels,
model = "nbeats",
architecture = PARAMS$architecture,
window = PARAMS$window,
blocks = as.integer(PARAMS$blocks),
layers = as.integer(PARAMS$layers),
width = as.integer(PARAMS$width),
degree = as.integer(PARAMS$degree),
loss = PARAMS$loss,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = PARAMS$batch_size,
seed = SEED
)
FINAL[[if (is.null(current_series)) "_" else current_series]] <<- list(res = res, t = as.numeric(t))
res
}
# %% Backtests and forecasts
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)
bt_rows <- list()
fc_rows <- list()
facts <- list()
labels <- list()
freq_label <- ""
freq_alias <- ""
seasons <- integer(0)
n_obs <- 0
n_origins <- 0
filled <- 0
residuals_first <- NULL
for (key in series_keys) {
current_series <- key # model blocks may read it (e.g. table titles)
sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
t_raw <- times_all[sel]; y_raw <- values_all[sel]
if (sum(!is.na(y_raw)) < 3) { # too few values to read the time step from
cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(1) + 1, n = sum(!is.na(y_raw)))
}
x_later <- NULL
if (length(XREG)) { # rows after the last observed value carry known future regressors
x_raw <- x_all[sel, , drop = FALSE]
last_y <- max(t_raw[!is.na(y_raw)])
later <- t_raw > last_y
x_later <- x_raw[later, , drop = FALSE][order(t_raw[later]), , drop = FALSE]
t_raw <- t_raw[!later]; y_raw <- y_raw[!later]; x_raw <- x_raw[!later, , drop = FALSE]
}
freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
t <- reg$t; y <- reg$y
x_grid <- if (length(XREG)) do.call(cbind, lapply(seq_len(ncol(x_raw)), function(j) cs_ml_fc_regularize(t_raw, x_raw[, j], freq)$y)) else NULL
filled <- filled + reg$filled
freq_label <- freq$label
freq_alias <- cs_ml_fc_alias(freq$unit)
m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
seasons <- c(seasons, m)
n <- length(y)
n_obs <- n_obs + n
if (n < min_train(m) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(m) + 1, n = n)
spec <- prepare_series(y, t, m, freq)
step <- if (!is.null(STEP)) as.integer(STEP) else H
if (!is.null(OFFSETS)) {
origins <- cs_ml_fc_plan_origins(n, H, as.integer(OFFSETS), min_train(m))
if (length(origins) < length(OFFSETS)) {
warnings <- c(warnings, sprintf("%d of %d backtest origins were skipped for %s: too few values before them.", length(OFFSETS) - length(origins), length(OFFSETS), if (is.null(key)) VALUE else key))
}
} else {
origins <- cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))
}
for (o in origins) {
start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
if (length(XREG)) {
X_TRAIN <- x_grid[start:o, , drop = FALSE]
X_FUTURE <- x_grid[(o + 1):(o + H), , drop = FALSE]
}
res <- tryCatch(fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec), error = function(e) e)
if (inherits(res, "error")) {
warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(t[o], TEMPORAL), conditionMessage(res)))
next
}
n_origins <- n_origins + 1
scale <- cs_ml_fc_mase_scale(y[1:o], m)
scale2 <- cs_ml_fc_rmsse_scale(y[1:o], m)
lag <- if (m > 1 && o > m) m else 1 # the seasonal naive forecast from this origin (MASE's lag rule)
for (k in seq_len(H)) {
row <- list(series = if (is.null(key)) NA_character_ else key, origin = cs_ml_fc_format_time(t[o], TEMPORAL),
time = cs_ml_fc_format_time(t[o + k], TEMPORAL), h = k, actual = y[o + k],
mean = res$mean[k], scale = scale, scale2 = scale2, last = y[o],
snaive = y[o - lag + (k - 1) %% lag + 1])
for (level in LEVELS) {
row[[paste0("lo_", lv(level))]] <- res$lower[[as.character(level)]][k]
row[[paste0("hi_", lv(level))]] <- res$upper[[as.character(level)]][k]
}
bt_rows[[length(bt_rows) + 1]] <- row
}
}
if (length(XREG)) {
X_TRAIN <- x_grid
X_FUTURE <- cs_ml_fc_future_regressors(x_grid, x_later, H)
if (nrow(x_later) < H) {
warnings <- c(warnings, sprintf("Future values of %s are known for %d of %d steps; the last known values are held for the rest.", paste(XREG, collapse = ", "), nrow(x_later), H))
}
}
final <- fit_forecast(y, t, H, m, LEVELS, spec)
labels[[length(labels) + 1]] <- final$label
for (name in names(final$facts)) facts[[if (is.null(SERIES)) name else sprintf("%s[%s]", name, key)]] <- final$facts[[name]]
fitted <- final$fitted
diag <- DIAG[[if (is.null(key)) "_" else key]]
resid <- diag$resid
if (is.null(residuals_first) && !is.null(resid)) {
residuals_first <- as.numeric(resid)
} else if (is.null(residuals_first) && !is.null(fitted)) {
ok <- !is.na(fitted)
residuals_first <- (y - fitted)[ok]
}
skey <- if (is.null(key)) NA_character_ else key
for (i in seq_len(n)) {
row <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "actual", mean = y[i])
if (!is.null(resid) && i > n - length(resid)) row$resid <- resid[i - (n - length(resid))] # the last length(resid) times
if (!is.null(diag$fitdf)) row$lb_fitdf <- as.numeric(diag$fitdf)
if (!is.null(diag$lags)) row$lb_lags <- as.numeric(diag$lags)
fc_rows[[length(fc_rows) + 1]] <- row
if (!is.null(fitted) && !is.na(fitted[i])) {
fc_rows[[length(fc_rows) + 1]] <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "fitted", mean = fitted[i])
}
}
future <- cs_ml_fc_future_times(t[n], freq, H)
for (k in seq_len(H)) {
row <- list(series = skey, time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k], kind = "forecast", mean = final$mean[k])
for (level in LEVELS) {
row[[paste0("lo_", lv(level))]] <- final$lower[[as.character(level)]][k]
row[[paste0("hi_", lv(level))]] <- final$upper[[as.character(level)]][k]
}
fc_rows[[length(fc_rows) + 1]] <- row
}
}
if (filled > 0) warnings <- c(warnings, sprintf("%d missing time steps or values were filled by linear interpolation.", filled))
as_frame <- function(rows) {
cols <- unique(unlist(lapply(rows, names)))
as.data.frame(stats::setNames(lapply(cols, function(cn) {
v <- lapply(rows, function(r) if (is.null(r[[cn]])) NA else r[[cn]])
unlist(v)
}), cols), stringsAsFactors = FALSE, check.names = FALSE)
}
# %% Accuracy
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
top <- if (length(LEVELS)) lv(max(LEVELS)) else NULL
wsum <- function(xs) sum(weights * xs) / sum(weights)
values <- list(
n_series = length(series_keys), n_obs = n_obs, horizon = H, season = seasons[1], n_origins = n_origins,
filled = filled, fc_check = wsum(forecasts$mean),
model_label = if (length(series_keys) == 1) labels[[1]] else sprintf("%d series, one model each", length(series_keys)),
freq_label = freq_label, frequency = freq_alias
)
if (!is.null(top)) {
values$fc_lo_check <- wsum(forecasts[[paste0("lo_", top)]])
values$fc_hi_check <- wsum(forecasts[[paste0("hi_", top)]])
}
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
values <- c(values, facts)
nanoparquet::write_parquet(fc_df, file.path(out, "forecast.parquet"))
artifacts <- list(list(key = "forecast", path = file.path(out, "forecast.parquet"), format = "parquet"))
if (nrow(bt)) {
nanoparquet::write_parquet(bt, file.path(out, "backtest.parquet"))
artifacts[[2]] <- list(key = "backtest", path = file.path(out, "backtest.parquet"), format = "parquet")
}
# %% Charts
charts <- list()
shown <- if (!is.null(SERIES)) utils::head(series_keys, 8) else NULL
fan <- fc_df[fc_df$kind != "fitted" & (if (!is.null(SERIES)) fc_df$series %in% shown else TRUE), , drop = FALSE]
roles <- list(
time = cs_col(TIME, fan$time, kind = if (TEMPORAL) "temporal" else "numeric"),
value = cs_col(VALUE, fan$mean, kind = "numeric"),
kind = cs_col("kind", fan$kind, kind = "categorical", levels = c("actual", "forecast"))
)
for (level in c(80, 95)) {
if (level %in% LEVELS) {
roles[[paste0("lo_", lv(level))]] <- cs_col(paste0("lo_", lv(level)), fan[[paste0("lo_", lv(level))]], kind = "numeric")
roles[[paste0("hi_", lv(level))]] <- cs_col(paste0("hi_", lv(level)), fan[[paste0("hi_", lv(level))]], kind = "numeric")
}
}
if (!is.null(SERIES)) roles$series <- cs_col(SERIES, fan$series, kind = "categorical", levels = shown)
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Forecast of %s", VALUE), roles)
if (nrow(bt)) {
charts[[length(charts) + 1]] <- cs_chart("backtest", "backtest-errors", "Backtest errors by horizon", list(
h = cs_col("horizon", bt$h, kind = "numeric"),
error = cs_col("error", bt$actual - bt$mean, kind = "numeric"),
origin = cs_col("origin", bt$origin, kind = "categorical")
))
}
if (length(residuals_first) > 4) {
lags <- min(max(2 * seasons[1], 10), length(residuals_first) - 1, 48)
r_acf <- cs_ml_fc_acf(residuals_first, lags)
bound <- 1.959963984540054 / sqrt(length(residuals_first))
charts[[length(charts) + 1]] <- cs_chart("acf", "acf-plot", "Residual autocorrelation", list(
lag = cs_col("lag", seq_len(lags), kind = "numeric"),
acf = cs_col("ACF", r_acf, kind = "numeric"),
bound = cs_col("bound", rep(bound, lags), kind = "numeric")
))
}
# %% Forecast parts
first_key <- if (is.null(SERIES)) "_" else series_keys[1]
res0 <- FINAL[[first_key]]$res
t0 <- FINAL[[first_key]]$t
freq0 <- cs_ml_fc_detect_frequency(t0, TEMPORAL)
future0 <- cs_ml_fc_future_times(t0[length(t0)], freq0, H)
times0 <- vapply(future0, cs_ml_fc_format_time, if (TEMPORAL) "" else 0, temporal = TEMPORAL)
names0 <- names(res0$components)
parts0 <- unlist(lapply(names0, function(nm) res0$components[[nm]]), use.names = FALSE)
wparts <- as.numeric(outer(seq_len(H), seq_along(names0), function(k, j) j * k))
values$parts_check <- sum(wparts * parts0) / sum(wparts)
if (!is.null(PARAMS$window) && res0$facts$window < PARAMS$window) {
warnings <- c(warnings, sprintf("The lookback was shortened to %d values so that at least 10 windows train.", as.integer(res0$facts$window)))
}
suffix0 <- if (!is.null(SERIES)) paste0(" — ", first_key) else ""
if (LB3_PARTS) {
charts[[length(charts) + 1]] <- cs_chart("parts", "forecast-components", paste0(sprintf("Forecast of %s by part", VALUE), suffix0), list(
time = cs_col(TIME, rep(times0, length(names0)), kind = if (TEMPORAL) "temporal" else "numeric"),
value = cs_col(VALUE, parts0, kind = "numeric"),
part = cs_col("part", rep(names0, each = H), kind = "categorical", levels = names0)
))
part_cols <- lapply(seq_along(names0), function(j) list(key = sprintf("p%d", j - 1L), label = names0[j], type = "number"))
extra_tables[[length(extra_tables) + 1]] <- list(
key = "parts",
title = paste0("Forecast by part (they add up to the forecast; the first part carries the last value)", suffix0),
columns = c(list(list(key = "time", label = TIME)), part_cols),
rows = lapply(seq_len(H), function(k) {
row <- list(time = times0[[k]])
for (j in seq_along(names0)) row[[sprintf("p%d", j - 1L)]] <- res0$components[[names0[j]]][k]
row
})
)
}
# %% Checks
nw0 <- as.integer(res0$facts$n_windows)
extra_assumptions[[length(extra_assumptions) + 1]] <- list(
key = "enough_windows", label = "Enough windows to learn from", status = if (nw0 >= 100) "pass" else "warn", statistic = nw0,
detail = paste0(sprintf("%d training windows for %d weights.", nw0, as.integer(res0$facts$n_params)),
if (nw0 < 100) " That is little data for a neural network: compare it with ETS and the seasonal naive forecast on the same backtest." else "")
)
rel0 <- cs_ml_fc_naive_relative_mae(bt) # not MASE < 1: MASE scales by the in-sample one-step naive error
if (is.finite(rel0)) {
values[["bt[rel_mae]"]] <- rel0
beats0 <- rel0 < 1
extra_assumptions[[length(extra_assumptions) + 1]] <- list(
key = "beats_naive", label = "Beats the seasonal naive forecast", status = if (beats0) "pass" else "warn", statistic = rel0,
detail = paste0(sprintf("Backtest MAE is %.2f times the seasonal naive forecast's from the same origins.", rel0), if (!beats0) " Repeating the last season forecast these origins at least as well." else "")
)
}
check0 <- cs_fcm_residual_check(residuals_first, seasons[1])
if (!is.null(check0)) {
values$lb_p <- check0$p
extra_assumptions[[length(extra_assumptions) + 1]] <- cs_fcm_residual_row(check0, "The network left autocorrelation in its one-step errors: try a longer lookback, or ARIMA.", if (!is.null(SERIES)) series_keys[1])
}
# %% Result
show <- intersect(c("mae", "rmse", "mape", "smape", "mase", "wape"), names(accuracy))
tables <- list()
if (length(accuracy)) {
rows <- lapply(show, function(k) list(metric = if (k == "smape") "sMAPE" else toupper(k), value = accuracy[[k]]))
for (level in LEVELS) {
ck <- paste0("coverage_", lv(level))
if (!is.null(accuracy[[ck]])) rows[[length(rows) + 1]] <- list(metric = sprintf("Coverage of the %s%% interval", lv(level)), value = accuracy[[ck]])
}
tables[[1]] <- list(key = "accuracy", title = sprintf("Backtest accuracy (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
columns = list(list(key = "metric", label = "Metric"), list(key = "value", label = "Value", type = "number")), rows = rows)
}
fc_cols <- c(if (!is.null(SERIES)) list(list(key = "series", label = "Series")),
list(list(key = "time", label = TIME), list(key = "mean", label = "Forecast", type = "number")))
for (level in LEVELS) {
fc_cols <- c(fc_cols, list(list(key = paste0("lo_", lv(level)), label = sprintf("%s%% low", lv(level)), type = "number"),
list(key = paste0("hi_", lv(level)), label = sprintf("%s%% high", lv(level)), type = "number")))
}
tables <- c(tables, extra_tables)
keep <- setdiff(names(forecasts), c("t", "kind", if (is.null(SERIES)) "series"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Forecast", columns = fc_cols,
rows = lapply(seq_len(min(200, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
summary <- sprintf("%s: %d-step forecasts of %s (%s data, %d observations).", values$model_label, H, VALUE, freq_label, n_obs)
if (!is.null(accuracy$mae)) summary <- paste0(summary, sprintf(" Backtest MAE %s over %d origin%s.", format(signif(accuracy$mae, 3)), n_origins, if (n_origins != 1) "s" else ""))
cs_publish(list(
title = "N-BEATS neural forecast",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
n = n_obs,
summary = summary,
statistics = lapply(utils::head(show, 3), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
tables = tables,
values = values,
assumptions = extra_assumptions,
warnings = warnings,
notes = list(),
charts = charts,
artifacts = artifacts
))
N-BEATS-I (trend + seasonality): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 17.3 over 1 origin.
- MAE
- 17.346
- RMSE
- 20.715
- MAPE
- 0.0366
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough windows to learn from — 97 training windows for 2560 weights. That is little data for a neural network: compare it with ETS and the seasonal naive forecast on the same backtest.
- Beats the seasonal naive forecast — Backtest MAE is 0.36 times the seasonal naive forecast's from the same origins.
- Residuals look uncorrelated — Ljung–Box at 21 lags: p = 0.882.
Backtest accuracy (1 origin, horizon 12)
| Metric | Value |
|---|---|
| MAE | 17.346 |
| RMSE | 20.715 |
| MAPE | 0.0366 |
| sMAPE | 0.0358 |
| MASE | 0.5696 |
| WAPE | 0.0364 |
| Coverage of the 80% interval | 0.4167 |
| Coverage of the 95% interval | 0.5000 |
Forecast by part (they add up to the forecast; the first part carries the last value)
| month | trend | seasonality |
|---|---|---|
| 1961-01-01 | 409.77 | 40.871 |
| 1961-02-01 | 410.19 | 8.626 |
| 1961-03-01 | 410.82 | 65.722 |
| 1961-04-01 | 411.66 | 70.684 |
| 1961-05-01 | 412.69 | 96.773 |
| 1961-06-01 | 413.94 | 152.85 |
| 1961-07-01 | 415.38 | 244.02 |
| 1961-08-01 | 417.03 | 243.04 |
| 1961-09-01 | 418.88 | 142.09 |
| 1961-10-01 | 420.94 | 69.912 |
| 1961-11-01 | 423.20 | 11.256 |
| 1961-12-01 | 425.67 | 55.623 |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1961-01-01 | 450.64 | 439.52 | 461.77 | 433.63 | 467.65 |
| 1961-02-01 | 418.82 | 408.93 | 428.71 | 403.70 | 433.95 |
| 1961-03-01 | 476.55 | 464.53 | 488.56 | 458.17 | 494.92 |
| 1961-04-01 | 482.34 | 468.96 | 495.73 | 461.87 | 502.81 |
| 1961-05-01 | 509.47 | 496.40 | 522.53 | 489.49 | 529.45 |
| 1961-06-01 | 566.78 | 553.80 | 579.76 | 546.93 | 586.63 |
| 1961-07-01 | 659.40 | 644.17 | 674.64 | 636.10 | 682.70 |
| 1961-08-01 | 660.07 | 645.24 | 674.90 | 637.39 | 682.75 |
| 1961-09-01 | 560.98 | 547.08 | 574.87 | 539.72 | 582.23 |
| 1961-10-01 | 490.86 | 474.99 | 506.72 | 466.60 | 515.11 |
| 1961-11-01 | 434.46 | 417.46 | 451.46 | 408.46 | 460.46 |
| 1961-12-01 | 481.29 | 463.74 | 498.84 | 454.46 | 508.13 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# N-BEATS neural forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.nbeats 1.2.0 · spec 8037dba215b0dcf0
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.deep import nbeats # twin of codesplashr::cs_nb_fit_forecast (torch, shared initial weights)
from codesplash.ml import forecast_models as fcm
# %% Data
TIME = "month"
VALUE = "passengers"
SERIES = None
H = 12
LEVELS = [float(v) for v in [80, 95]]
SEASON = None # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 1
STEP = None # None = the horizon
OFFSETS = None # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None # None = train on all values before each origin
TRAIN_START = None # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = []
PARAMS = {
"architecture": "interpretable",
"blocks": 2,
"layers": 2,
"width": 16,
"degree": 2,
"window": None,
"loss": "mse",
"epochs": 120,
"learning_rate": 0.005,
"batch_size": None,
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
cut = fc.parse_time(TRAIN_START, TEMPORAL)
early = np.nan_to_num(times_all, nan=np.inf) < cut
if early.any():
warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None] # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.nbeats/interpretable_monthly/out-python")
extra_tables = [] # model blocks may add result tables (e.g. automatic selection)
extra_assumptions = [] # … and assumption rows
current_series = None
X_TRAIN = None # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE = None # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[current_series] = {"resid": [...], "fitdf": k, "lags": L} from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG = {}
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/forecast.nbeats/interpretable_monthly/out-python",
)
# N-BEATS (Oreshkin et al. 2020) on PyTorch (float64, one thread): windows of past values, scaled around their last
# value, run through chained basis-expansion blocks that forecast every horizon step at once. R's torch trains the
# same network from the same initial weights with the same Adam steps.
FINAL = {}
LB3_PARTS = PARAMS["architecture"] == "interpretable"
def min_train(m):
return H + 11 # a lookback of at least 2 and at least 10 training windows
def prepare_series(y, t, m, freq):
return None
def fit_forecast(y, t, h, m, levels, spec):
res = nbeats.fit_forecast(
y, h, m, levels,
model="nbeats",
architecture=PARAMS["architecture"],
window=PARAMS["window"],
blocks=int(PARAMS["blocks"]),
layers=int(PARAMS["layers"]),
width=int(PARAMS["width"]),
degree=int(PARAMS["degree"]),
loss=PARAMS["loss"],
epochs=int(PARAMS["epochs"]),
lr=PARAMS["learning_rate"],
batch_size=PARAMS["batch_size"],
seed=SEED,
)
FINAL[current_series] = (res, [float(v) for v in t])
return res
# %% Backtests and forecasts
def lv(level):
return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")
bt_rows = []
fc_rows = []
facts = {}
labels = {}
freq_label = ""
freq_alias = ""
seasons = []
n_obs = 0
n_origins = 0
filled = 0
residuals_first = None
for key in series_keys:
current_series = key # model blocks may read it (e.g. table titles)
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
t_raw, y_raw = times_all[sel], values_all[sel]
if int(np.sum(~np.isnan(y_raw))) < 3: # too few values to read the time step from
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(1) + 1, n=int(np.sum(~np.isnan(y_raw))))
x_later = None
if XREG: # rows after the last observed value carry known future regressors
x_raw = x_all[sel]
last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
later = t_raw > last_y
order_later = np.argsort(t_raw[later], kind="stable")
x_later = x_raw[later][order_later]
t_raw, y_raw, x_raw = t_raw[~later], y_raw[~later], x_raw[~later]
freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t, y, nfill = fc.regularize(t_raw, y_raw, freq)
x_grid = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq)[1] for j in range(x_raw.shape[1])]) if XREG else None
filled += nfill
freq_label = freq["label"]
freq_alias = fc.ALIASES.get(freq["unit"], "")
m = int(SEASON) if SEASON else int(freq["season"])
seasons.append(m)
y = [float(v) for v in y]
n = len(y)
n_obs += n
if n < min_train(m) + 1:
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(m) + 1, n=n)
spec = prepare_series(y, t, m, freq)
step = int(STEP) if STEP else H
if OFFSETS is not None:
origins = fc.plan_origins(n, H, [int(v) for v in OFFSETS], min_train(m))
if len(origins) < len(OFFSETS):
warnings.append(f"{len(OFFSETS) - len(origins)} of {len(OFFSETS)} backtest origins were skipped for {key or VALUE}: too few values before them.")
else:
origins = fc.backtest_origins(n, H, WINDOWS, step, min_train(m))
for o in origins:
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
if XREG:
X_TRAIN, X_FUTURE = x_grid[start:o], x_grid[o:o + H]
try:
res = fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec)
except Exception as e: # a failed origin is skipped, not fatal
warnings.append(f"Backtest from {fc.format_time(t[o - 1], TEMPORAL)} failed: {e}")
continue
n_origins += 1
scale = fc.mase_scale(y[:o], m)
scale2 = fc.rmsse_scale(y[:o], m)
lag = m if (m > 1 and o > m) else 1 # the seasonal naive forecast from this origin (MASE's lag rule)
for k in range(H):
row = {
"series": key,
"origin": fc.format_time(t[o - 1], TEMPORAL),
"time": fc.format_time(t[o + k], TEMPORAL),
"h": k + 1,
"actual": y[o + k],
"mean": float(res["mean"][k]),
"scale": scale,
"scale2": scale2,
"last": y[o - 1],
"snaive": y[o - lag + k % lag],
}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(res["lower"][level][k])
row[f"hi_{lv(level)}"] = float(res["upper"][level][k])
bt_rows.append(row)
if XREG:
X_TRAIN = x_grid
X_FUTURE = fc.future_regressors(x_grid, x_later, H)
if len(x_later) < H:
warnings.append(f"Future values of {', '.join(XREG)} are known for {len(x_later)} of {H} steps; the last known values are held for the rest.")
final = fit_forecast(y, t, H, m, LEVELS, spec)
labels[key] = final["label"]
for name, value in final["facts"].items():
facts[name if not SERIES else f"{name}[{key}]"] = value
fitted = final.get("fitted")
diag = DIAG.get(key) or {}
resid = diag.get("resid")
if residuals_first is None and resid is not None:
residuals_first = [float(v) for v in resid]
elif residuals_first is None and fitted is not None:
residuals_first = [y[i] - fitted[i] for i in range(n) if fitted[i] is not None and not math.isnan(fitted[i])]
for i in range(n):
row = {"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "actual", "mean": y[i]}
if resid is not None and i >= n - len(resid): # the last len(resid) times (differencing drops early ones)
row["resid"] = float(resid[i - (n - len(resid))])
if "fitdf" in diag:
row["lb_fitdf"] = float(diag["fitdf"])
if "lags" in diag:
row["lb_lags"] = float(diag["lags"])
fc_rows.append(row)
if fitted is not None and not math.isnan(fitted[i]):
fc_rows.append({"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "fitted", "mean": float(fitted[i])})
future = fc.future_times(t[-1], freq, H)
for k in range(H):
row = {"series": key, "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(final["mean"][k])}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(final["lower"][level][k])
row[f"hi_{lv(level)}"] = float(final["upper"][level][k])
fc_rows.append(row)
if filled:
warnings.append(f"{filled} missing time steps or values were filled by linear interpolation.")
# %% Accuracy
accuracy = fc.accuracy(bt_rows, LEVELS)
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]
top = lv(max(LEVELS)) if LEVELS else None
def wsum(xs):
return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)
values = {
"n_series": len(series_keys),
"n_obs": n_obs,
"horizon": H,
"season": seasons[0],
"n_origins": n_origins,
"filled": filled,
"fc_check": wsum([r["mean"] for r in forecasts]),
"model_label": labels[series_keys[0]] if len(series_keys) == 1 else f"{len(series_keys)} series, one model each",
"freq_label": freq_label,
"frequency": freq_alias,
}
if top:
values["fc_lo_check"] = wsum([r[f"lo_{top}"] for r in forecasts])
values["fc_hi_check"] = wsum([r[f"hi_{top}"] for r in forecasts])
for k, v in accuracy.items():
values[f"bt[{k}]"] = v
values.update(facts)
pd.DataFrame(fc_rows).to_parquet(os.path.join(out, "forecast.parquet"), index=False)
artifacts = [{"key": "forecast", "path": os.path.join(out, "forecast.parquet"), "format": "parquet"}]
if bt_rows:
pd.DataFrame(bt_rows).to_parquet(os.path.join(out, "backtest.parquet"), index=False)
artifacts.append({"key": "backtest", "path": os.path.join(out, "backtest.parquet"), "format": "parquet"})
# %% Charts
charts = []
shown = series_keys[:8]
fan = [r for r in fc_rows if r["series"] in shown and r["kind"] != "fitted"]
kind = "temporal" if TEMPORAL else "numeric"
roles = {
"time": cs.col(TIME, [r["time"] for r in fan], kind=kind),
"value": cs.col(VALUE, [r["mean"] for r in fan], kind="numeric"),
"kind": cs.col("kind", [r["kind"] for r in fan], kind="categorical", levels=["actual", "forecast"]),
}
for level in (80.0, 95.0):
if level in LEVELS:
roles[f"lo_{lv(level)}"] = cs.col(f"lo_{lv(level)}", [r.get(f"lo_{lv(level)}") for r in fan], kind="numeric")
roles[f"hi_{lv(level)}"] = cs.col(f"hi_{lv(level)}", [r.get(f"hi_{lv(level)}") for r in fan], kind="numeric")
if SERIES:
roles["series"] = cs.col(SERIES, [r["series"] for r in fan], kind="categorical", levels=shown)
charts.append(cs.chart("forecast", "forecast-fan", f"Forecast of {VALUE}", roles))
if bt_rows:
charts.append(
cs.chart(
"backtest",
"backtest-errors",
"Backtest errors by horizon",
{
"h": cs.col("horizon", [r["h"] for r in bt_rows], kind="numeric"),
"error": cs.col("error", [r["actual"] - r["mean"] for r in bt_rows], kind="numeric"),
"origin": cs.col("origin", [r["origin"] for r in bt_rows], kind="categorical"),
},
)
)
if residuals_first and len(residuals_first) > 4:
lags = min(max(2 * seasons[0], 10), len(residuals_first) - 1, 48)
r_acf = fc.acf(residuals_first, lags)
bound = 1.959963984540054 / math.sqrt(len(residuals_first))
charts.append(
cs.chart(
"acf",
"acf-plot",
"Residual autocorrelation",
{
"lag": cs.col("lag", list(range(1, lags + 1)), kind="numeric"),
"acf": cs.col("ACF", r_acf, kind="numeric"),
"bound": cs.col("bound", [bound] * lags, kind="numeric"),
},
)
)
# %% Forecast parts
res0, t0 = FINAL[series_keys[0]]
freq0 = fc.detect_frequency(np.array(t0), TEMPORAL)
times0 = [fc.format_time(v, TEMPORAL) for v in fc.future_times(t0[-1], freq0, H)]
names0 = list(res0["components"])
parts0 = [res0["components"][name][k] for name in names0 for k in range(H)]
wparts = [(j + 1.0) * (k + 1.0) for j in range(len(names0)) for k in range(H)]
values["parts_check"] = fc._sum([wparts[i] * parts0[i] for i in range(len(parts0))]) / fc._sum(wparts)
if PARAMS["window"] and int(res0["facts"]["window"]) < int(PARAMS["window"]):
warnings.append(f"The lookback was shortened to {int(res0['facts']['window'])} values so that at least 10 windows train.")
suffix0 = f" — {series_keys[0]}" if SERIES else ""
if LB3_PARTS:
charts.append(
cs.chart(
"parts",
"forecast-components",
f"Forecast of {VALUE} by part" + suffix0,
{
"time": cs.col(TIME, [times0[k] for name in names0 for k in range(H)], kind="temporal" if TEMPORAL else "numeric"),
"value": cs.col(VALUE, parts0, kind="numeric"),
"part": cs.col("part", [name for name in names0 for k in range(H)], kind="categorical", levels=names0),
},
)
)
extra_tables.append(
{
"key": "parts",
"title": "Forecast by part (they add up to the forecast; the first part carries the last value)" + suffix0,
"columns": [{"key": "time", "label": TIME}] + [{"key": f"p{j}", "label": name, "type": "number"} for j, name in enumerate(names0)],
"rows": [dict({"time": times0[k]}, **{f"p{j}": res0["components"][name][k] for j, name in enumerate(names0)}) for k in range(H)],
}
)
# %% Checks
nw0 = int(res0["facts"]["n_windows"])
extra_assumptions.append(
{
"key": "enough_windows",
"label": "Enough windows to learn from",
"status": "pass" if nw0 >= 100 else "warn",
"statistic": float(nw0),
"detail": f"{nw0} training windows for {int(res0['facts']['n_params'])} weights." + ("" if nw0 >= 100 else " That is little data for a neural network: compare it with ETS and the seasonal naive forecast on the same backtest."),
}
)
rel0 = fc.naive_relative_mae(bt_rows) # not MASE < 1: MASE scales by the in-sample one-step naive error
if math.isfinite(rel0):
values["bt[rel_mae]"] = rel0
beats0 = rel0 < 1
extra_assumptions.append(
{
"key": "beats_naive",
"label": "Beats the seasonal naive forecast",
"status": "pass" if beats0 else "warn",
"statistic": rel0,
"detail": f"Backtest MAE is {rel0:.2f} times the seasonal naive forecast's from the same origins." + ("" if beats0 else " Repeating the last season forecast these origins at least as well."),
}
)
check0 = fcm.residual_check(residuals_first, seasons[0])
if check0 is not None:
values["lb_p"] = check0["p"]
extra_assumptions.append(fcm.residual_row(check0, "The network left autocorrelation in its one-step errors: try a longer lookback, or ARIMA.", series_keys[0]))
# %% Result
show = [m for m in ("mae", "rmse", "mape", "smape", "mase", "wape") if m in accuracy]
tables = []
if accuracy:
tables.append(
{
"key": "accuracy",
"title": f"Backtest accuracy ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
"columns": [{"key": "metric", "label": "Metric"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"metric": k.upper() if k != "smape" else "sMAPE", "value": accuracy[k]} for k in show]
+ [{"metric": f"Coverage of the {lv(level)}% interval", "value": accuracy.get(f"coverage_{lv(level)}")} for level in LEVELS if f"coverage_{lv(level)}" in accuracy],
}
)
tables.extend(extra_tables)
tables.append(
{
"key": "forecast",
"title": "Forecast",
"columns": ([{"key": "series", "label": "Series"}] if SERIES else [])
+ [{"key": "time", "label": TIME}, {"key": "mean", "label": "Forecast", "type": "number"}]
+ [c for level in LEVELS for c in ({"key": f"lo_{lv(level)}", "label": f"{lv(level)}% low", "type": "number"}, {"key": f"hi_{lv(level)}", "label": f"{lv(level)}% high", "type": "number"})],
"rows": [{k: v for k, v in r.items() if k not in ("t", "kind") and (SERIES or k != "series")} for r in forecasts[:200]],
}
)
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} ({freq_label} data, {n_obs} observations)."
if "mae" in accuracy:
summary += f" Backtest MAE {accuracy['mae']:.3g} over {n_origins} origin{'s' if n_origins != 1 else ''}."
cs.publish(
{
"title": "N-BEATS neural forecast",
"engine": cs.engine_info("torch", "codesplash", "numpy", "pandas"),
"n": n_obs,
"summary": summary,
"statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in show[:3]],
"tables": tables,
"values": values,
"assumptions": extra_assumptions,
"warnings": warnings,
"notes": [],
"charts": charts,
"artifacts": artifacts,
}
)
N-BEATS-I (trend + seasonality) reads 36 months at a time. It trains on 97 windows with 2,560 weights.
Open Forecast by part. The parts add up to the forecast; the first carries the last observed value.
How far to trust it
ReflectThe backtest MASE is 0.57. MASE divides the errors by the naive forecast's one-step error in the training data, so it can't say whether the network beat the seasonal naive forecast over the horizon. MAE vs seasonal naive can: it is 0.36, below 1, so it beat repeating last year on these origins. But only 42% of actual values fell inside its 80% intervals.
Its intervals come from in-sample errors, and a network with that many weights fits its own windows closely. Which would you quote: the point forecast, the interval, or both with a caveat?
Coarse to fine
PredictPredict first
N-HiTSN-HiTSN-BEATS with stacks that read coarser, max-pooled views of the past and forecast a few interpolated knots, from smooth to detailed. keeps the block chain. What does its first stack do differently from an N-BEATS block?
Reveal
It reads a coarser, max-pooled window and forecasts a few knots that are interpolated over the horizon. Early stacks draw the slow shape and later ones add detail.
Fit N-HiTS
In the appN-HiTS (3 stacks, pooling 4/2/1): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 17.2 over 1 origin.
- MAE
- 17.223
- RMSE
- 20.047
- MAPE
- 0.0363
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | month | passengers |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | −662,688,000,000 | 112 |
| — | — | actual | — | — | −660,009,600,000 | 118 |
| — | — | actual | — | — | −657,590,400,000 | 132 |
| — | — | actual | — | — | −654,912,000,000 | 129 |
| — | — | actual | — | — | −652,320,000,000 | 121 |
| — | — | actual | — | — | −649,641,600,000 | 135 |
| — | — | actual | — | — | −647,049,600,000 | 148 |
| — | — | actual | — | — | −644,371,200,000 | 148 |
| — | — | actual | — | — | −641,692,800,000 | 136 |
| — | — | actual | — | — | −639,100,800,000 | 119 |
| — | — | actual | — | — | −636,422,400,000 | 104 |
| — | — | actual | — | — | −633,830,400,000 | 118 |
| — | — | actual | — | — | −631,152,000,000 | 115 |
| — | — | actual | — | — | −628,473,600,000 | 126 |
| — | — | actual | — | — | −626,054,400,000 | 141 |
| — | — | actual | — | — | −623,376,000,000 | 135 |
| — | — | actual | — | — | −620,784,000,000 | 125 |
| — | — | actual | — | — | −618,105,600,000 | 149 |
| — | — | actual | — | — | −615,513,600,000 | 170 |
| — | — | actual | — | — | −612,835,200,000 | 170 |
| — | — | actual | — | — | −610,156,800,000 | 158 |
| — | — | actual | — | — | −607,564,800,000 | 133 |
| — | — | actual | — | — | −604,886,400,000 | 114 |
| — | — | actual | — | — | −602,294,400,000 | 140 |
| — | — | actual | — | — | −599,616,000,000 | 145 |
| — | — | actual | — | — | −596,937,600,000 | 150 |
| — | — | actual | — | — | −594,518,400,000 | 178 |
| — | — | actual | — | — | −591,840,000,000 | 163 |
| — | — | actual | — | — | −589,248,000,000 | 172 |
| — | — | actual | — | — | −586,569,600,000 | 178 |
| — | — | actual | — | — | −583,977,600,000 | 199 |
| — | — | actual | — | — | −581,299,200,000 | 199 |
| — | — | actual | — | — | −578,620,800,000 | 184 |
| — | — | actual | — | — | −576,028,800,000 | 162 |
| — | — | actual | — | — | −573,350,400,000 | 146 |
| — | — | actual | — | — | −570,758,400,000 | 166 |
| — | — | actual | — | — | −568,080,000,000 | 171 |
| — | — | actual | — | — | −565,401,600,000 | 180 |
| — | — | actual | — | — | −562,896,000,000 | 193 |
| — | — | actual | — | — | −560,217,600,000 | 181 |
| — | — | actual | — | — | −557,625,600,000 | 183 |
| — | — | actual | — | — | −554,947,200,000 | 218 |
| — | — | actual | — | — | −552,355,200,000 | 230 |
| — | — | actual | — | — | −549,676,800,000 | 242 |
| — | — | actual | — | — | −546,998,400,000 | 209 |
| — | — | actual | — | — | −544,406,400,000 | 191 |
| — | — | actual | — | — | −541,728,000,000 | 172 |
| — | — | actual | — | — | −539,136,000,000 | 194 |
| — | — | actual | — | — | −536,457,600,000 | 196 |
| — | — | actual | — | — | −533,779,200,000 | 196 |
| — | — | actual | — | — | −531,360,000,000 | 236 |
| — | — | actual | — | — | −528,681,600,000 | 235 |
| — | — | actual | — | — | −526,089,600,000 | 229 |
| — | — | actual | — | — | −523,411,200,000 | 243 |
| — | — | actual | — | — | −520,819,200,000 | 264 |
| — | — | actual | — | — | −518,140,800,000 | 272 |
| — | — | actual | — | — | −515,462,400,000 | 237 |
| — | — | actual | — | — | −512,870,400,000 | 211 |
| — | — | actual | — | — | −510,192,000,000 | 180 |
| — | — | actual | — | — | −507,600,000,000 | 201 |
First 60 of 156 rows.
View data
| error | horizon | origin |
|---|---|---|
| 20.544 | 1 | 1959-12-01 |
| 10.107 | 2 | 1959-12-01 |
| −9.990 | 3 | 1959-12-01 |
| 36.205 | 4 | 1959-12-01 |
| 28.934 | 5 | 1959-12-01 |
| 32.642 | 6 | 1959-12-01 |
| 14.431 | 7 | 1959-12-01 |
| −6.279 | 8 | 1959-12-01 |
| −17.084 | 9 | 1959-12-01 |
| 12.463 | 10 | 1959-12-01 |
| 0.9939 | 11 | 1959-12-01 |
| −17.006 | 12 | 1959-12-01 |
View data
| ACF | bound | lag |
|---|---|---|
| −0.1144 | 0.1886 | 1 |
| 0.0043 | 0.1886 | 2 |
| 0.0203 | 0.1886 | 3 |
| −0.1340 | 0.1886 | 4 |
| 0.0049 | 0.1886 | 5 |
| 0.1244 | 0.1886 | 6 |
| −0.1222 | 0.1886 | 7 |
| −0.0894 | 0.1886 | 8 |
| 0.1061 | 0.1886 | 9 |
| −0.1115 | 0.1886 | 10 |
| 0.0180 | 0.1886 | 11 |
| 0.0759 | 0.1886 | 12 |
| −0.0873 | 0.1886 | 13 |
| −0.0165 | 0.1886 | 14 |
| 0.0215 | 0.1886 | 15 |
| −0.1131 | 0.1886 | 16 |
| −0.0996 | 0.1886 | 17 |
| 0.0431 | 0.1886 | 18 |
| −0.1153 | 0.1886 | 19 |
| −0.0955 | 0.1886 | 20 |
| −0.0020 | 0.1886 | 21 |
| −0.0129 | 0.1886 | 22 |
| 0.1481 | 0.1886 | 23 |
| 0.0986 | 0.1886 | 24 |
View data
| part | month | passengers |
|---|---|---|
| stack 1 (pool 4, 3 knots) | −283,996,800,000 | 445.62 |
| stack 1 (pool 4, 3 knots) | −281,318,400,000 | 448.13 |
| stack 1 (pool 4, 3 knots) | −278,899,200,000 | 450.63 |
| stack 1 (pool 4, 3 knots) | −276,220,800,000 | 453.14 |
| stack 1 (pool 4, 3 knots) | −273,628,800,000 | 455.65 |
| stack 1 (pool 4, 3 knots) | −270,950,400,000 | 458.15 |
| stack 1 (pool 4, 3 knots) | −268,358,400,000 | 457.64 |
| stack 1 (pool 4, 3 knots) | −265,680,000,000 | 454.10 |
| stack 1 (pool 4, 3 knots) | −263,001,600,000 | 450.56 |
| stack 1 (pool 4, 3 knots) | −260,409,600,000 | 447.02 |
| stack 1 (pool 4, 3 knots) | −257,731,200,000 | 443.48 |
| stack 1 (pool 4, 3 knots) | −255,139,200,000 | 439.94 |
| stack 2 (pool 2, 6 knots) | −283,996,800,000 | −2.487 |
| stack 2 (pool 2, 6 knots) | −281,318,400,000 | 7.799 |
| stack 2 (pool 2, 6 knots) | −278,899,200,000 | 18.085 |
| stack 2 (pool 2, 6 knots) | −276,220,800,000 | 21.701 |
| stack 2 (pool 2, 6 knots) | −273,628,800,000 | 23.650 |
| stack 2 (pool 2, 6 knots) | −270,950,400,000 | 34.659 |
| stack 2 (pool 2, 6 knots) | −268,358,400,000 | 51.706 |
| stack 2 (pool 2, 6 knots) | −265,680,000,000 | 57.087 |
| stack 2 (pool 2, 6 knots) | −263,001,600,000 | 44.967 |
| stack 2 (pool 2, 6 knots) | −260,409,600,000 | 34.628 |
| stack 2 (pool 2, 6 knots) | −257,731,200,000 | 31.414 |
| stack 2 (pool 2, 6 knots) | −255,139,200,000 | 28.200 |
| stack 3 (pool 1, 12 knots) | −283,996,800,000 | −7.287 |
| stack 3 (pool 1, 12 knots) | −281,318,400,000 | −40.356 |
| stack 3 (pool 1, 12 knots) | −278,899,200,000 | 0.8168 |
| stack 3 (pool 1, 12 knots) | −276,220,800,000 | 6.174 |
| stack 3 (pool 1, 12 knots) | −273,628,800,000 | 18.716 |
| stack 3 (pool 1, 12 knots) | −270,950,400,000 | 82.169 |
| stack 3 (pool 1, 12 knots) | −268,358,400,000 | 150.18 |
| stack 3 (pool 1, 12 knots) | −265,680,000,000 | 134.87 |
| stack 3 (pool 1, 12 knots) | −263,001,600,000 | 39.923 |
| stack 3 (pool 1, 12 knots) | −260,409,600,000 | −18.467 |
| stack 3 (pool 1, 12 knots) | −257,731,200,000 | −66.794 |
| stack 3 (pool 1, 12 knots) | −255,139,200,000 | −13.030 |
Assumptions
- Enough windows to learn from — 97 training windows for 2640 weights. That is little data for a neural network: compare it with ETS and the seasonal naive forecast on the same backtest.
- Beats the seasonal naive forecast — Backtest MAE is 0.36 times the seasonal naive forecast's from the same origins.
- Residuals look uncorrelated — Ljung–Box at 21 lags: p = 0.591.
Backtest accuracy (1 origin, horizon 12)
| Metric | Value |
|---|---|
| MAE | 17.223 |
| RMSE | 20.047 |
| MAPE | 0.0363 |
| sMAPE | 0.0370 |
| MASE | 0.5656 |
| WAPE | 0.0362 |
| Coverage of the 80% interval | 0.2500 |
| Coverage of the 95% interval | 0.6667 |
Forecast by part (they add up to the forecast; the first part carries the last value)
| month | stack 1 (pool 4, 3 knots) | stack 2 (pool 2, 6 knots) | stack 3 (pool 1, 12 knots) |
|---|---|---|---|
| 1961-01-01 | 445.62 | −2.487 | −7.287 |
| 1961-02-01 | 448.13 | 7.799 | −40.356 |
| 1961-03-01 | 450.63 | 18.085 | 0.8168 |
| 1961-04-01 | 453.14 | 21.701 | 6.174 |
| 1961-05-01 | 455.65 | 23.650 | 18.716 |
| 1961-06-01 | 458.15 | 34.659 | 82.169 |
| 1961-07-01 | 457.64 | 51.706 | 150.18 |
| 1961-08-01 | 454.10 | 57.087 | 134.87 |
| 1961-09-01 | 450.56 | 44.967 | 39.923 |
| 1961-10-01 | 447.02 | 34.628 | −18.467 |
| 1961-11-01 | 443.48 | 31.414 | −66.794 |
| 1961-12-01 | 439.94 | 28.200 | −13.030 |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1961-01-01 | 435.85 | 425.56 | 446.13 | 420.12 | 451.58 |
| 1961-02-01 | 415.57 | 406.96 | 424.18 | 402.40 | 428.74 |
| 1961-03-01 | 469.53 | 459.44 | 479.63 | 454.09 | 484.98 |
| 1961-04-01 | 481.02 | 469.48 | 492.55 | 463.37 | 498.66 |
| 1961-05-01 | 498.01 | 486.30 | 509.72 | 480.10 | 515.92 |
| 1961-06-01 | 574.98 | 562.38 | 587.58 | 555.71 | 594.25 |
| 1961-07-01 | 659.53 | 647.75 | 671.30 | 641.52 | 677.54 |
| 1961-08-01 | 646.05 | 634.19 | 657.91 | 627.91 | 664.19 |
| 1961-09-01 | 535.45 | 522.79 | 548.11 | 516.09 | 554.81 |
| 1961-10-01 | 463.18 | 450.69 | 475.67 | 444.08 | 482.27 |
| 1961-11-01 | 408.10 | 390.64 | 425.56 | 381.39 | 434.81 |
| 1961-12-01 | 455.11 | 436.91 | 473.31 | 427.27 | 482.95 |
The exact R script · R R version 4.5.1 (2025-06-13)
# N-HiTS neural forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.nhits 1.2.0 · spec 73790748b2a3a0c6
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network is built by codesplashr's cs_nb_* twins.
# %% Data
TIME <- "month"
VALUE <- "passengers"
SERIES <- NULL
H <- 12
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 1
STEP <- NULL # NULL = the horizon
OFFSETS <- NULL # the host's BacktestPlan: distance of each origin from the end of the series; NULL = windows and step
TRAIN_WINDOW <- NULL # NULL = train on all values before each origin
TRAIN_START <- NULL # rows before this time are left out (for example, before a structural break)
SEED <- 42
XREG <- character(0)
PARAMS <- list(
pool_sizes = c(4, 2, 1),
downsample = c(4, 2, 1),
blocks = 1,
layers = 2,
width = 16,
window = NULL,
loss = "mae",
epochs = 150,
learning_rate = 0.005,
batch_size = NULL,
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", col_select = unique(c(TIME, VALUE, SERIES, XREG))))
cs_check_finite_columns(df, c(TIME, VALUE, XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
warnings <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
x_all <- if (length(XREG)) do.call(cbind, lapply(XREG, function(c) suppressWarnings(as.numeric(df[[c]])))) else NULL
n_early <- 0L
if (!is.null(TRAIN_START)) {
cut <- cs_ml_fc_parse_time(TRAIN_START, TEMPORAL)
early <- !is.na(times_all) & times_all < cut
n_early <- sum(early)
if (n_early > 0) {
warnings <- c(warnings, sprintf("%d rows before %s were left out of training.", n_early, as.character(TRAIN_START)))
times_all[early] <- NA
}
}
keys_all <- if (!is.null(SERIES)) as.character(df[[SERIES]]) else rep(NA_character_, nrow(df))
dropped <- sum(is.na(times_all)) - n_early
if (dropped > 0) warnings <- c(warnings, sprintf("%d rows without a time were left out.", dropped))
series_keys <- if (!is.null(SERIES)) sort(unique(keys_all[!is.na(keys_all)]), method = "radix") else list(NULL)
if (!is.null(SERIES) && anyNA(keys_all)) warnings <- c(warnings, "Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the Python driver.
if (all(is.na(values_all))) cs_error("CS_E_ALL_MISSING", column = VALUE)
if (!any(!is.na(times_all) & !is.na(values_all))) cs_error("CS_E_NO_ROWS")
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.nhits/three_stacks_monthly/out-r")
extra_tables <- list() # model blocks may add result tables (assign with <<-)
extra_assumptions <- list() # … and assumption rows
current_series <- NULL
X_TRAIN <- NULL # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE <- NULL # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[[current_series, or "_"]] <<- list(resid = ..., fitdf = k, lags = L) from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG <- list()
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/forecast.nhits/three_stacks_monthly/out-r")
# N-HiTS (Challu et al. 2023) on torch for R (float64, one thread): each stack max-pools the scaled window and forecasts a
# few knots that are interpolated over the horizon, from coarse to fine time scales. Python's torch trains the same
# network from the same initial weights with the same Adam steps.
FINAL <- list()
LB3_PARTS <- TRUE
min_train <- function(m) H + 11L # a lookback of at least 2 and at least 10 training windows
prepare_series <- function(y, t, m, freq) NULL
fit_forecast <- function(y, t, h, m, levels, spec) {
res <- cs_nb_fit_forecast(
y, h, m, levels,
model = "nhits",
window = PARAMS$window,
blocks = as.integer(PARAMS$blocks),
layers = as.integer(PARAMS$layers),
width = as.integer(PARAMS$width),
pool_sizes = as.integer(unlist(PARAMS$pool_sizes)),
downsample = as.integer(unlist(PARAMS$downsample)),
loss = PARAMS$loss,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = PARAMS$batch_size,
seed = SEED
)
FINAL[[if (is.null(current_series)) "_" else current_series]] <<- list(res = res, t = as.numeric(t))
res
}
# %% Backtests and forecasts
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)
bt_rows <- list()
fc_rows <- list()
facts <- list()
labels <- list()
freq_label <- ""
freq_alias <- ""
seasons <- integer(0)
n_obs <- 0
n_origins <- 0
filled <- 0
residuals_first <- NULL
for (key in series_keys) {
current_series <- key # model blocks may read it (e.g. table titles)
sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
t_raw <- times_all[sel]; y_raw <- values_all[sel]
if (sum(!is.na(y_raw)) < 3) { # too few values to read the time step from
cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(1) + 1, n = sum(!is.na(y_raw)))
}
x_later <- NULL
if (length(XREG)) { # rows after the last observed value carry known future regressors
x_raw <- x_all[sel, , drop = FALSE]
last_y <- max(t_raw[!is.na(y_raw)])
later <- t_raw > last_y
x_later <- x_raw[later, , drop = FALSE][order(t_raw[later]), , drop = FALSE]
t_raw <- t_raw[!later]; y_raw <- y_raw[!later]; x_raw <- x_raw[!later, , drop = FALSE]
}
freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
t <- reg$t; y <- reg$y
x_grid <- if (length(XREG)) do.call(cbind, lapply(seq_len(ncol(x_raw)), function(j) cs_ml_fc_regularize(t_raw, x_raw[, j], freq)$y)) else NULL
filled <- filled + reg$filled
freq_label <- freq$label
freq_alias <- cs_ml_fc_alias(freq$unit)
m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
seasons <- c(seasons, m)
n <- length(y)
n_obs <- n_obs + n
if (n < min_train(m) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(m) + 1, n = n)
spec <- prepare_series(y, t, m, freq)
step <- if (!is.null(STEP)) as.integer(STEP) else H
if (!is.null(OFFSETS)) {
origins <- cs_ml_fc_plan_origins(n, H, as.integer(OFFSETS), min_train(m))
if (length(origins) < length(OFFSETS)) {
warnings <- c(warnings, sprintf("%d of %d backtest origins were skipped for %s: too few values before them.", length(OFFSETS) - length(origins), length(OFFSETS), if (is.null(key)) VALUE else key))
}
} else {
origins <- cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))
}
for (o in origins) {
start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
if (length(XREG)) {
X_TRAIN <- x_grid[start:o, , drop = FALSE]
X_FUTURE <- x_grid[(o + 1):(o + H), , drop = FALSE]
}
res <- tryCatch(fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec), error = function(e) e)
if (inherits(res, "error")) {
warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(t[o], TEMPORAL), conditionMessage(res)))
next
}
n_origins <- n_origins + 1
scale <- cs_ml_fc_mase_scale(y[1:o], m)
scale2 <- cs_ml_fc_rmsse_scale(y[1:o], m)
lag <- if (m > 1 && o > m) m else 1 # the seasonal naive forecast from this origin (MASE's lag rule)
for (k in seq_len(H)) {
row <- list(series = if (is.null(key)) NA_character_ else key, origin = cs_ml_fc_format_time(t[o], TEMPORAL),
time = cs_ml_fc_format_time(t[o + k], TEMPORAL), h = k, actual = y[o + k],
mean = res$mean[k], scale = scale, scale2 = scale2, last = y[o],
snaive = y[o - lag + (k - 1) %% lag + 1])
for (level in LEVELS) {
row[[paste0("lo_", lv(level))]] <- res$lower[[as.character(level)]][k]
row[[paste0("hi_", lv(level))]] <- res$upper[[as.character(level)]][k]
}
bt_rows[[length(bt_rows) + 1]] <- row
}
}
if (length(XREG)) {
X_TRAIN <- x_grid
X_FUTURE <- cs_ml_fc_future_regressors(x_grid, x_later, H)
if (nrow(x_later) < H) {
warnings <- c(warnings, sprintf("Future values of %s are known for %d of %d steps; the last known values are held for the rest.", paste(XREG, collapse = ", "), nrow(x_later), H))
}
}
final <- fit_forecast(y, t, H, m, LEVELS, spec)
labels[[length(labels) + 1]] <- final$label
for (name in names(final$facts)) facts[[if (is.null(SERIES)) name else sprintf("%s[%s]", name, key)]] <- final$facts[[name]]
fitted <- final$fitted
diag <- DIAG[[if (is.null(key)) "_" else key]]
resid <- diag$resid
if (is.null(residuals_first) && !is.null(resid)) {
residuals_first <- as.numeric(resid)
} else if (is.null(residuals_first) && !is.null(fitted)) {
ok <- !is.na(fitted)
residuals_first <- (y - fitted)[ok]
}
skey <- if (is.null(key)) NA_character_ else key
for (i in seq_len(n)) {
row <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "actual", mean = y[i])
if (!is.null(resid) && i > n - length(resid)) row$resid <- resid[i - (n - length(resid))] # the last length(resid) times
if (!is.null(diag$fitdf)) row$lb_fitdf <- as.numeric(diag$fitdf)
if (!is.null(diag$lags)) row$lb_lags <- as.numeric(diag$lags)
fc_rows[[length(fc_rows) + 1]] <- row
if (!is.null(fitted) && !is.na(fitted[i])) {
fc_rows[[length(fc_rows) + 1]] <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "fitted", mean = fitted[i])
}
}
future <- cs_ml_fc_future_times(t[n], freq, H)
for (k in seq_len(H)) {
row <- list(series = skey, time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k], kind = "forecast", mean = final$mean[k])
for (level in LEVELS) {
row[[paste0("lo_", lv(level))]] <- final$lower[[as.character(level)]][k]
row[[paste0("hi_", lv(level))]] <- final$upper[[as.character(level)]][k]
}
fc_rows[[length(fc_rows) + 1]] <- row
}
}
if (filled > 0) warnings <- c(warnings, sprintf("%d missing time steps or values were filled by linear interpolation.", filled))
as_frame <- function(rows) {
cols <- unique(unlist(lapply(rows, names)))
as.data.frame(stats::setNames(lapply(cols, function(cn) {
v <- lapply(rows, function(r) if (is.null(r[[cn]])) NA else r[[cn]])
unlist(v)
}), cols), stringsAsFactors = FALSE, check.names = FALSE)
}
# %% Accuracy
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
top <- if (length(LEVELS)) lv(max(LEVELS)) else NULL
wsum <- function(xs) sum(weights * xs) / sum(weights)
values <- list(
n_series = length(series_keys), n_obs = n_obs, horizon = H, season = seasons[1], n_origins = n_origins,
filled = filled, fc_check = wsum(forecasts$mean),
model_label = if (length(series_keys) == 1) labels[[1]] else sprintf("%d series, one model each", length(series_keys)),
freq_label = freq_label, frequency = freq_alias
)
if (!is.null(top)) {
values$fc_lo_check <- wsum(forecasts[[paste0("lo_", top)]])
values$fc_hi_check <- wsum(forecasts[[paste0("hi_", top)]])
}
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
values <- c(values, facts)
nanoparquet::write_parquet(fc_df, file.path(out, "forecast.parquet"))
artifacts <- list(list(key = "forecast", path = file.path(out, "forecast.parquet"), format = "parquet"))
if (nrow(bt)) {
nanoparquet::write_parquet(bt, file.path(out, "backtest.parquet"))
artifacts[[2]] <- list(key = "backtest", path = file.path(out, "backtest.parquet"), format = "parquet")
}
# %% Charts
charts <- list()
shown <- if (!is.null(SERIES)) utils::head(series_keys, 8) else NULL
fan <- fc_df[fc_df$kind != "fitted" & (if (!is.null(SERIES)) fc_df$series %in% shown else TRUE), , drop = FALSE]
roles <- list(
time = cs_col(TIME, fan$time, kind = if (TEMPORAL) "temporal" else "numeric"),
value = cs_col(VALUE, fan$mean, kind = "numeric"),
kind = cs_col("kind", fan$kind, kind = "categorical", levels = c("actual", "forecast"))
)
for (level in c(80, 95)) {
if (level %in% LEVELS) {
roles[[paste0("lo_", lv(level))]] <- cs_col(paste0("lo_", lv(level)), fan[[paste0("lo_", lv(level))]], kind = "numeric")
roles[[paste0("hi_", lv(level))]] <- cs_col(paste0("hi_", lv(level)), fan[[paste0("hi_", lv(level))]], kind = "numeric")
}
}
if (!is.null(SERIES)) roles$series <- cs_col(SERIES, fan$series, kind = "categorical", levels = shown)
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Forecast of %s", VALUE), roles)
if (nrow(bt)) {
charts[[length(charts) + 1]] <- cs_chart("backtest", "backtest-errors", "Backtest errors by horizon", list(
h = cs_col("horizon", bt$h, kind = "numeric"),
error = cs_col("error", bt$actual - bt$mean, kind = "numeric"),
origin = cs_col("origin", bt$origin, kind = "categorical")
))
}
if (length(residuals_first) > 4) {
lags <- min(max(2 * seasons[1], 10), length(residuals_first) - 1, 48)
r_acf <- cs_ml_fc_acf(residuals_first, lags)
bound <- 1.959963984540054 / sqrt(length(residuals_first))
charts[[length(charts) + 1]] <- cs_chart("acf", "acf-plot", "Residual autocorrelation", list(
lag = cs_col("lag", seq_len(lags), kind = "numeric"),
acf = cs_col("ACF", r_acf, kind = "numeric"),
bound = cs_col("bound", rep(bound, lags), kind = "numeric")
))
}
# %% Forecast parts
first_key <- if (is.null(SERIES)) "_" else series_keys[1]
res0 <- FINAL[[first_key]]$res
t0 <- FINAL[[first_key]]$t
freq0 <- cs_ml_fc_detect_frequency(t0, TEMPORAL)
future0 <- cs_ml_fc_future_times(t0[length(t0)], freq0, H)
times0 <- vapply(future0, cs_ml_fc_format_time, if (TEMPORAL) "" else 0, temporal = TEMPORAL)
names0 <- names(res0$components)
parts0 <- unlist(lapply(names0, function(nm) res0$components[[nm]]), use.names = FALSE)
wparts <- as.numeric(outer(seq_len(H), seq_along(names0), function(k, j) j * k))
values$parts_check <- sum(wparts * parts0) / sum(wparts)
if (!is.null(PARAMS$window) && res0$facts$window < PARAMS$window) {
warnings <- c(warnings, sprintf("The lookback was shortened to %d values so that at least 10 windows train.", as.integer(res0$facts$window)))
}
suffix0 <- if (!is.null(SERIES)) paste0(" — ", first_key) else ""
if (LB3_PARTS) {
charts[[length(charts) + 1]] <- cs_chart("parts", "forecast-components", paste0(sprintf("Forecast of %s by part", VALUE), suffix0), list(
time = cs_col(TIME, rep(times0, length(names0)), kind = if (TEMPORAL) "temporal" else "numeric"),
value = cs_col(VALUE, parts0, kind = "numeric"),
part = cs_col("part", rep(names0, each = H), kind = "categorical", levels = names0)
))
part_cols <- lapply(seq_along(names0), function(j) list(key = sprintf("p%d", j - 1L), label = names0[j], type = "number"))
extra_tables[[length(extra_tables) + 1]] <- list(
key = "parts",
title = paste0("Forecast by part (they add up to the forecast; the first part carries the last value)", suffix0),
columns = c(list(list(key = "time", label = TIME)), part_cols),
rows = lapply(seq_len(H), function(k) {
row <- list(time = times0[[k]])
for (j in seq_along(names0)) row[[sprintf("p%d", j - 1L)]] <- res0$components[[names0[j]]][k]
row
})
)
}
# %% Checks
nw0 <- as.integer(res0$facts$n_windows)
extra_assumptions[[length(extra_assumptions) + 1]] <- list(
key = "enough_windows", label = "Enough windows to learn from", status = if (nw0 >= 100) "pass" else "warn", statistic = nw0,
detail = paste0(sprintf("%d training windows for %d weights.", nw0, as.integer(res0$facts$n_params)),
if (nw0 < 100) " That is little data for a neural network: compare it with ETS and the seasonal naive forecast on the same backtest." else "")
)
rel0 <- cs_ml_fc_naive_relative_mae(bt) # not MASE < 1: MASE scales by the in-sample one-step naive error
if (is.finite(rel0)) {
values[["bt[rel_mae]"]] <- rel0
beats0 <- rel0 < 1
extra_assumptions[[length(extra_assumptions) + 1]] <- list(
key = "beats_naive", label = "Beats the seasonal naive forecast", status = if (beats0) "pass" else "warn", statistic = rel0,
detail = paste0(sprintf("Backtest MAE is %.2f times the seasonal naive forecast's from the same origins.", rel0), if (!beats0) " Repeating the last season forecast these origins at least as well." else "")
)
}
check0 <- cs_fcm_residual_check(residuals_first, seasons[1])
if (!is.null(check0)) {
values$lb_p <- check0$p
extra_assumptions[[length(extra_assumptions) + 1]] <- cs_fcm_residual_row(check0, "The network left autocorrelation in its one-step errors: try a longer lookback, or ARIMA.", if (!is.null(SERIES)) series_keys[1])
}
# %% Result
show <- intersect(c("mae", "rmse", "mape", "smape", "mase", "wape"), names(accuracy))
tables <- list()
if (length(accuracy)) {
rows <- lapply(show, function(k) list(metric = if (k == "smape") "sMAPE" else toupper(k), value = accuracy[[k]]))
for (level in LEVELS) {
ck <- paste0("coverage_", lv(level))
if (!is.null(accuracy[[ck]])) rows[[length(rows) + 1]] <- list(metric = sprintf("Coverage of the %s%% interval", lv(level)), value = accuracy[[ck]])
}
tables[[1]] <- list(key = "accuracy", title = sprintf("Backtest accuracy (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
columns = list(list(key = "metric", label = "Metric"), list(key = "value", label = "Value", type = "number")), rows = rows)
}
fc_cols <- c(if (!is.null(SERIES)) list(list(key = "series", label = "Series")),
list(list(key = "time", label = TIME), list(key = "mean", label = "Forecast", type = "number")))
for (level in LEVELS) {
fc_cols <- c(fc_cols, list(list(key = paste0("lo_", lv(level)), label = sprintf("%s%% low", lv(level)), type = "number"),
list(key = paste0("hi_", lv(level)), label = sprintf("%s%% high", lv(level)), type = "number")))
}
tables <- c(tables, extra_tables)
keep <- setdiff(names(forecasts), c("t", "kind", if (is.null(SERIES)) "series"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Forecast", columns = fc_cols,
rows = lapply(seq_len(min(200, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
summary <- sprintf("%s: %d-step forecasts of %s (%s data, %d observations).", values$model_label, H, VALUE, freq_label, n_obs)
if (!is.null(accuracy$mae)) summary <- paste0(summary, sprintf(" Backtest MAE %s over %d origin%s.", format(signif(accuracy$mae, 3)), n_origins, if (n_origins != 1) "s" else ""))
cs_publish(list(
title = "N-HiTS neural forecast",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
n = n_obs,
summary = summary,
statistics = lapply(utils::head(show, 3), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
tables = tables,
values = values,
assumptions = extra_assumptions,
warnings = warnings,
notes = list(),
charts = charts,
artifacts = artifacts
))
N-HiTS (3 stacks, pooling 4/2/1): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 17.2 over 1 origin.
- MAE
- 17.223
- RMSE
- 20.047
- MAPE
- 0.0363
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough windows to learn from — 97 training windows for 2640 weights. That is little data for a neural network: compare it with ETS and the seasonal naive forecast on the same backtest.
- Beats the seasonal naive forecast — Backtest MAE is 0.36 times the seasonal naive forecast's from the same origins.
- Residuals look uncorrelated — Ljung–Box at 21 lags: p = 0.591.
Backtest accuracy (1 origin, horizon 12)
| Metric | Value |
|---|---|
| MAE | 17.223 |
| RMSE | 20.047 |
| MAPE | 0.0363 |
| sMAPE | 0.0370 |
| MASE | 0.5656 |
| WAPE | 0.0362 |
| Coverage of the 80% interval | 0.2500 |
| Coverage of the 95% interval | 0.6667 |
Forecast by part (they add up to the forecast; the first part carries the last value)
| month | stack 1 (pool 4, 3 knots) | stack 2 (pool 2, 6 knots) | stack 3 (pool 1, 12 knots) |
|---|---|---|---|
| 1961-01-01 | 445.62 | −2.487 | −7.287 |
| 1961-02-01 | 448.13 | 7.799 | −40.356 |
| 1961-03-01 | 450.63 | 18.085 | 0.8168 |
| 1961-04-01 | 453.14 | 21.701 | 6.174 |
| 1961-05-01 | 455.65 | 23.650 | 18.716 |
| 1961-06-01 | 458.15 | 34.659 | 82.169 |
| 1961-07-01 | 457.64 | 51.706 | 150.18 |
| 1961-08-01 | 454.10 | 57.087 | 134.87 |
| 1961-09-01 | 450.56 | 44.967 | 39.923 |
| 1961-10-01 | 447.02 | 34.628 | −18.467 |
| 1961-11-01 | 443.48 | 31.414 | −66.794 |
| 1961-12-01 | 439.94 | 28.200 | −13.030 |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1961-01-01 | 435.85 | 425.56 | 446.13 | 420.12 | 451.58 |
| 1961-02-01 | 415.57 | 406.96 | 424.18 | 402.40 | 428.74 |
| 1961-03-01 | 469.53 | 459.44 | 479.63 | 454.09 | 484.98 |
| 1961-04-01 | 481.02 | 469.48 | 492.55 | 463.37 | 498.66 |
| 1961-05-01 | 498.01 | 486.30 | 509.72 | 480.10 | 515.92 |
| 1961-06-01 | 574.98 | 562.38 | 587.58 | 555.71 | 594.25 |
| 1961-07-01 | 659.53 | 647.75 | 671.30 | 641.52 | 677.54 |
| 1961-08-01 | 646.05 | 634.19 | 657.91 | 627.91 | 664.19 |
| 1961-09-01 | 535.45 | 522.79 | 548.11 | 516.09 | 554.81 |
| 1961-10-01 | 463.18 | 450.69 | 475.67 | 444.08 | 482.27 |
| 1961-11-01 | 408.10 | 390.64 | 425.56 | 381.39 | 434.81 |
| 1961-12-01 | 455.11 | 436.91 | 473.31 | 427.27 | 482.95 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# N-HiTS neural forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.nhits 1.2.0 · spec 73790748b2a3a0c6
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.deep import nbeats # twin of codesplashr::cs_nb_fit_forecast (torch, shared initial weights)
from codesplash.ml import forecast_models as fcm
# %% Data
TIME = "month"
VALUE = "passengers"
SERIES = None
H = 12
LEVELS = [float(v) for v in [80, 95]]
SEASON = None # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 1
STEP = None # None = the horizon
OFFSETS = None # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None # None = train on all values before each origin
TRAIN_START = None # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = []
PARAMS = {
"pool_sizes": [4, 2, 1],
"downsample": [4, 2, 1],
"blocks": 1,
"layers": 2,
"width": 16,
"window": None,
"loss": "mae",
"epochs": 150,
"learning_rate": 0.005,
"batch_size": None,
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
cut = fc.parse_time(TRAIN_START, TEMPORAL)
early = np.nan_to_num(times_all, nan=np.inf) < cut
if early.any():
warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None] # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.nhits/three_stacks_monthly/out-python")
extra_tables = [] # model blocks may add result tables (e.g. automatic selection)
extra_assumptions = [] # … and assumption rows
current_series = None
X_TRAIN = None # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE = None # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[current_series] = {"resid": [...], "fitdf": k, "lags": L} from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG = {}
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/forecast.nhits/three_stacks_monthly/out-python",
)
# N-HiTS (Challu et al. 2023) on PyTorch (float64, one thread): each stack max-pools the scaled window and forecasts a
# few knots that are interpolated over the horizon, from coarse to fine time scales. R's torch trains the same network
# from the same initial weights with the same Adam steps.
FINAL = {}
LB3_PARTS = True
def min_train(m):
return H + 11 # a lookback of at least 2 and at least 10 training windows
def prepare_series(y, t, m, freq):
return None
def fit_forecast(y, t, h, m, levels, spec):
res = nbeats.fit_forecast(
y, h, m, levels,
model="nhits",
window=PARAMS["window"],
blocks=int(PARAMS["blocks"]),
layers=int(PARAMS["layers"]),
width=int(PARAMS["width"]),
pool_sizes=[int(v) for v in PARAMS["pool_sizes"]],
downsample=[int(v) for v in PARAMS["downsample"]],
loss=PARAMS["loss"],
epochs=int(PARAMS["epochs"]),
lr=PARAMS["learning_rate"],
batch_size=PARAMS["batch_size"],
seed=SEED,
)
FINAL[current_series] = (res, [float(v) for v in t])
return res
# %% Backtests and forecasts
def lv(level):
return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")
bt_rows = []
fc_rows = []
facts = {}
labels = {}
freq_label = ""
freq_alias = ""
seasons = []
n_obs = 0
n_origins = 0
filled = 0
residuals_first = None
for key in series_keys:
current_series = key # model blocks may read it (e.g. table titles)
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
t_raw, y_raw = times_all[sel], values_all[sel]
if int(np.sum(~np.isnan(y_raw))) < 3: # too few values to read the time step from
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(1) + 1, n=int(np.sum(~np.isnan(y_raw))))
x_later = None
if XREG: # rows after the last observed value carry known future regressors
x_raw = x_all[sel]
last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
later = t_raw > last_y
order_later = np.argsort(t_raw[later], kind="stable")
x_later = x_raw[later][order_later]
t_raw, y_raw, x_raw = t_raw[~later], y_raw[~later], x_raw[~later]
freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t, y, nfill = fc.regularize(t_raw, y_raw, freq)
x_grid = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq)[1] for j in range(x_raw.shape[1])]) if XREG else None
filled += nfill
freq_label = freq["label"]
freq_alias = fc.ALIASES.get(freq["unit"], "")
m = int(SEASON) if SEASON else int(freq["season"])
seasons.append(m)
y = [float(v) for v in y]
n = len(y)
n_obs += n
if n < min_train(m) + 1:
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(m) + 1, n=n)
spec = prepare_series(y, t, m, freq)
step = int(STEP) if STEP else H
if OFFSETS is not None:
origins = fc.plan_origins(n, H, [int(v) for v in OFFSETS], min_train(m))
if len(origins) < len(OFFSETS):
warnings.append(f"{len(OFFSETS) - len(origins)} of {len(OFFSETS)} backtest origins were skipped for {key or VALUE}: too few values before them.")
else:
origins = fc.backtest_origins(n, H, WINDOWS, step, min_train(m))
for o in origins:
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
if XREG:
X_TRAIN, X_FUTURE = x_grid[start:o], x_grid[o:o + H]
try:
res = fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec)
except Exception as e: # a failed origin is skipped, not fatal
warnings.append(f"Backtest from {fc.format_time(t[o - 1], TEMPORAL)} failed: {e}")
continue
n_origins += 1
scale = fc.mase_scale(y[:o], m)
scale2 = fc.rmsse_scale(y[:o], m)
lag = m if (m > 1 and o > m) else 1 # the seasonal naive forecast from this origin (MASE's lag rule)
for k in range(H):
row = {
"series": key,
"origin": fc.format_time(t[o - 1], TEMPORAL),
"time": fc.format_time(t[o + k], TEMPORAL),
"h": k + 1,
"actual": y[o + k],
"mean": float(res["mean"][k]),
"scale": scale,
"scale2": scale2,
"last": y[o - 1],
"snaive": y[o - lag + k % lag],
}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(res["lower"][level][k])
row[f"hi_{lv(level)}"] = float(res["upper"][level][k])
bt_rows.append(row)
if XREG:
X_TRAIN = x_grid
X_FUTURE = fc.future_regressors(x_grid, x_later, H)
if len(x_later) < H:
warnings.append(f"Future values of {', '.join(XREG)} are known for {len(x_later)} of {H} steps; the last known values are held for the rest.")
final = fit_forecast(y, t, H, m, LEVELS, spec)
labels[key] = final["label"]
for name, value in final["facts"].items():
facts[name if not SERIES else f"{name}[{key}]"] = value
fitted = final.get("fitted")
diag = DIAG.get(key) or {}
resid = diag.get("resid")
if residuals_first is None and resid is not None:
residuals_first = [float(v) for v in resid]
elif residuals_first is None and fitted is not None:
residuals_first = [y[i] - fitted[i] for i in range(n) if fitted[i] is not None and not math.isnan(fitted[i])]
for i in range(n):
row = {"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "actual", "mean": y[i]}
if resid is not None and i >= n - len(resid): # the last len(resid) times (differencing drops early ones)
row["resid"] = float(resid[i - (n - len(resid))])
if "fitdf" in diag:
row["lb_fitdf"] = float(diag["fitdf"])
if "lags" in diag:
row["lb_lags"] = float(diag["lags"])
fc_rows.append(row)
if fitted is not None and not math.isnan(fitted[i]):
fc_rows.append({"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "fitted", "mean": float(fitted[i])})
future = fc.future_times(t[-1], freq, H)
for k in range(H):
row = {"series": key, "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(final["mean"][k])}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(final["lower"][level][k])
row[f"hi_{lv(level)}"] = float(final["upper"][level][k])
fc_rows.append(row)
if filled:
warnings.append(f"{filled} missing time steps or values were filled by linear interpolation.")
# %% Accuracy
accuracy = fc.accuracy(bt_rows, LEVELS)
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]
top = lv(max(LEVELS)) if LEVELS else None
def wsum(xs):
return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)
values = {
"n_series": len(series_keys),
"n_obs": n_obs,
"horizon": H,
"season": seasons[0],
"n_origins": n_origins,
"filled": filled,
"fc_check": wsum([r["mean"] for r in forecasts]),
"model_label": labels[series_keys[0]] if len(series_keys) == 1 else f"{len(series_keys)} series, one model each",
"freq_label": freq_label,
"frequency": freq_alias,
}
if top:
values["fc_lo_check"] = wsum([r[f"lo_{top}"] for r in forecasts])
values["fc_hi_check"] = wsum([r[f"hi_{top}"] for r in forecasts])
for k, v in accuracy.items():
values[f"bt[{k}]"] = v
values.update(facts)
pd.DataFrame(fc_rows).to_parquet(os.path.join(out, "forecast.parquet"), index=False)
artifacts = [{"key": "forecast", "path": os.path.join(out, "forecast.parquet"), "format": "parquet"}]
if bt_rows:
pd.DataFrame(bt_rows).to_parquet(os.path.join(out, "backtest.parquet"), index=False)
artifacts.append({"key": "backtest", "path": os.path.join(out, "backtest.parquet"), "format": "parquet"})
# %% Charts
charts = []
shown = series_keys[:8]
fan = [r for r in fc_rows if r["series"] in shown and r["kind"] != "fitted"]
kind = "temporal" if TEMPORAL else "numeric"
roles = {
"time": cs.col(TIME, [r["time"] for r in fan], kind=kind),
"value": cs.col(VALUE, [r["mean"] for r in fan], kind="numeric"),
"kind": cs.col("kind", [r["kind"] for r in fan], kind="categorical", levels=["actual", "forecast"]),
}
for level in (80.0, 95.0):
if level in LEVELS:
roles[f"lo_{lv(level)}"] = cs.col(f"lo_{lv(level)}", [r.get(f"lo_{lv(level)}") for r in fan], kind="numeric")
roles[f"hi_{lv(level)}"] = cs.col(f"hi_{lv(level)}", [r.get(f"hi_{lv(level)}") for r in fan], kind="numeric")
if SERIES:
roles["series"] = cs.col(SERIES, [r["series"] for r in fan], kind="categorical", levels=shown)
charts.append(cs.chart("forecast", "forecast-fan", f"Forecast of {VALUE}", roles))
if bt_rows:
charts.append(
cs.chart(
"backtest",
"backtest-errors",
"Backtest errors by horizon",
{
"h": cs.col("horizon", [r["h"] for r in bt_rows], kind="numeric"),
"error": cs.col("error", [r["actual"] - r["mean"] for r in bt_rows], kind="numeric"),
"origin": cs.col("origin", [r["origin"] for r in bt_rows], kind="categorical"),
},
)
)
if residuals_first and len(residuals_first) > 4:
lags = min(max(2 * seasons[0], 10), len(residuals_first) - 1, 48)
r_acf = fc.acf(residuals_first, lags)
bound = 1.959963984540054 / math.sqrt(len(residuals_first))
charts.append(
cs.chart(
"acf",
"acf-plot",
"Residual autocorrelation",
{
"lag": cs.col("lag", list(range(1, lags + 1)), kind="numeric"),
"acf": cs.col("ACF", r_acf, kind="numeric"),
"bound": cs.col("bound", [bound] * lags, kind="numeric"),
},
)
)
# %% Forecast parts
res0, t0 = FINAL[series_keys[0]]
freq0 = fc.detect_frequency(np.array(t0), TEMPORAL)
times0 = [fc.format_time(v, TEMPORAL) for v in fc.future_times(t0[-1], freq0, H)]
names0 = list(res0["components"])
parts0 = [res0["components"][name][k] for name in names0 for k in range(H)]
wparts = [(j + 1.0) * (k + 1.0) for j in range(len(names0)) for k in range(H)]
values["parts_check"] = fc._sum([wparts[i] * parts0[i] for i in range(len(parts0))]) / fc._sum(wparts)
if PARAMS["window"] and int(res0["facts"]["window"]) < int(PARAMS["window"]):
warnings.append(f"The lookback was shortened to {int(res0['facts']['window'])} values so that at least 10 windows train.")
suffix0 = f" — {series_keys[0]}" if SERIES else ""
if LB3_PARTS:
charts.append(
cs.chart(
"parts",
"forecast-components",
f"Forecast of {VALUE} by part" + suffix0,
{
"time": cs.col(TIME, [times0[k] for name in names0 for k in range(H)], kind="temporal" if TEMPORAL else "numeric"),
"value": cs.col(VALUE, parts0, kind="numeric"),
"part": cs.col("part", [name for name in names0 for k in range(H)], kind="categorical", levels=names0),
},
)
)
extra_tables.append(
{
"key": "parts",
"title": "Forecast by part (they add up to the forecast; the first part carries the last value)" + suffix0,
"columns": [{"key": "time", "label": TIME}] + [{"key": f"p{j}", "label": name, "type": "number"} for j, name in enumerate(names0)],
"rows": [dict({"time": times0[k]}, **{f"p{j}": res0["components"][name][k] for j, name in enumerate(names0)}) for k in range(H)],
}
)
# %% Checks
nw0 = int(res0["facts"]["n_windows"])
extra_assumptions.append(
{
"key": "enough_windows",
"label": "Enough windows to learn from",
"status": "pass" if nw0 >= 100 else "warn",
"statistic": float(nw0),
"detail": f"{nw0} training windows for {int(res0['facts']['n_params'])} weights." + ("" if nw0 >= 100 else " That is little data for a neural network: compare it with ETS and the seasonal naive forecast on the same backtest."),
}
)
rel0 = fc.naive_relative_mae(bt_rows) # not MASE < 1: MASE scales by the in-sample one-step naive error
if math.isfinite(rel0):
values["bt[rel_mae]"] = rel0
beats0 = rel0 < 1
extra_assumptions.append(
{
"key": "beats_naive",
"label": "Beats the seasonal naive forecast",
"status": "pass" if beats0 else "warn",
"statistic": rel0,
"detail": f"Backtest MAE is {rel0:.2f} times the seasonal naive forecast's from the same origins." + ("" if beats0 else " Repeating the last season forecast these origins at least as well."),
}
)
check0 = fcm.residual_check(residuals_first, seasons[0])
if check0 is not None:
values["lb_p"] = check0["p"]
extra_assumptions.append(fcm.residual_row(check0, "The network left autocorrelation in its one-step errors: try a longer lookback, or ARIMA.", series_keys[0]))
# %% Result
show = [m for m in ("mae", "rmse", "mape", "smape", "mase", "wape") if m in accuracy]
tables = []
if accuracy:
tables.append(
{
"key": "accuracy",
"title": f"Backtest accuracy ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
"columns": [{"key": "metric", "label": "Metric"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"metric": k.upper() if k != "smape" else "sMAPE", "value": accuracy[k]} for k in show]
+ [{"metric": f"Coverage of the {lv(level)}% interval", "value": accuracy.get(f"coverage_{lv(level)}")} for level in LEVELS if f"coverage_{lv(level)}" in accuracy],
}
)
tables.extend(extra_tables)
tables.append(
{
"key": "forecast",
"title": "Forecast",
"columns": ([{"key": "series", "label": "Series"}] if SERIES else [])
+ [{"key": "time", "label": TIME}, {"key": "mean", "label": "Forecast", "type": "number"}]
+ [c for level in LEVELS for c in ({"key": f"lo_{lv(level)}", "label": f"{lv(level)}% low", "type": "number"}, {"key": f"hi_{lv(level)}", "label": f"{lv(level)}% high", "type": "number"})],
"rows": [{k: v for k, v in r.items() if k not in ("t", "kind") and (SERIES or k != "series")} for r in forecasts[:200]],
}
)
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} ({freq_label} data, {n_obs} observations)."
if "mae" in accuracy:
summary += f" Backtest MAE {accuracy['mae']:.3g} over {n_origins} origin{'s' if n_origins != 1 else ''}."
cs.publish(
{
"title": "N-HiTS neural forecast",
"engine": cs.engine_info("torch", "codesplash", "numpy", "pandas"),
"n": n_obs,
"summary": summary,
"statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in show[:3]],
"tables": tables,
"values": values,
"assumptions": extra_assumptions,
"warnings": warnings,
"notes": [],
"charts": charts,
"artifacts": artifacts,
}
)
N-HiTS (3 stacks, pooling 4/2/1) uses 2,640 weights and backtests at a MASE of 0.57. In Forecast by part, each stack's panel is one time scale. Where does the seasonal shape appear: the coarse stack, or a finer one?
A model trained on other series
PredictPredict first
A foundation modelFoundation model (forecasting)A model pretrained on many other series that forecasts a new one as it is, without training on it (zero-shot). forecasts a series it was never trained on. How?
Reveal
It reads the recent history and predicts quantiles with weights learned on many other series. Nothing is fitted to your data, which is why it runs in seconds.
Try Chronos
In the appChronosChronosAmazon's family of pretrained forecasting models; Chronos-Bolt reads the history in patches and predicts its 10%–90% quantiles. needs its weights on this computer. The method page offers the download and states its size first; nothing is fetched until you confirm.
Chronos-Bolt Tiny (zero-shot): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 28.1 over 2 origins.
- MAE
- 28.058
- RMSE
- 37.429
- MAPE
- 0.0582
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | month | passengers |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | −662,688,000,000 | 112 |
| — | — | actual | — | — | −660,009,600,000 | 118 |
| — | — | actual | — | — | −657,590,400,000 | 132 |
| — | — | actual | — | — | −654,912,000,000 | 129 |
| — | — | actual | — | — | −652,320,000,000 | 121 |
| — | — | actual | — | — | −649,641,600,000 | 135 |
| — | — | actual | — | — | −647,049,600,000 | 148 |
| — | — | actual | — | — | −644,371,200,000 | 148 |
| — | — | actual | — | — | −641,692,800,000 | 136 |
| — | — | actual | — | — | −639,100,800,000 | 119 |
| — | — | actual | — | — | −636,422,400,000 | 104 |
| — | — | actual | — | — | −633,830,400,000 | 118 |
| — | — | actual | — | — | −631,152,000,000 | 115 |
| — | — | actual | — | — | −628,473,600,000 | 126 |
| — | — | actual | — | — | −626,054,400,000 | 141 |
| — | — | actual | — | — | −623,376,000,000 | 135 |
| — | — | actual | — | — | −620,784,000,000 | 125 |
| — | — | actual | — | — | −618,105,600,000 | 149 |
| — | — | actual | — | — | −615,513,600,000 | 170 |
| — | — | actual | — | — | −612,835,200,000 | 170 |
| — | — | actual | — | — | −610,156,800,000 | 158 |
| — | — | actual | — | — | −607,564,800,000 | 133 |
| — | — | actual | — | — | −604,886,400,000 | 114 |
| — | — | actual | — | — | −602,294,400,000 | 140 |
| — | — | actual | — | — | −599,616,000,000 | 145 |
| — | — | actual | — | — | −596,937,600,000 | 150 |
| — | — | actual | — | — | −594,518,400,000 | 178 |
| — | — | actual | — | — | −591,840,000,000 | 163 |
| — | — | actual | — | — | −589,248,000,000 | 172 |
| — | — | actual | — | — | −586,569,600,000 | 178 |
| — | — | actual | — | — | −583,977,600,000 | 199 |
| — | — | actual | — | — | −581,299,200,000 | 199 |
| — | — | actual | — | — | −578,620,800,000 | 184 |
| — | — | actual | — | — | −576,028,800,000 | 162 |
| — | — | actual | — | — | −573,350,400,000 | 146 |
| — | — | actual | — | — | −570,758,400,000 | 166 |
| — | — | actual | — | — | −568,080,000,000 | 171 |
| — | — | actual | — | — | −565,401,600,000 | 180 |
| — | — | actual | — | — | −562,896,000,000 | 193 |
| — | — | actual | — | — | −560,217,600,000 | 181 |
| — | — | actual | — | — | −557,625,600,000 | 183 |
| — | — | actual | — | — | −554,947,200,000 | 218 |
| — | — | actual | — | — | −552,355,200,000 | 230 |
| — | — | actual | — | — | −549,676,800,000 | 242 |
| — | — | actual | — | — | −546,998,400,000 | 209 |
| — | — | actual | — | — | −544,406,400,000 | 191 |
| — | — | actual | — | — | −541,728,000,000 | 172 |
| — | — | actual | — | — | −539,136,000,000 | 194 |
| — | — | actual | — | — | −536,457,600,000 | 196 |
| — | — | actual | — | — | −533,779,200,000 | 196 |
| — | — | actual | — | — | −531,360,000,000 | 236 |
| — | — | actual | — | — | −528,681,600,000 | 235 |
| — | — | actual | — | — | −526,089,600,000 | 229 |
| — | — | actual | — | — | −523,411,200,000 | 243 |
| — | — | actual | — | — | −520,819,200,000 | 264 |
| — | — | actual | — | — | −518,140,800,000 | 272 |
| — | — | actual | — | — | −515,462,400,000 | 237 |
| — | — | actual | — | — | −512,870,400,000 | 211 |
| — | — | actual | — | — | −510,192,000,000 | 180 |
| — | — | actual | — | — | −507,600,000,000 | 201 |
First 60 of 156 rows.
View data
| error | horizon | origin |
|---|---|---|
| 1.382 | 1 | 1958-12-01 |
| −28.974 | 2 | 1958-12-01 |
| 23.417 | 3 | 1958-12-01 |
| 5.815 | 4 | 1958-12-01 |
| 15.075 | 5 | 1958-12-01 |
| 31.007 | 6 | 1958-12-01 |
| 76.172 | 7 | 1958-12-01 |
| 85.563 | 8 | 1958-12-01 |
| 18.147 | 9 | 1958-12-01 |
| 26.884 | 10 | 1958-12-01 |
| 0.1960 | 11 | 1958-12-01 |
| 35.543 | 12 | 1958-12-01 |
| −4.135 | 1 | 1959-12-01 |
| −39.437 | 2 | 1959-12-01 |
| −20.612 | 3 | 1959-12-01 |
| 14.798 | 4 | 1959-12-01 |
| 9.992 | 5 | 1959-12-01 |
| 31.673 | 6 | 1959-12-01 |
| 81.930 | 7 | 1959-12-01 |
| 64.000 | 8 | 1959-12-01 |
| 2.102 | 9 | 1959-12-01 |
| 24.712 | 10 | 1959-12-01 |
| −28.604 | 11 | 1959-12-01 |
| 3.217 | 12 | 1959-12-01 |
View data
| quantile | month | passengers |
|---|---|---|
| — | −378,691,200,000 | 340 |
| — | −376,012,800,000 | 318 |
| — | −373,593,600,000 | 362 |
| — | −370,915,200,000 | 348 |
| — | −368,323,200,000 | 363 |
| — | −365,644,800,000 | 435 |
| — | −363,052,800,000 | 491 |
| — | −360,374,400,000 | 505 |
| — | −357,696,000,000 | 404 |
| — | −355,104,000,000 | 359 |
| — | −352,425,600,000 | 310 |
| — | −349,833,600,000 | 337 |
| — | −347,155,200,000 | 360 |
| — | −344,476,800,000 | 342 |
| — | −342,057,600,000 | 406 |
| — | −339,379,200,000 | 396 |
| — | −336,787,200,000 | 420 |
| — | −334,108,800,000 | 472 |
| — | −331,516,800,000 | 548 |
| — | −328,838,400,000 | 559 |
| — | −326,160,000,000 | 463 |
| — | −323,568,000,000 | 407 |
| — | −320,889,600,000 | 362 |
| — | −318,297,600,000 | 405 |
| — | −315,619,200,000 | 417 |
| — | −312,940,800,000 | 391 |
| — | −310,435,200,000 | 419 |
| — | −307,756,800,000 | 461 |
| — | −305,164,800,000 | 472 |
| — | −302,486,400,000 | 535 |
| — | −299,894,400,000 | 622 |
| — | −297,216,000,000 | 606 |
| — | −294,537,600,000 | 508 |
| — | −291,945,600,000 | 461 |
| — | −289,267,200,000 | 390 |
| — | −286,675,200,000 | 432 |
| 0.1000 | −283,996,800,000 | 426.96 |
| 0.1000 | −281,318,400,000 | 437.42 |
| 0.1000 | −278,899,200,000 | 447.06 |
| 0.1000 | −276,220,800,000 | 454.99 |
| 0.1000 | −273,628,800,000 | 474.54 |
| 0.1000 | −270,950,400,000 | 515.18 |
| 0.1000 | −268,358,400,000 | 551.34 |
| 0.1000 | −265,680,000,000 | 553.89 |
| 0.1000 | −263,001,600,000 | 509.52 |
| 0.1000 | −260,409,600,000 | 432.81 |
| 0.1000 | −257,731,200,000 | 412.51 |
| 0.1000 | −255,139,200,000 | 422.11 |
| 0.2000 | −283,996,800,000 | 436.34 |
| 0.2000 | −281,318,400,000 | 447.77 |
| 0.2000 | −278,899,200,000 | 458.70 |
| 0.2000 | −276,220,800,000 | 468.34 |
| 0.2000 | −273,628,800,000 | 487.90 |
| 0.2000 | −270,950,400,000 | 530.07 |
| 0.2000 | −268,358,400,000 | 569.17 |
| 0.2000 | −265,680,000,000 | 573.56 |
| 0.2000 | −263,001,600,000 | 528.67 |
| 0.2000 | −260,409,600,000 | 447.17 |
| 0.2000 | −257,731,200,000 | 428.01 |
| 0.2000 | −255,139,200,000 | 439.52 |
First 60 of 144 rows.
Assumptions
- Horizon within the model's training — Horizon 12; Chronos-Bolt predicts up to 64 steps at once.
- Enough history for the model — The model read 144 values.
- Beats the seasonal naive forecast — Backtest MAE is 0.59 times the seasonal naive forecast's from the same origins.
Backtest accuracy (2 origins, horizon 12)
| Metric | Value |
|---|---|
| MAE | 28.058 |
| RMSE | 37.429 |
| MAPE | 0.0582 |
| sMAPE | 0.0599 |
| MASE | 0.9527 |
| WAPE | 0.0620 |
| Coverage of the 80% interval | 0.7500 |
| Coverage of the 95% interval | 0.8750 |
The model's quantiles (the 50% quantile is the forecast)
| month | 10% | 20% | 30% | 40% | 50% | 60% | 70% | 80% | 90% |
|---|---|---|---|---|---|---|---|---|---|
| 1961-01-01 | 426.96 | 436.34 | 443.24 | 449.75 | 456.54 | 463.19 | 470.40 | 478.39 | 490.93 |
| 1961-02-01 | 437.42 | 447.77 | 455.59 | 462.43 | 469.48 | 476.56 | 483.67 | 492.25 | 504.40 |
| 1961-03-01 | 447.06 | 458.70 | 467.69 | 474.88 | 483.33 | 491.30 | 499.66 | 508.56 | 521.03 |
| 1961-04-01 | 454.99 | 468.34 | 477.58 | 485.73 | 493.49 | 502.31 | 510.19 | 519.77 | 531.07 |
| 1961-05-01 | 474.54 | 487.90 | 496.81 | 504.17 | 511.93 | 519.80 | 528.40 | 537.22 | 549.30 |
| 1961-06-01 | 515.18 | 530.07 | 540.73 | 549.17 | 558.58 | 568.29 | 578.01 | 589.19 | 604.29 |
| 1961-07-01 | 551.34 | 569.17 | 581.38 | 591.50 | 602.37 | 613.18 | 624.62 | 636.84 | 654.22 |
| 1961-08-01 | 553.89 | 573.56 | 586.38 | 597.55 | 609.33 | 620.58 | 632.28 | 644.47 | 662.18 |
| 1961-09-01 | 509.52 | 528.67 | 541.69 | 552.80 | 563.82 | 575.09 | 586.64 | 599.81 | 616.24 |
| 1961-10-01 | 432.81 | 447.17 | 458.14 | 467.39 | 477.71 | 488.21 | 498.13 | 509.09 | 526.68 |
| 1961-11-01 | 412.51 | 428.01 | 439.79 | 449.19 | 458.74 | 468.49 | 477.87 | 488.31 | 502.88 |
| 1961-12-01 | 422.11 | 439.52 | 451.29 | 461.58 | 471.21 | 480.47 | 490.32 | 501.73 | 519.74 |
Pretrained weights
| Item | Value |
|---|---|
| Model | Chronos-Bolt Tiny (9M parameters) |
| Source | huggingface.co/amazon/chronos-bolt-tiny |
| Revision | a0e552de83495b5c28c14c71c374f3e33280b340 |
| License | Apache-2.0 |
| Download size | 34.6 MB |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1961-01-01 | 456.54 | 426.96 | 490.93 | 411.30 | 509.14 |
| 1961-02-01 | 469.48 | 437.42 | 504.40 | 420.44 | 522.88 |
| 1961-03-01 | 483.33 | 447.06 | 521.03 | 427.87 | 540.99 |
| 1961-04-01 | 493.49 | 454.99 | 531.07 | 434.61 | 550.97 |
| 1961-05-01 | 511.93 | 474.54 | 549.30 | 454.75 | 569.08 |
| 1961-06-01 | 558.58 | 515.18 | 604.29 | 492.21 | 628.48 |
| 1961-07-01 | 602.37 | 551.34 | 654.22 | 524.33 | 681.67 |
| 1961-08-01 | 609.33 | 553.89 | 662.18 | 524.54 | 690.16 |
| 1961-09-01 | 563.82 | 509.52 | 616.24 | 480.78 | 643.99 |
| 1961-10-01 | 477.71 | 432.81 | 526.68 | 409.03 | 552.59 |
| 1961-11-01 | 458.74 | 412.51 | 502.88 | 388.04 | 526.25 |
| 1961-12-01 | 471.21 | 422.11 | 519.74 | 396.11 | 545.43 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Chronos zero-shot forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.chronos 1.1.1 · spec 202261816b326ed3
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.deep import chronos as cbolt # pretrained weights, looked up locally only (never downloaded here)
# %% Data
TIME = "month"
VALUE = "passengers"
SERIES = None
H = 12
LEVELS = [float(v) for v in [80, 95]]
SEASON = None # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 2
STEP = None # None = the horizon
OFFSETS = None # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None # None = train on all values before each origin
TRAIN_START = None # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = []
PARAMS = {
"model": "bolt_tiny",
"context": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
cut = fc.parse_time(TRAIN_START, TEMPORAL)
early = np.nan_to_num(times_all, nan=np.inf) < cut
if early.any():
warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None] # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.chronos/tiny_monthly/out-python")
extra_tables = [] # model blocks may add result tables (e.g. automatic selection)
extra_assumptions = [] # … and assumption rows
current_series = None
X_TRAIN = None # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE = None # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[current_series] = {"resid": [...], "fitdf": k, "lags": L} from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG = {}
# %% Model
# Chronos-Bolt (Ansari et al. 2024) is pretrained: it reads the recent history and predicts quantiles of the next
# steps without training on this series. Python only — the weights run through the chronos-forecasting package.
# The weights must already be on this computer (the app downloads them only after you confirm the size).
FINAL = {}
WEIGHTS = cbolt.locate(PARAMS["model"]) # stops with CS_WEIGHTS_MISSING and the download size when absent
def min_train(m):
return 8
def prepare_series(y, t, m, freq):
return None
def fit_forecast(y, t, h, m, levels, spec):
res = cbolt.fit_forecast(y, h, m, levels, model=PARAMS["model"], context=PARAMS["context"])
FINAL[current_series] = (res, [float(v) for v in t])
return res
# %% Backtests and forecasts
def lv(level):
return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")
bt_rows = []
fc_rows = []
facts = {}
labels = {}
freq_label = ""
freq_alias = ""
seasons = []
n_obs = 0
n_origins = 0
filled = 0
residuals_first = None
for key in series_keys:
current_series = key # model blocks may read it (e.g. table titles)
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
t_raw, y_raw = times_all[sel], values_all[sel]
if int(np.sum(~np.isnan(y_raw))) < 3: # too few values to read the time step from
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(1) + 1, n=int(np.sum(~np.isnan(y_raw))))
x_later = None
if XREG: # rows after the last observed value carry known future regressors
x_raw = x_all[sel]
last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
later = t_raw > last_y
order_later = np.argsort(t_raw[later], kind="stable")
x_later = x_raw[later][order_later]
t_raw, y_raw, x_raw = t_raw[~later], y_raw[~later], x_raw[~later]
freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t, y, nfill = fc.regularize(t_raw, y_raw, freq)
x_grid = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq)[1] for j in range(x_raw.shape[1])]) if XREG else None
filled += nfill
freq_label = freq["label"]
freq_alias = fc.ALIASES.get(freq["unit"], "")
m = int(SEASON) if SEASON else int(freq["season"])
seasons.append(m)
y = [float(v) for v in y]
n = len(y)
n_obs += n
if n < min_train(m) + 1:
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(m) + 1, n=n)
spec = prepare_series(y, t, m, freq)
step = int(STEP) if STEP else H
if OFFSETS is not None:
origins = fc.plan_origins(n, H, [int(v) for v in OFFSETS], min_train(m))
if len(origins) < len(OFFSETS):
warnings.append(f"{len(OFFSETS) - len(origins)} of {len(OFFSETS)} backtest origins were skipped for {key or VALUE}: too few values before them.")
else:
origins = fc.backtest_origins(n, H, WINDOWS, step, min_train(m))
for o in origins:
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
if XREG:
X_TRAIN, X_FUTURE = x_grid[start:o], x_grid[o:o + H]
try:
res = fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec)
except Exception as e: # a failed origin is skipped, not fatal
warnings.append(f"Backtest from {fc.format_time(t[o - 1], TEMPORAL)} failed: {e}")
continue
n_origins += 1
scale = fc.mase_scale(y[:o], m)
scale2 = fc.rmsse_scale(y[:o], m)
lag = m if (m > 1 and o > m) else 1 # the seasonal naive forecast from this origin (MASE's lag rule)
for k in range(H):
row = {
"series": key,
"origin": fc.format_time(t[o - 1], TEMPORAL),
"time": fc.format_time(t[o + k], TEMPORAL),
"h": k + 1,
"actual": y[o + k],
"mean": float(res["mean"][k]),
"scale": scale,
"scale2": scale2,
"last": y[o - 1],
"snaive": y[o - lag + k % lag],
}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(res["lower"][level][k])
row[f"hi_{lv(level)}"] = float(res["upper"][level][k])
bt_rows.append(row)
if XREG:
X_TRAIN = x_grid
X_FUTURE = fc.future_regressors(x_grid, x_later, H)
if len(x_later) < H:
warnings.append(f"Future values of {', '.join(XREG)} are known for {len(x_later)} of {H} steps; the last known values are held for the rest.")
final = fit_forecast(y, t, H, m, LEVELS, spec)
labels[key] = final["label"]
for name, value in final["facts"].items():
facts[name if not SERIES else f"{name}[{key}]"] = value
fitted = final.get("fitted")
diag = DIAG.get(key) or {}
resid = diag.get("resid")
if residuals_first is None and resid is not None:
residuals_first = [float(v) for v in resid]
elif residuals_first is None and fitted is not None:
residuals_first = [y[i] - fitted[i] for i in range(n) if fitted[i] is not None and not math.isnan(fitted[i])]
for i in range(n):
row = {"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "actual", "mean": y[i]}
if resid is not None and i >= n - len(resid): # the last len(resid) times (differencing drops early ones)
row["resid"] = float(resid[i - (n - len(resid))])
if "fitdf" in diag:
row["lb_fitdf"] = float(diag["fitdf"])
if "lags" in diag:
row["lb_lags"] = float(diag["lags"])
fc_rows.append(row)
if fitted is not None and not math.isnan(fitted[i]):
fc_rows.append({"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "fitted", "mean": float(fitted[i])})
future = fc.future_times(t[-1], freq, H)
for k in range(H):
row = {"series": key, "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(final["mean"][k])}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(final["lower"][level][k])
row[f"hi_{lv(level)}"] = float(final["upper"][level][k])
fc_rows.append(row)
if filled:
warnings.append(f"{filled} missing time steps or values were filled by linear interpolation.")
# %% Accuracy
accuracy = fc.accuracy(bt_rows, LEVELS)
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]
top = lv(max(LEVELS)) if LEVELS else None
def wsum(xs):
return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)
values = {
"n_series": len(series_keys),
"n_obs": n_obs,
"horizon": H,
"season": seasons[0],
"n_origins": n_origins,
"filled": filled,
"fc_check": wsum([r["mean"] for r in forecasts]),
"model_label": labels[series_keys[0]] if len(series_keys) == 1 else f"{len(series_keys)} series, one model each",
"freq_label": freq_label,
"frequency": freq_alias,
}
if top:
values["fc_lo_check"] = wsum([r[f"lo_{top}"] for r in forecasts])
values["fc_hi_check"] = wsum([r[f"hi_{top}"] for r in forecasts])
for k, v in accuracy.items():
values[f"bt[{k}]"] = v
values.update(facts)
pd.DataFrame(fc_rows).to_parquet(os.path.join(out, "forecast.parquet"), index=False)
artifacts = [{"key": "forecast", "path": os.path.join(out, "forecast.parquet"), "format": "parquet"}]
if bt_rows:
pd.DataFrame(bt_rows).to_parquet(os.path.join(out, "backtest.parquet"), index=False)
artifacts.append({"key": "backtest", "path": os.path.join(out, "backtest.parquet"), "format": "parquet"})
# %% Charts
charts = []
shown = series_keys[:8]
fan = [r for r in fc_rows if r["series"] in shown and r["kind"] != "fitted"]
kind = "temporal" if TEMPORAL else "numeric"
roles = {
"time": cs.col(TIME, [r["time"] for r in fan], kind=kind),
"value": cs.col(VALUE, [r["mean"] for r in fan], kind="numeric"),
"kind": cs.col("kind", [r["kind"] for r in fan], kind="categorical", levels=["actual", "forecast"]),
}
for level in (80.0, 95.0):
if level in LEVELS:
roles[f"lo_{lv(level)}"] = cs.col(f"lo_{lv(level)}", [r.get(f"lo_{lv(level)}") for r in fan], kind="numeric")
roles[f"hi_{lv(level)}"] = cs.col(f"hi_{lv(level)}", [r.get(f"hi_{lv(level)}") for r in fan], kind="numeric")
if SERIES:
roles["series"] = cs.col(SERIES, [r["series"] for r in fan], kind="categorical", levels=shown)
charts.append(cs.chart("forecast", "forecast-fan", f"Forecast of {VALUE}", roles))
if bt_rows:
charts.append(
cs.chart(
"backtest",
"backtest-errors",
"Backtest errors by horizon",
{
"h": cs.col("horizon", [r["h"] for r in bt_rows], kind="numeric"),
"error": cs.col("error", [r["actual"] - r["mean"] for r in bt_rows], kind="numeric"),
"origin": cs.col("origin", [r["origin"] for r in bt_rows], kind="categorical"),
},
)
)
if residuals_first and len(residuals_first) > 4:
lags = min(max(2 * seasons[0], 10), len(residuals_first) - 1, 48)
r_acf = fc.acf(residuals_first, lags)
bound = 1.959963984540054 / math.sqrt(len(residuals_first))
charts.append(
cs.chart(
"acf",
"acf-plot",
"Residual autocorrelation",
{
"lag": cs.col("lag", list(range(1, lags + 1)), kind="numeric"),
"acf": cs.col("ACF", r_acf, kind="numeric"),
"bound": cs.col("bound", [bound] * lags, kind="numeric"),
},
)
)
# %% Quantiles and checks
res0, t0 = FINAL[series_keys[0]]
spec0 = cbolt.MODELS[PARAMS["model"]]
freq0 = fc.detect_frequency(np.array(t0), TEMPORAL)
times0 = [fc.format_time(v, TEMPORAL) for v in fc.future_times(t0[-1], freq0, H)]
lq0, q0 = res0["quantile_levels"], res0["quantiles"]
wq = [(j + 1.0) * (k + 1.0) for j in range(len(lq0)) for k in range(H)]
values["q_check"] = fc._sum([wq[j * H + k] * float(q0[j, k]) for j in range(len(lq0)) for k in range(H)]) / fc._sum(wq)
values["weights_label"] = spec0["label"]
suffix0 = f" — {series_keys[0]}" if SERIES else ""
hist0 = min(len(t0), max(3 * H, 24))
y0 = [r["mean"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
th0 = [r["time"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
charts.append(
cs.chart(
"quantiles",
"quantile-fan",
f"Chronos quantiles for {VALUE}" + suffix0,
{
"time": cs.col(TIME, th0 + [times0[k] for j in range(len(lq0)) for k in range(H)], kind="temporal" if TEMPORAL else "numeric"),
"value": cs.col(VALUE, y0 + [float(q0[j, k]) for j in range(len(lq0)) for k in range(H)], kind="numeric"),
"quantile": cs.col("quantile", [None] * len(y0) + [lq0[j] for j in range(len(lq0)) for k in range(H)], kind="numeric"),
},
)
)
extra_tables.append(
{
"key": "quantiles",
"title": "The model's quantiles (the 50% quantile is the forecast)" + suffix0,
"columns": [{"key": "time", "label": TIME}] + [{"key": f"q{int(round(p * 100))}", "label": f"{int(round(p * 100))}%", "type": "number"} for p in lq0],
"rows": [dict({"time": times0[k]}, **{f"q{int(round(p * 100))}": float(q0[j, k]) for j, p in enumerate(lq0)}) for k in range(H)],
}
)
extra_tables.append(
{
"key": "weights",
"title": "Pretrained weights",
"columns": [{"key": "item", "label": "Item"}, {"key": "value", "label": "Value"}],
"rows": [
{"item": "Model", "value": f"{spec0['label']} ({spec0['params']} parameters)"},
{"item": "Source", "value": f"huggingface.co/{spec0['repo']}"},
{"item": "Revision", "value": spec0["revision"]},
{"item": "License", "value": "Apache-2.0"},
{"item": "Download size", "value": cbolt.size_text(spec0["bytes"])},
],
}
)
extra_assumptions.append(
{
"key": "horizon_trained",
"label": "Horizon within the model's training",
"status": "pass" if H <= cbolt.TRAINED_HORIZON else "warn",
"statistic": float(H),
"detail": f"Horizon {H}; Chronos-Bolt predicts up to {cbolt.TRAINED_HORIZON} steps at once." + ("" if H <= cbolt.TRAINED_HORIZON else " Later steps feed the model's own forecasts back, so they can drift."),
}
)
ctx0 = int(res0["facts"]["context"])
extra_assumptions.append(
{
"key": "context_length",
"label": "Enough history for the model",
"status": "pass" if ctx0 >= 64 else "warn",
"statistic": float(ctx0),
"detail": f"The model read {ctx0} values." + ("" if ctx0 >= 64 else " Fewer than 64 (four patches of 16) leaves little pattern to recognize."),
}
)
rel0 = fc.naive_relative_mae(bt_rows) # not MASE < 1: MASE scales by the in-sample one-step naive error
if math.isfinite(rel0):
values["bt[rel_mae]"] = rel0
beats0 = rel0 < 1
extra_assumptions.append(
{
"key": "beats_naive",
"label": "Beats the seasonal naive forecast",
"status": "pass" if beats0 else "warn",
"statistic": rel0,
"detail": f"Backtest MAE is {rel0:.2f} times the seasonal naive forecast's from the same origins." + ("" if beats0 else " Repeating the last season forecast these origins at least as well."),
}
)
if H > cbolt.TRAINED_HORIZON:
warnings.append(f"Chronos-Bolt was trained for up to {cbolt.TRAINED_HORIZON} steps; steps beyond that are rolled forward from its own forecasts.")
# %% Result
show = [m for m in ("mae", "rmse", "mape", "smape", "mase", "wape") if m in accuracy]
tables = []
if accuracy:
tables.append(
{
"key": "accuracy",
"title": f"Backtest accuracy ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
"columns": [{"key": "metric", "label": "Metric"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"metric": k.upper() if k != "smape" else "sMAPE", "value": accuracy[k]} for k in show]
+ [{"metric": f"Coverage of the {lv(level)}% interval", "value": accuracy.get(f"coverage_{lv(level)}")} for level in LEVELS if f"coverage_{lv(level)}" in accuracy],
}
)
tables.extend(extra_tables)
tables.append(
{
"key": "forecast",
"title": "Forecast",
"columns": ([{"key": "series", "label": "Series"}] if SERIES else [])
+ [{"key": "time", "label": TIME}, {"key": "mean", "label": "Forecast", "type": "number"}]
+ [c for level in LEVELS for c in ({"key": f"lo_{lv(level)}", "label": f"{lv(level)}% low", "type": "number"}, {"key": f"hi_{lv(level)}", "label": f"{lv(level)}% high", "type": "number"})],
"rows": [{k: v for k, v in r.items() if k not in ("t", "kind") and (SERIES or k != "series")} for r in forecasts[:200]],
}
)
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} ({freq_label} data, {n_obs} observations)."
if "mae" in accuracy:
summary += f" Backtest MAE {accuracy['mae']:.3g} over {n_origins} origin{'s' if n_origins != 1 else ''}."
cs.publish(
{
"title": "Chronos zero-shot forecast",
"engine": cs.engine_info("chronos-forecasting", "torch", "numpy", "pandas"),
"n": n_obs,
"summary": summary,
"statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in show[:3]],
"tables": tables,
"values": values,
"assumptions": extra_assumptions,
"warnings": warnings,
"notes": [],
"charts": charts,
"artifacts": artifacts,
}
)
Chronos-Bolt Tiny (zero-shot) read 144 values. Its backtest MASE is 0.95, and 75% of actual values fell inside its 80% intervals.
Reading the quantile fan
ReflectOpen Quantile fan. The widest band runs from the 10% to the 90% quantile. Narrower bands sit inside it, around the median.
On the Nile series with a short context, Chronos read only 48 values, and its check on history length warns. What would you compare it with before using that forecast?
Compare them all on one backtest
In the appRun these in a forecast experiment beside the baselines, so every model is scored on the same origins.
If a neural model and ETS score within noise of each other, which would you keep, and why?
Check: neural forecasters
CheckpointCheck yourself
What does the next N-BEATS block read?
Show the answer
Answer: a
Each block passes on what it couldn't explain, so later blocks model what is left.
Check yourself
In Forecast by part, how do the parts relate to the forecast?
Show the answer
Answer: a
Doubly residual stacking sums the blocks' forecasts. The first part carries the level, the others are deviations.
Check yourself
When do an N-BEATS forecast's parts mean "trend" and "season"?
Show the answer
Answer: a
Generic blocks learn their own bases, so their parts carry no fixed meaning.
Check yourself
An N-HiTS stack has a knot spacing of 4 and a horizon of 12. How many values does that stack forecast directly?
Show the answer
Answer: a
It predicts ⌈12 ÷ 4⌉ knots and interpolates between them, which keeps that stack smooth.
Check yourself
A network's 80% intervals cover 42% of actual values in the backtest. What does that tell you?
Show the answer
Answer: a
Coverage judges the intervals separately from point accuracy. These come from in-sample errors, which a flexible network keeps small.
Check: pretrained models
CheckpointCheck yourself
What does Chronos learn from your series before it forecasts?
Show the answer
Answer: a
That's what zero-shot means. It's fast, and it knows only what the history shows.
Check yourself
When does the app download Chronos weights?
Show the answer
Answer: a
The method page states the model, its source, license and size, and waits for you to confirm.
Check yourself
Why does Chronos run in Python only?
Show the answer
Answer: a
N-BEATS and N-HiTS run in both engines from the same initial weights; Chronos is a pretrained checkpoint for one package.
In code
Read# pip install chronos-forecasting
import torch
from chronos import BaseChronosPipeline
pipe = BaseChronosPipeline.from_pretrained("amazon/chronos-bolt-tiny", device_map="cpu")
context = torch.tensor(y, dtype=torch.float32)
quantiles, median = pipe.predict_quantiles(context, prediction_length=12, quantile_levels=[0.1, 0.5, 0.9])# N-BEATS in R through the app's helper (torch for R); Chronos has no R package.
library(codesplashr)
fc <- cs_nb_fit_forecast(y, h = 12, m = 12, levels = c(80, 95), model = "nbeats",
architecture = "interpretable", width = 64, epochs = 300)
fc$meanRecap
Recap- N-BEATS forecasts the horizon at once from a chain of blocks, and its interpretable form shows trend and season.
- N-HiTS adds pooled inputs and interpolated knots, from coarse to fine.
- Chronos forecasts without training, and the app downloads its weights only after you confirm the size.
- Judge every one on the same backtest as the baselines, and check interval coverage on its own.
Concepts in this lesson