Gaussian processes meet networks: deep kernels and deep GPs
A deep kernel lets a network learn the features a GP compares; a deep GP stacks GPs into layers. What each adds to a plain GP, how a learned feature map can fake confidence, and why a better marginal likelihood isn't a better model.
What runs in CodeSplash
- UNC006Deep kernel learning with Gaussian processes Runs in CodeSplash
- UNC008Deep Gaussian process (DGP) Explained here
- Gaussian process Verified in Python and R
You will be able to
- Write a deep kernel and the GP marginal likelihood it is trained on
- Explain feature collapse and why it makes far-apart inputs look close and certain
- Compare a deep kernel with a plain GP on held-out scores, not on marginal likelihood
- Describe a deep GP's layers and why averaging hidden means loses uncertainty
What a kernel decides
ReadA Gaussian process predicts a new row from rows that its kernel calls similar, and its uncertainty grows as the new row moves away from them. Everything rides on the kernel's notion of distance. An RBF kernel on raw columns says "similar means close in every column, scaled by a lengthscale".
When that notion is wrong, say only a combination of columns matters, or the data live on a curve, the GP is both less accurate and wrongly confident. Two ideas change the notion of distance with a network: learn the features (deep kernels) or stack GPs (deep GPs).
Deep kernel learning
ReadA deep kernelDeep kernelA Gaussian process kernel that compares rows on features a small network learns, trained with the kernel on the marginal likelihood. applies a base kernel to learned features: . The network weights , the kernel's settings and the noise are trained together by maximizing the marginal likelihoodLog marginal likelihoodHow probable the training targets are under the kernel, with the function averaged out; kernel settings maximize it.
The predictive variance is the GP's, now in feature space. Add for a new observation.
A better likelihood, a better model?
PredictPredict first
On ozone, a deep kernel reaches a much higher log marginal likelihood than an RBF kernel with one lengthscale per column. Will it predict new days better?
Reveal
Not necessarily. The deep kernel's marginal likelihood was −52.6 against −81.1, yet its cross-validated RMSE was 20.8 against 20.5. A flexible feature map can fit the training rows' covariance closely; only held-out scores tell you whether that generalizes.
Gaussian process: cross-validated RMSE 20.831 ± 4.311 over 3 folds; RMSE on the locked test set 21.065 (n = 23).
- CV RMSE
- 20.831
- SD across folds
- 4.311
- Test RMSE
- 21.065
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 31 | 23.044 | 15.701 | 0.6744 | 0.4226 |
| 2 | 1 | 31 | 15.863 | 11.495 | 0.6759 | 0.6239 |
| 3 | 1 | 31 | 23.586 | 17.453 | 0.5126 | 0.4806 |
Kernel settings of the final model
| Setting | Value | Scale |
|---|---|---|
| Signal SD (σ) | 104.73 | target |
| Hidden units | 8 | network |
| Learned features | 2 | network |
| Training epochs | 400 | network |
| Noise SD (σₙ) | 13.274 | target |
- The deep kernel was still improving at its last epoch; more epochs may fit better.
The exact R script · R R version 4.5.1 (2025-06-13)
# Gaussian process
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.gp 1.1.0 · spec 475f99f52f94be22
# Dataset: ml_airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data and split plan
TARGET <- "Ozone"
FEATURES <- c("solar radiation", "Wind", "Temp")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
kernel = "deep",
ard = FALSE,
optimize = TRUE,
lengthscale = NULL,
signal_sd = 1,
noise_sd = 0.3,
rq_alpha = 1,
max_rows = 1000,
deep_units = 8,
deep_dims = 2,
deep_epochs = 400,
deep_lr = 0.005
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airquality.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.gp/regression_deep_kernel/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
`solar radiation` = "numeric",
Wind = "numeric",
Temp = "numeric"
),
levels = list(
),
impute = "median",
scale = "standard",
indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
run$predictive <- TRUE
out <- cs_ml_out_dir("target/academy-parity/run-8142/learn.gp/regression_deep_kernel/out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
yy <- y[rows + 1L]
ww <- sample_weights(rows)
if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
if (fold_id == 0) resampled <<- r$info
r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)
# %% Model
# Gaussian process: kernel settings by type-II maximum likelihood (the same projected BFGS in Python and R),
# regression in closed form on a standardized target, binary by the Laplace approximation. A deep kernel trains a
# small network (Wichmann–Hill initial weights from the seed) jointly with the kernel by full-batch Adam.
fit_model <- function(X, y, w) {
cs_ml_gp_fit(X, y, w, TASK, PARAMS$kernel, isTRUE(PARAMS$ard), isTRUE(PARAMS$optimize), PARAMS$lengthscale,
PARAMS$signal_sd, PARAMS$noise_sd, PARAMS$rq_alpha, as.integer(PARAMS$max_rows),
deep_units = as.integer(PARAMS$deep_units), deep_dims = as.integer(PARAMS$deep_dims), seed = SEED,
deep_epochs = as.integer(PARAMS$deep_epochs), deep_lr = as.numeric(PARAMS$deep_lr))
}
predict_model <- function(model, X) cs_ml_gp_predict(model, X)$mean
predict_sd <- function(model, X) cs_ml_gp_predict(model, X)$sd
feature_importance <- function(model, names) {
for (note in cs_ml_gp_notes(model)) { # the final model's row cap and convergence
if (!(note %in% unlist(warnings))) warnings[[length(warnings) + 1L]] <<- note
}
cs_ml_gp_importance(model, names)
}
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path)
list(list(key = "model", path = path, format = "rds"))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# Predictive mean and SD for `rows`.
held_out <- function(model, prep, fit_rows, rows) {
X <- cs_ml_design_apply(prep, rows_of(rows))
list(mean = predict_model(model, X), sd = predict_sd(model, X))
}
# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
fold <- folds[[i]]
prep <- cs_ml_design_fit(design, rows_of(fold$train))
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
held_out(model, prep, fold$train, fold$valid))
cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")
# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
if (!is.null(resampled)) {
warnings <- c(warnings, as.list(resampled$notes))
notes <- c(notes, list(cs_ml_resample_describe(resampled)))
}
if (length(plan$test)) {
cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
held_out(model, prep, plan$train, plan$test))
}
importance <- feature_importance(model, names_)
artifacts[[length(artifacts) + 1L]] <- list(
key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
)
artifacts <- c(artifacts, save_model(model, out))
cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)
# %% Result
cs_publish(cs_ml_gp_extend(cs_ml_result(
run,
title = "Gaussian process",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n_features = length(names_),
n_train = length(plan$train),
n_test = length(plan$test),
params = PARAMS,
features = names_,
importance = importance,
artifacts = artifacts,
warnings = warnings,
notes = notes
), model, names_))
Gaussian process: cross-validated RMSE 20.831 ± 4.311 over 3 folds; RMSE on the locked test set 21.065 (n = 23).
- CV RMSE
- 20.831
- SD across folds
- 4.311
- Test RMSE
- 21.065
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 31 | 23.044 | 15.701 | 0.6744 | 0.4226 |
| 2 | 1 | 31 | 15.863 | 11.495 | 0.6759 | 0.6239 |
| 3 | 1 | 31 | 23.586 | 17.453 | 0.5126 | 0.4806 |
Kernel settings of the final model
| Setting | Value | Scale |
|---|---|---|
| Signal SD (σ) | 104.73 | target |
| Hidden units | 8 | network |
| Learned features | 2 | network |
| Training epochs | 400 | network |
| Noise SD (σₙ) | 13.274 | target |
- The deep kernel was still improving at its last epoch; more epochs may fit better.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Gaussian process
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.gp 1.1.0 · spec 475f99f52f94be22
# Dataset: ml_airquality (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import gp as csgp
# %% Data and split plan
TARGET = "Ozone"
FEATURES = ["solar radiation", "Wind", "Temp"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
"kernel": "deep",
"ard": False,
"optimize": True,
"lengthscale": None,
"signal_sd": 1,
"noise_sd": 0.3,
"rq_alpha": 1,
"max_rows": 1000,
"deep_units": 8,
"deep_dims": 2,
"deep_epochs": 400,
"deep_lr": 0.005,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airquality.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.gp/regression_deep_kernel/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"solar radiation": "numeric",
"Wind": "numeric",
"Temp": "numeric",
},
levels={
},
impute="median",
scale="standard",
indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
run.predictive = True
out = csml.out_dir("target/academy-parity/run-8142/learn.gp/regression_deep_kernel/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
# Gaussian process: kernel settings by type-II maximum likelihood (the same projected BFGS in Python and R),
# regression in closed form on a standardized target, binary by the Laplace approximation. A deep kernel trains a
# small network (Wichmann–Hill initial weights from the seed) jointly with the kernel by full-batch Adam.
def fit_model(X, y, w):
return csgp.fit(
X, y, w, TASK, PARAMS["kernel"], bool(PARAMS["ard"]), bool(PARAMS["optimize"]), PARAMS["lengthscale"],
PARAMS["signal_sd"], PARAMS["noise_sd"], PARAMS["rq_alpha"], int(PARAMS["max_rows"]),
deep_units=int(PARAMS["deep_units"]), deep_dims=int(PARAMS["deep_dims"]), seed=SEED,
deep_epochs=int(PARAMS["deep_epochs"]), deep_lr=float(PARAMS["deep_lr"]),
)
def predict_model(model, X):
return csgp.predict(model, X)[0]
def predict_sd(model, X):
return csgp.predict(model, X)[1]
def feature_importance(model, names):
for note in csgp.notes(model): # the final model's row cap and convergence
if note not in warnings:
warnings.append(note)
return csgp.importance(model, names)
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path)
return [{"key": "model", "path": path, "format": "joblib"}]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
def held_out(model, prep, fit_rows, rows):
"""Predictive mean and SD for `rows`."""
X = prep.transform(df.iloc[rows])
return predict_model(model, X), predict_sd(model, X)
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, held_out(model, prep, fold.train, fold.valid))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, held_out(model, prep, plan.train, plan.test))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
csgp.extend_result(run.result(
title="Gaussian process",
engine=cs.engine_info("scipy", "codesplash", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
), model, names)
)
Feature collapse
ReadThe network can learn to map very different inputs to nearby features. Then the GP sees them as neighbors and reports low uncertainty for an input unlike anything in training: the opposite of what you wanted a GP for.
Checks: look at learned distances between known-different rows, at posterior variance in gaps and beyond the training range, and compare with a plain GP and a plain network on proper scores and interval coverage. Remember that the GP's uncertainty is conditional on the point-estimated network weights; it doesn't include their uncertainty.
Deep Gaussian processes
ReadA deep GP composes GPs: with . Each layer warps the input for the next, so the composition can model changing smoothness and non-Gaussian outputs. It's fit with sparse variational inference: inducing points per layer and an ELBO that sums expected log likelihood minus each layer's KL term.
Two cautions. Passing only each layer's mean to the next drops the uncertainty that made it a deep GP; samples must flow through the layers. And depth isn't free: start with one GP and add layers only if validation improves.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| Deep kernel learning (UNC006) | Runs as an option of Gaussian process: Kernel Deep kernel (learned features) |
| Deep GP (UNC008) | Explained here |
The reference's deep-GP program draws one function from a two-layer prior; it shows the architecture, not a fitted model.
Reference · UNC008 · Explained hereDeep Gaussian process (DGP)Compose Gaussian-process mappings to represent nonlinear hierarchical uncertainty. Intermediate representations are random variables, distinguishing a DGP from a GP attached to a point-estimated neural feature…Check your understanding
CheckpointCheck yourself
What does a deep kernel learn that an RBF kernel on raw columns doesn't?
Show the answer
Answer: a
: the network decides what "similar" means.
Check yourself
A deep-kernel GP is confident on an input far outside the training data. What's a likely cause?
Show the answer
Answer: b
A GP is uncertain far from its data in feature space. If the features squash distances, that protection disappears.
Check yourself
How should you choose between a deep kernel and a plain GP?
Show the answer
Answer: b
The marginal likelihood is computed on the training rows and rewards a flexible feature map. Held-out data decide.
Check yourself
What is a deep Gaussian process?
Show the answer
Answer: b
Composition lets the model warp its inputs, giving changing smoothness and non-Gaussian outputs.
Check yourself
An implementation passes only each hidden layer's mean to the next layer. What's lost?
Show the answer
Answer: a
Samples must propagate through the layers, keeping their dependencies, for the predictive uncertainty to be right.
Check yourself
When should you add a layer to a GP model?
Show the answer
Answer: b
Depth adds approximation error and optimization difficulty. Track predictive NLL and coverage, not depth.
Do it on your own data
In the appIn Predict, train a Gaussian process with an RBF kernel and one lengthscale per feature, then the same split with Deep kernel (learned features). Compare cross-validated scores and interval coverage, not the marginal likelihood.
Concepts in this lesson