Frontier: trees versus deep learning and tabular foundation models
Examine the open question of why GBDTs still dominate typical tabular data and what is changing. Analyze benchmarks and inductive biases identified by Grinsztajn et al., the evolution of tabular networks, tabular foundation models using in-context learning after synthetic pretraining (TabPFN), and distributional boosting (NGBoost). Learn to read these papers critically and reproduce comparisons locally.
After this lesson you can
- Explain tree-favoring tabular inductive biases (irregular functions, uninformative features and lack of rotation invariance).
- Critically evaluate a tabular benchmark: dataset selection, tuning budget, metrics and aggregation.
- Describe how a prior-fitted network learns to approximate the posterior predictive in context from synthetic data.
- Use TabPFN locally and compare it with a tuned GBDT on small datasets, discussing size and cost limits.
- Explain distributional boosting with natural gradients and produce probabilistic predictions.
Before you start
- 11XGBoost, LightGBM and CatBoost comparedGBDT hyperparameter tuningProper scoring rulesNested cross-validationRandom forestRandom search
- 15Multilayer perceptronEpochs and shuffling
- 06Stochastic gradient descent
- 18Self-attentionEncoder-decoder transformer
- 05Fisher informationPosterior predictive distribution
Motivation: the open question of tabular data
Deep networks swept away previous methods in vision, audio and text within a few years. This has not happened for tabular data in spreadsheets or SQL tables (one row per customer, transaction, connection or asset; heterogeneous columns such as amounts, ages, codes, counts and ratios). More than a decade after AlexNet, a well-tuned GBDT (XGBoost, LightGBM, CatBoost) remains the default for credit risk, fraud, intrusion detection or quantitative signals on market features. Careful studies continue finding trees win or tie on medium-sized tabular data.
This raises three questions addressed using literature and runnable experiments:
- Is it true? What reference comparative studies measure, their protocols and what they cannot conclude.
- Why? Which tabular-data properties favor trees. Grinsztajn, Oyallon and Varoquaux (2022) identified three, each with an ablation experiment; you will reproduce them on a controlled synthetic problem.
- What is changing? Tabular networks have improved (well-regularized MLPs, ResNet, FT-Transformer, numerical embeddings), but the deeper change is tabular foundation models, transformers pretrained on millions of synthetic datasets that predict a new table in one forward pass without fitting parameters. Meanwhile boosting gained the ability to predict full distributions rather than just means (NGBoost).
By the end you can critically read these papers (tuning budget, dataset selection, aggregation, inference cost) and reproduce a local comparison with uncertainty-qualified conclusions.
Evidence: what comparative studies say
Three studies shape the debate. Read them for what they measure, not headlines.
Shwartz-Ziv and Armon (2022), “Tabular data: Deep learning is not all you need”. They compared four then-recent tabular networks (TabNet, NODE, DNF-Net and a 1D CNN) with XGBoost on 11 datasets: 9 from the TabNet, DNF-Net and NODE papers (3 each), plus 2 Kaggle datasets absent from all. All models received 1000 Bayesian optimization (HyperOpt) steps per dataset. Two observations matter: each network was best only on datasets from its own paper, and XGBoost beat networks across datasets and achieved good performance with far fewer tuning iterations. The best result was an ensemble of networks and XGBoost. The first observation is methodological: methods evaluated on data chosen by their authors tend to look better than they are.
Grinsztajn, Oyallon and Varoquaux (2022), “Why do tree-based models still outperform deep learning on tabular data?”. This highly cited study carefully controls protocol. It builds a 45-dataset benchmark using explicit criteria (heterogeneous columns, real iid data, at least 3000 rows and 4 features, ratio , nondeterministic and “not too easy”: remove datasets where linear or logistic regression is within 5% relative of default ResNet and HistGradientBoosting), limiting training to 10 000 rows in the medium regime (50 000 large). Each model receives random search of about 400 configurations per dataset, starting with defaults; roughly 20 000 compute hours total. To avoid search-order dependence, evaluate 15 random orders and show best test result after iterations versus . Conclusion: on medium data trees (XGBoost, Random Forest, GBT) remain state of the art against MLP, ResNet, FT-Transformer and SAINT, even ignoring lower cost.
McElfresh et al. (2023), “When do neural nets outperform boosted trees on tabular data?”. The broadest study then: 19 algorithms on 176 datasets. It nuances the debate: on surprisingly many datasets GBDT–network differences are negligible, or tuning the GBDT a little matters more than choosing networks versus trees. GBDTs also handle skewed and heavy-tailed features and other irregularities far better. A new actor appears: TabPFN, limited to 3000 training examples (larger datasets subsampled for it), was best on average. The authors published TabZilla, a selection of 36 hardest datasets.
What they measure and do not. All three measure prediction error on small or medium public datasets with clean columns and no temporal shift. They do not measure factors dominating many industrial decisions: hundreds of millions of rows, training-to-production drift, inference latency, maintenance cost or interpretability. Conclusions depend on protocol: datasets, tuning budgets and aggregation. We return to critical reading below. A more recent snapshot is TabArena (Erickson et al., 2025), a living benchmark updated with new models: GBDTs remain strong on practical data, deep learning catches up with larger time budgets and configuration ensembles, foundation models lead on small datasets, and validation and ensembles strongly affect each model’s results.
Three inductive biases
Why trees? Grinsztajn et al.’s answer is that their inductive bias (functions preferred when data do not decide) fits typical tabular data better. Define the subject:
Each bias has an ablation: transform data to remove or exaggerate the property and measure change in model gap. If the property explains tree advantage, removing it should reduce that advantage.
Irregular functions
Grinsztajn et al. replace training target with a Gaussian-kernel-smoothed version whose covariance is empirical data covariance times squared length scale ( means unsmoothed). To make smoothing meaningful, first normalize features and retain the top 5 by Random Forest importance. Then train on smoothed target and measure test accuracy. At small scales smoothing greatly reduces tree accuracy and barely affects networks. Interpretation: the real target contains irregularities trees capture and networks do not; removing them removes tree advantage without hurting networks that never learned them.
You can see this when truth is known. The figure uses target
on : a smooth part, corner plateau, horizontal step and narrow strip. Train on 3000 noisy examples , first replacing each with Nadaraya–Watson smoothing at , and measure test RMSE against .
At GBDT RMSE is and MLP : 29% more error, explained by the map. MLP blurs plateau, step and strip edges (width ); GBDT reproduces them with few splits. At , about mean nearest-neighbor distance among 3000 points (), smoothing barely touches irregularities and advantage persists (). It then drops rapidly: at , at , at and under from . Both errors rise from smoothing bias, but GBDT rises more because it loses its distinguishing structure. Measuring error against the smoothed target each model sees, MLP wins from ( versus ): smooth-function preference is no longer a drawback.
Where does that preference come from? Both architecture and training. A smooth-activation network is a smooth input function, and even piecewise-linear ReLU requires large weights for jumps that gradient descent takes time to reach: networks first learn low-frequency target components, known as spectral bias (Rahaman et al., 2019). A tree represents a step of any height with one split.
Uninformative features
Grinsztajn et al.’s second experiment orders features by Random Forest importance and removes them least to most important. GBT accuracy barely changes after removing up to half; a GBT trained only on removed features has very low accuracy: most columns are uninformative, not redundant. Removing them narrows the ResNet (MLP-like) gap to other models; adding target-independent Gaussian columns widens it. Their conclusion: MLPs are less robust to uninformative features.
The reason is geometric. A tree chooses the best split feature at each node: noise enters only if it improves a split by chance and its effect dilutes. An MLP mixes every input in its first layer and must learn to zero noise columns; finite data prevent perfect success, each useless column adding variance. This is the curse of dimensionality for a model without feature selection.
Rotations and meaningful axes
The third experiment applies the same random rotation (orthogonal matrix determinant 1) to all training and test rows. Information is unchanged: is invertible and a model could undo it. But trees collapse while ResNets do not change; after rotation networks lead. Why does an MLP not notice?
Proof
Define map . Since , and rotated-data loss satisfies ; also . Differentiate with respect to : since is linear in with acting as , the chain rule gives , i.e., , and gradients with respect to and match. Thus step becomes : the rotated-data step from reaches . Momentum is a linear combination of past gradients and commutes with similarly. By induction ; apply the first identity. For the second part, if each row of is , the corresponding row of is .
∎Two nuances. First, invariance is of the distribution of outcomes, not each run: with a fixed seed, rotated data train a different but equally probable network. Second, the optimizer must commute with rotations: Adam normalizes each coordinate by its own scale and does not, so an Adam MLP is only approximately invariant in practice (below, its error barely changes). Per-feature embedding architectures such as FT-Transformer deliberately break invariance: each column has its own transformation.
Why is rotation invariance bad? It treats all directions equally, while tabular directions differ: “age” means something, “0.3·age − 0.7·amount” does not. Ng (2004) proved that for any rotation-invariant algorithm, problems with very few relevant features exist where required sample count grows at least linearly with irrelevant feature count in the worst case, while -penalized logistic regression (not invariant) needs only logarithmic growth. The second and third biases are the same problem from two sides.
With aligned corner the tree describes it with two splits and three leaves. Rotated, each slanted edge needs a staircase of axis-aligned splits: at it needs 8 leaves for 95%, and with 6 reaches 94%. It can approximate arbitrarily well, but each extra step is estimated with fewer data and maximum accuracy with 400 examples falls. MLP gives the same accuracy at all angles (99.4%). Its map rounds the corner even unrotated, illustrating the first bias again.
The next cell checks the theorem numerically on the figure problem: train one gradient-descent MLP on originals and another on data rotated from rotated initialization, comparing predictions. Then train a six-leaf scikit-learn DecisionTreeClassifier at several angles.
import numpy as np
from sklearn.tree import DecisionTreeClassifier
def mlp_gd(X, y, W1, b1, w2, b2, pasos=400, eta=0.5):
"""MLP 2-H-1 con tanh entrenado por descenso por gradiente de lote completo sobre la entropía cruzada."""
W1, b1, w2, b2 = W1.copy(), b1.copy(), w2.copy(), float(b2)
n = len(y)
for _ in range(pasos):
H = np.tanh(X @ W1.T + b1) # (n, H): la entrada solo entra a través de W1 x
p = 1 / (1 + np.exp(-(H @ w2 + b2)))
d = (p - y) / n
dH = np.outer(d, w2) * (1 - H ** 2)
W1 -= eta * dH.T @ X; b1 -= eta * dH.sum(0)
w2 -= eta * H.T @ d; b2 -= eta * d.sum()
return lambda Z: 1 / (1 + np.exp(-(np.tanh(Z @ W1.T + b1) @ w2 + b2)))
r = np.random.default_rng(0)
def disco(n):
X = r.uniform(-1, 1, (3 * n, 2))
return X[(X ** 2).sum(1) <= 1][:n]
X, Xt = disco(300), disco(2000)
esquina = lambda Z: ((Z[:, 0] > -0.25) & (Z[:, 1] > -0.1)).astype(float)
y, yt = esquina(X), esquina(Xt)
H = 16
W1, b1, w2 = r.normal(size=(H, 2)), np.zeros(H), r.normal(size=H) / 4
th = np.deg2rad(30)
Q = np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]])
f = mlp_gd(X, y, W1, b1, w2, 0.0) # datos originales
g = mlp_gd(X @ Q.T, y, W1 @ Q.T, b1, w2, 0.0) # datos rotados, inicialización rotada
print("max |f(x) − g(Qx)| en prueba:", np.abs(f(Xt) - g(Xt @ Q.T)).max())
print(f"exactitud del MLP: original {np.mean((f(Xt) > 0.5) == yt):.3f} rotado {np.mean((g(Xt @ Q.T) > 0.5) == yt):.3f}")
for grados in [0, 15, 30, 45]:
t = np.deg2rad(grados)
R = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])
a = DecisionTreeClassifier(max_leaf_nodes=6, random_state=0).fit(X @ R.T, y).score(Xt @ R.T, yt)
print(f"árbol de 6 hojas, datos rotados {grados:2d}°: exactitud {a:.3f}")The networks match to rounding error (maximum difference on the order of ) and have identical accuracy . The six-leaf tree falls from unrotated to , and at , and . Unrotated it beats MLP; rotated it loses. Angle changes no information, only how closely the boundary matches what each model represents with few parameters.
Three ablations on a synthetic problem
The next cell reproduces the three ablations on target above, with three seeds. It runs locally in minutes on CPU (scikit-learn), supplying the first figure’s numbers.
import json, time, warnings
import numpy as np
from scipy.stats import special_ortho_group
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
warnings.filterwarnings("ignore")
def f(X):
"""Objetivo 2D con saltos: escalón en x1, meseta en una esquina, franja estrecha y una parte suave."""
x1, x2 = X[:, 0], X[:, 1]
return (0.5 * np.sin(2 * np.pi * x1) + 2.0 * ((x1 > 0.55) & (x2 > 0.3)) - 1.5 * (x2 > 0.75)
+ 1.0 * (np.abs(x1 - 0.25) < 0.05))
def datos(n, semilla, ruido=0.1):
r = np.random.default_rng(semilla)
X = r.uniform(0, 1, (n, 2))
return X, f(X) + ruido * r.normal(size=n)
def suavizar(Xa, ya, Xq, ell):
"""Suavizador de núcleo gaussiano (Nadaraya-Watson) de anchura ell, evaluado en Xq."""
if ell == 0:
return ya.copy()
out = np.empty(len(Xq))
for s in range(0, len(Xq), 1000):
d2 = ((Xq[s:s + 1000, None, :] - Xa[None, :, :]) ** 2).sum(-1)
K = np.exp(-0.5 * d2 / ell ** 2)
out[s:s + 1000] = K @ ya / K.sum(1)
return out
def gbdt(semilla):
return HistGradientBoostingRegressor(max_iter=1000, learning_rate=0.1, max_leaf_nodes=31, early_stopping=True,
validation_fraction=0.15, n_iter_no_change=30, random_state=semilla)
def mlp(semilla):
return make_pipeline(StandardScaler(), MLPRegressor(hidden_layer_sizes=(256, 256), alpha=1e-4, learning_rate_init=1e-3,
max_iter=400, early_stopping=True, validation_fraction=0.15,
n_iter_no_change=30, random_state=semilla))
rmse = lambda a, b: float(np.sqrt(np.mean((a - b) ** 2)))
N, NT, SEMILLAS = 3000, 5000, [0, 1, 2]
ELLS = [0.0, 0.01, 0.02, 0.03, 0.05, 0.075, 0.1, 0.15]
G = 32
gx = (np.arange(G) + 0.5) / G
XG = np.array([[a, b] for b in gx for a in gx]) # fila b (x2), columna a (x1)
t0 = time.time()
# --- 1. Suavizar el objetivo de entrenamiento -------------------------------------------------------
res = {m: np.zeros((len(SEMILLAS), len(ELLS), 2)) for m in ("gbdt", "mlp")} # [.., 0] frente a f, [.., 1] frente a f suavizada
rejillas = {"target": [], "gbdt": [], "mlp": []}
for si, s in enumerate(SEMILLAS):
Xa, ya = datos(N, s)
Xt = np.random.default_rng(100 + s).uniform(0, 1, (NT, 2))
ft = f(Xt)
for k, ell in enumerate(ELLS):
ys = suavizar(Xa, ya, Xa, ell) # los modelos solo ven el objetivo suavizado
fts = suavizar(Xa, ya, Xt, ell) if ell > 0 else ft # el objetivo suavizado en los puntos de prueba
for m, ctor in (("gbdt", gbdt), ("mlp", mlp)):
mod = ctor(s).fit(Xa, ys)
p = mod.predict(Xt)
res[m][si, k] = rmse(p, ft), rmse(p, fts)
if s == 0:
rejillas[m].append(np.round(mod.predict(XG), 3).tolist())
if s == 0:
rejillas["target"].append(np.round(suavizar(Xa, ya, XG, ell) if ell > 0 else f(XG), 3).tolist())
print(f"1) Suavizado del objetivo: RMSE de prueba frente a f original (media de {len(SEMILLAS)} semillas)")
print(" ell GBDT MLP ventaja GBDT | frente al objetivo suavizado: GBDT MLP")
for k, ell in enumerate(ELLS):
g, m_ = res["gbdt"][:, k, 0].mean(), res["mlp"][:, k, 0].mean()
print(f" {ell:5.3f} {g:6.3f} {m_:6.3f} {m_ - g:+7.3f} | "
f"{res['gbdt'][:, k, 1].mean():6.3f} {res['mlp'][:, k, 1].mean():6.3f}")
json.dump({"ells": ELLS, "grid": G, "seeds": SEMILLAS,
"rmse": {m: np.round(res[m], 4).tolist() for m in res}, "grids": rejillas},
open("irregular.json", "w", encoding="utf-8"))
# --- 2. Variables no informativas -----------------------------------------------------------------------
print("\n2) Variables no informativas añadidas (gaussianas independientes de y), RMSE frente a f, ell = 0")
for k_ruido in [0, 4, 16, 64]:
fila = []
for s in SEMILLAS:
r = np.random.default_rng(200 + s)
Xa, ya = datos(N, s)
Xt = np.random.default_rng(100 + s).uniform(0, 1, (NT, 2))
Za = np.hstack([Xa, r.normal(size=(N, k_ruido))])
Zt = np.hstack([Xt, r.normal(size=(NT, k_ruido))])
fila.append([rmse(gbdt(s).fit(Za, ya).predict(Zt), f(Xt)), rmse(mlp(s).fit(Za, ya).predict(Zt), f(Xt))])
g, m_ = np.mean(fila, 0)
print(f" {k_ruido:3d} variables de ruido: GBDT {g:.3f} MLP {m_:.3f}")
# --- 3. Rotación aleatoria de la entrada ------------------------------------------------------------------
print("\n3) Rotación aleatoria de [x1, x2, 6 variables de ruido] (la misma rotación en entrenamiento y prueba)")
for rot in (False, True):
fila = []
for s in SEMILLAS:
r = np.random.default_rng(300 + s)
Xa, ya = datos(N, s)
Xt = np.random.default_rng(100 + s).uniform(0, 1, (NT, 2))
Za = np.hstack([(Xa - 0.5) / 0.2887, r.normal(size=(N, 6))]) # todas las columnas con varianza 1
Zt = np.hstack([(Xt - 0.5) / 0.2887, r.normal(size=(NT, 6))])
if rot:
Q = special_ortho_group.rvs(8, random_state=s)
Za, Zt = Za @ Q.T, Zt @ Q.T
fila.append([rmse(gbdt(s).fit(Za, ya).predict(Zt), f(Xt)), rmse(mlp(s).fit(Za, ya).predict(Zt), f(Xt))])
g, m_ = np.mean(fila, 0)
print(f" {'rotados ' if rot else 'originales'} GBDT {g:.3f} MLP {m_:.3f}")
print(f"\n({time.time() - t0:.0f} s)")npm run lab and open the connection link.The ablations confirm all three biases, with larger effects than real data because the problem isolates them:
- Smoothing: GBDT advantage falls from RMSE unsmoothed to below at , as in the figure.
- Uninformative features: with 0, 4, 16 and 64 noise columns, GBDT gives , , and ; MLP , , and . The tree barely notices; with 3000 examples MLP struggles.
- Rotation: with and 6 noise columns, GBDT changes to upon rotation and MLP to . Ranking reverses as in the paper, while Adam-trained MLP is practically invariant: difference is within seed variation.
The rotation MLP already starts poorly ( versus without noise): the six uninformative columns. Thus feature selection (the previous lesson) helps networks much more than GBDTs in practice.
Tabular networks: what works
The deep-learning community has answered those biases in three ways.
Truly regularize a simple MLP. Kadra et al. (2021) searched per dataset for the best combination of a 13-technique regularization cocktail (weight decay, dropout, batch normalization, residual connections, data augmentation) and hyperparameters. Across 40 datasets these well-tuned MLPs beat specialized tabular architectures and XGBoost. As with GBDTs: a poorly tuned baseline is not a baseline.
Simple, well-evaluated architectures. Gorishniy et al. (2021) compared major families on 11 datasets with the same tuning protocol (Optuna, 15 seeds per configuration), proposing two baselines. A tabular ResNet: residual blocks add to the result of sequential BatchNorm, linear layer, ReLU, dropout, another linear layer and dropout; a strong baseline often absent previously. FT-Transformer uses a feature tokenizer converting each column to a vector, for numeric (lookup plus bias for categoricals), stacks vectors with a token and applies transformer layers, so self-attention models column interactions; prediction comes from final representation. FT-Transformer was the best network on most tasks, but no universally superior GBDT or network existed.
Numeric feature embeddings. Tokenizer is linear in and cannot represent a threshold jump. Gorishniy, Rubachev and Babenko (2022) studied nonlinear scalar embeddings. Piecewise-linear encoding divides into bins (quantiles or tree splits) and encodes as a vector whose component is 1 if , 0 if and within-bin fraction ; periodic activations use with learned frequencies . Even MLPs then match attention architectures and approach GBDTs on tree-favorable benchmarks. Bin encoding resembles a tree representation (a threshold per component), addressing irregular functions; per-column embeddings break rotation invariance.
The pattern: successful tabular networks reintroduce tree inductive biases in one way or another.
Prior-fitted networks: learning Bayesian inference
The radical alternative learns how to learn from any dataset rather than learning better from one. Recall ideal Bayesian inference: given a data-generating model with latent parameter or mechanism and prior , the best statement about a new point’s label after seeing is the posterior predictive
Computing it is usually intractable: the posterior over under a rich prior (neural networks, causal graphs) has no closed form. But sampling from the generative model is easy: sample , then dataset and test point . Müller et al. (2022) propose using these samples to train a network taking and and predicting .
Why does this loss lead to posterior prediction? It is a proper scoring rule averaged over the prior.
Proof
Condition on . Under the joint distribution the conditional law of given is by definition posterior predictive , matching the formula above when ‘s distribution does not depend on (as in the toy cell’s prior, where ). If is discrete,
adding and subtracting (if is continuous, similarly with densities, integrals and finite differential entropy). Take expectation over for the identity. Gibbs’ inequality gives with equality exactly when distributions match, characterizing the minimum.
∎Three consequences. First, the network does not memorize datasets; it learns an amortized inference algorithm (amortized inference): Bayesian inference cost is paid once during pretraining, making later predictions cheap. Second, PFN is Bayesian relative to its prior. If real data resemble prior-generated data it inherits posterior-predictive virtues (well-calibrated uncertainty with few data, hypothesis averaging); otherwise there is no guarantee. Third, since input is a set, architecture must be invariant to training-example order.
The next cell checks the theorem in the smallest known-predictive case: coins with bias , whose predictive after heads in tosses is Laplace’s rule . The “transformer” here is a table with one logit per possible context , trained by SGD on cross-entropy of prior-generated queries.
import numpy as np
r = np.random.default_rng(0)
N_MAX = 10
logit = np.zeros((N_MAX + 1, N_MAX + 1)) # el "modelo": un logit por cada contexto posible (n, k)
for paso in range(1500):
th = r.uniform(size=4096) # 1. datasets del prior: theta ~ Beta(1, 1) = U(0, 1)
n = r.integers(0, N_MAX + 1, size=4096) # 2. tamaño del contexto
k = r.binomial(n, th) # las n tiradas de entrenamiento (basta con su suma k)
yq = (r.uniform(size=4096) < th).astype(float) # 3. una tirada de consulta del mismo dataset
p = 1 / (1 + np.exp(-logit[n, k]))
g = np.zeros_like(logit); c = np.zeros_like(logit)
np.add.at(g, (n, k), p - yq); np.add.at(c, (n, k), 1)
logit -= 4.0 / np.sqrt(paso + 1) * g / np.maximum(c, 1) # 4. SGD sobre la entropía cruzada media
q = 1 / (1 + np.exp(-logit))
print(" n k red (k+1)/(n+2)")
for n, k in [(0, 0), (1, 1), (3, 0), (5, 4), (10, 7), (10, 10)]:
print(f"{n:2d} {k:3d} {q[n, k]:.3f} {(k + 1) / (n + 2):.3f}")
casillas = [(n, k) for n in range(N_MAX + 1) for k in range(n + 1)]
print("error máximo en las 66 casillas:", round(max(abs(q[n, k] - (k + 1) / (n + 2)) for n, k in casillas), 3))The table was never told about beta distributions or Laplace’s rule: it saw only prior-generated tosses. Yet each cell converges to , with maximum error of a few hundredths from SGD noise in rarely visited cells. With it predicts , and with tails in tosses predicts rather than zero: Bayesian uncertainty emerges because it minimizes loss.
Architecture: a transformer over sets
Moving from a table to continuous features needs a variable-size-set network. Müller et al. use a transformer (encoder–decoder architecture, without positional encoding) where each training example is a token containing and , each query a token with alone. Attention mask controls visibility: training tokens attend each other, queries attend training but not one another. Query prediction is independent of other batched queries; without positional encoding it is invariant to training-example permutations. Each query outputs a distribution over (softmax for classification, discretized for regression).
The cost is quadratic: attention among training examples costs per layer, dominant once reaches thousands.
A toy PFN
The next cell trains a full PFN on your GPU in minutes. The prior is two-dimensional classification: , logit a Gaussian process with kernel and log-uniform scale in (each synthetic dataset has its own ), and . A four-layer transformer with and four heads (76 225 parameters) trains for 30 000 steps on batches of 128 datasets with 1–50 training examples and 50 queries. Evaluate on new prior datasets against four alternatives:
- a GP classifier with Laplace approximation and probit predictive approximation, using each dataset’s true (partial oracle: exact predictive averages over ) and fixed ;
- default scikit-learn GBDT (100 depth-3 trees) and a cautious one (30 depth-2 trees);
- context base rate with Laplace rule and, as lower bound, an oracle knowing and predicting .
import time, math, json, base64
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.ensemble import GradientBoostingClassifier
PASOS = 30000 # unos 5 minutos en una GPU de consumo
dev = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(0)
print("dispositivo:", dev, "| pasos:", PASOS)
# --- El prior: clasificación 2D con un logit que es un proceso gaussiano -------------------------------
SF, SB = 3.0, 1.0 # desviación típica del logit (parte RBF) y del sesgo constante
L_MIN, L_MAX = 0.2, 1.5 # escala de longitud ~ log-uniforme en [L_MIN, L_MAX]
def kernel(A, B, ell):
"""k(x, x') = SF² exp(−|x − x'|² / (2 ell²)) + SB², por lotes. A: (b, n, 2), B: (b, m, 2), ell: (b,)."""
d2 = ((A[:, :, None, :] - B[:, None, :, :]) ** 2).sum(-1)
return SF ** 2 * torch.exp(-0.5 * d2 / ell[:, None, None] ** 2) + SB ** 2
def muestrear_prior(b, n, g=None):
"""b datasets de n puntos: x ~ U[−1, 1]², f ~ GP(0, k) con su propia ell, y ~ Bernoulli(sigmoide(f))."""
x = torch.rand(b, n, 2, device=dev, generator=g) * 2 - 1
ell = torch.exp(math.log(L_MIN) + torch.rand(b, device=dev, generator=g) * math.log(L_MAX / L_MIN))
K = kernel(x, x, ell) + 1e-4 * torch.eye(n, device=dev)
f = (torch.linalg.cholesky(K) @ torch.randn(b, n, 1, device=dev, generator=g)).squeeze(-1)
y = (torch.rand(b, n, device=dev, generator=g) < torch.sigmoid(f)).float()
return x, y, f, ell
# --- El PFN: un transformer sobre conjuntos; las consultas solo atienden al contexto -------------------
class Capa(nn.Module):
def __init__(self, d, h, dff):
super().__init__()
self.h = h
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.qkv, self.o = nn.Linear(d, 3 * d), nn.Linear(d, d)
self.ff1, self.ff2 = nn.Linear(d, dff), nn.Linear(dff, d)
def forward(self, z, n_ctx):
B, N, d = z.shape
q, k, v = self.qkv(self.ln1(z)).split(d, dim=-1)
q, k, v = (t.view(B, N, self.h, d // self.h).transpose(1, 2) for t in (q, k, v))
k, v = k[:, :, :n_ctx], v[:, :, :n_ctx] # claves y valores: solo los puntos de entrenamiento
a = F.scaled_dot_product_attention(q, k, v)
z = z + self.o(a.transpose(1, 2).reshape(B, N, d))
return z + self.ff2(F.gelu(self.ff1(self.ln2(z))))
class PFN(nn.Module):
def __init__(self, d=48, h=4, capas=4, dff=96):
super().__init__()
self.ex, self.ey = nn.Linear(2, d), nn.Embedding(2, d)
self.capas = nn.ModuleList([Capa(d, h, dff) for _ in range(capas)])
self.lnf, self.sal = nn.LayerNorm(d), nn.Linear(d, 1)
def forward(self, xc, yc, xq):
"""xc: (B, n, 2), yc: (B, n) en {0, 1}, xq: (B, m, 2) -> logits (B, m) de Pr(y = 1 | x, contexto)."""
z = torch.cat([self.ex(xc) + self.ey(yc.long()), self.ex(xq)], dim=1)
for c in self.capas:
z = c(z, xc.shape[1])
return self.sal(self.lnf(z[:, xc.shape[1]:])).squeeze(-1)
modelo = PFN().to(dev)
print("parámetros:", sum(p.numel() for p in modelo.parameters()))
opt = torch.optim.AdamW(modelo.parameters(), lr=3e-4, weight_decay=0.0)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda t: min(1, (t + 1) / 500) * 0.5 * (1 + math.cos(math.pi * min(t, PASOS) / PASOS)))
M, LOTE = 50, 128
t0, media = time.time(), []
for paso in range(PASOS):
n = int(torch.randint(1, 51, (1,))) # tamaño del contexto, igual en todo el lote
x, y, _, _ = muestrear_prior(LOTE, n + M)
logit = modelo(x[:, :n], y[:, :n], x[:, n:])
perdida = F.binary_cross_entropy_with_logits(logit, y[:, n:]) # NLL de la predictiva: la pérdida del PFN
opt.zero_grad(set_to_none=True)
perdida.backward()
torch.nn.utils.clip_grad_norm_(modelo.parameters(), 1.0)
opt.step(); sched.step()
media.append(perdida.item())
if (paso + 1) % (PASOS // 6) == 0:
print(f"paso {paso + 1:6d} NLL media de los últimos {PASOS // 6} lotes {np.mean(media):.4f}", flush=True)
media = []
print(f"entrenamiento: {time.time() - t0:.0f} s")
# --- Evaluación en datasets nuevos del prior: PFN frente a un GP (Laplace), un GBDT y el oráculo -------------
def gp_laplace(X, y, Xq, ell, iters=30):
"""Clasificación con GP y aproximación de Laplace (Rasmussen y Williams, alg. 3.1 y 3.2), predictiva probit."""
k = lambda A, B: SF ** 2 * np.exp(-0.5 * ((A[:, None] - B[None]) ** 2).sum(-1) / ell ** 2) + SB ** 2
K = k(X, X) + 1e-6 * np.eye(len(X))
fh = np.zeros(len(X))
for _ in range(iters): # Newton sobre log p(y|f) + log p(f)
p = 1 / (1 + np.exp(-fh))
W = p * (1 - p)
sW = np.sqrt(W)
L = np.linalg.cholesky(np.eye(len(X)) + sW[:, None] * K * sW[None])
b = W * fh + (y - p)
a = b - sW * np.linalg.solve(L.T, np.linalg.solve(L, sW * (K @ b)))
fh = K @ a
p = 1 / (1 + np.exp(-fh))
W = p * (1 - p); sW = np.sqrt(W)
L = np.linalg.cholesky(np.eye(len(X)) + sW[:, None] * K * sW[None])
Ks = k(X, Xq)
mu = Ks.T @ (y - p)
v = np.linalg.solve(L, sW[:, None] * Ks)
var = SF ** 2 + SB ** 2 - (v ** 2).sum(0)
return 1 / (1 + np.exp(-mu / np.sqrt(1 + np.pi * var / 8))) # aproximación probit de ∫ σ(f) N(f) df
nll = lambda p, y: float(-np.mean(y * np.log(np.clip(p, 1e-6, 1)) + (1 - y) * np.log(np.clip(1 - p, 1e-6, 1))))
g = torch.Generator(device=dev).manual_seed(12345)
REPS = 300
modelo.eval()
print(f"\nNLL de prueba en {REPS} datasets nuevos del prior por tamaño de contexto (50 consultas cada uno)")
print(" n PFN GP(ell verd.) GP(ell=0.5) GBDT def. GBDT reg. tasa base oráculo (f verdadera)")
tabla = {}
for n in [2, 5, 10, 20, 40]:
acc = {k: [] for k in ("pfn", "gp", "gp05", "gbdt", "gbdtr", "base", "oraculo")}
x, y, fv, ell = muestrear_prior(REPS, n + M, g)
with torch.no_grad():
pp = torch.sigmoid(modelo(x[:, :n], y[:, :n], x[:, n:])).cpu().numpy()
x, y, fv, ell = (t.cpu().numpy() for t in (x, y, fv, ell))
for r in range(REPS):
Xc, yc, Xq, yq = x[r, :n], y[r, :n], x[r, n:], y[r, n:]
acc["pfn"].append(nll(pp[r], yq))
acc["gp"].append(nll(gp_laplace(Xc, yc, Xq, ell[r]), yq))
acc["gp05"].append(nll(gp_laplace(Xc, yc, Xq, 0.5), yq))
base = (yc.sum() + 1) / (n + 2) # regla de Laplace para la tasa base
acc["base"].append(nll(np.full(M, base), yq))
if 0 < yc.sum() < n:
gb = GradientBoostingClassifier(random_state=0).fit(Xc, yc) # por defecto: 100 árboles, prof. 3
acc["gbdt"].append(nll(gb.predict_proba(Xq)[:, 1], yq))
gb = GradientBoostingClassifier(n_estimators=30, max_depth=2, random_state=0).fit(Xc, yc)
acc["gbdtr"].append(nll(gb.predict_proba(Xq)[:, 1], yq))
else: # una sola clase en el contexto: el GBDT no puede ajustarse
acc["gbdt"].append(nll(np.full(M, base), yq)); acc["gbdtr"].append(nll(np.full(M, base), yq))
acc["oraculo"].append(nll(1 / (1 + np.exp(-fv[r, n:])), yq))
tabla[n] = {k: float(np.mean(v)) for k, v in acc.items()}
t = tabla[n]
print(f"{n:3d} {t['pfn']:.4f} {t['gp']:.4f} {t['gp05']:.4f} {t['gbdt']:.4f} {t['gbdtr']:.4f} {t['base']:.4f} {t['oraculo']:.4f}")
# --- Exportar los pesos (float16) y un caso de prueba para el interactivo ----------------------------------
sd = {k: v.detach().cpu().float().numpy() for k, v in modelo.state_dict().items()}
plano = np.concatenate([v.ravel() for v in sd.values()]).astype(np.float16)
xc = torch.tensor([[[-0.5, -0.5], [0.5, 0.5], [0.4, -0.6]]], device=dev)
yc = torch.tensor([[0.0, 1.0, 1.0]], device=dev)
xq = torch.tensor([[[0.0, 0.0], [-0.9, 0.9], [0.6, 0.2]]], device=dev)
modelo.load_state_dict( # el caso de prueba, con los pesos redondeados a float16
{k: torch.tensor(v.ravel().astype(np.float16).astype(np.float32).reshape(v.shape)) for k, v in sd.items()})
with torch.no_grad():
ref = torch.sigmoid(modelo(xc, yc, xq)).cpu().numpy().ravel()
json.dump({"d": 48, "heads": 4, "layers": 4, "dff": 96,
"shapes": [[k, list(v.shape)] for k, v in sd.items()],
"weights": base64.b64encode(plano.tobytes()).decode(),
"prior": {"sf": SF, "sb": SB, "ellMin": L_MIN, "ellMax": L_MAX},
"eval": tabla,
"test": {"xc": xc.cpu().numpy()[0].tolist(), "yc": [0, 1, 1], "xq": xq.cpu().numpy()[0].tolist(), "p": ref.round(5).tolist()}},
open("pfn2d.json", "w", encoding="utf-8"))
print("\ncaso de prueba, Pr(y = 1) en (0, 0), (−0.9, 0.9), (0.6, 0.2):", np.round(ref, 4))
del modelo; torch.cuda.empty_cache()npm run lab and open the connection link.In the run generating the next figure’s weights, training took about 5 minutes and batch mean NLL fell from in the first 5000 steps to in the last (not because labels are Bernoulli: even oracle NLL is about ). On 300 new datasets per context size (two runs on the same machine gave the same table; another GPU or PyTorch version may change last digits):
| PFN | GP, true | GP, | default GBDT | cautious GBDT | base rate | oracle | |
|---|---|---|---|---|---|---|---|
| 2 | 0.637 | 0.631 | 0.644 | 1.379 | 0.810 | 0.655 | 0.352 |
| 5 | 0.592 | 0.587 | 0.601 | 2.704 | 1.111 | 0.634 | 0.347 |
| 10 | 0.555 | 0.547 | 0.564 | 2.919 | 0.981 | 0.617 | 0.347 |
| 20 | 0.498 | 0.497 | 0.510 | 2.033 | 0.697 | 0.591 | 0.344 |
| 40 | 0.472 | 0.469 | 0.480 | 1.218 | 0.572 | 0.593 | 0.350 |
Three readings. PFN is within of the GP knowing each true scale and beats fixed- GP at all sizes: it learned to infer from data, unlike the GP unless given it. GBDTs are catastrophic with few data (default sklearn NLL with 10 examples, far worse than constant base rate) because probabilities become nearly 0/1 upon separating training; cautious beats base rate only at 40. The PFN–oracle gap, with two examples to with forty, is the price of unknown : no method beats posterior predictive and PFN is nearly there.
With three points PFN and GP give probabilities near 0.5 far from data and tilt only nearby, while GBDT divides the plane into extreme-probability blocks: each depth-2 tree perfectly separates three examples and 30 boosting steps accumulate confidence. Adding points sharpens PFN where data exist, with no hyperparameter to adjust: GP needs scale as input, PFN infers it from context because minimizing loss under variable- prior requires averaging over it (learned Bayesian model averaging). On XOR PFN learns structure with twelve points; depth-2 GBDT represents it too, but with straight boundaries and overconfidence.
TabPFN: the prior is the product
TabPFN applies the idea to real tables; its main ingredient is the prior, not the network.
TabPFN v1 (Hollmann et al., 2023) handled classification up to 1000 training examples, 100 numeric features and 10 classes. Its prior mixes random Bayesian networks with structural causal models (SCMs): sample a directed acyclic graph, propagate variables through random noisy transformations and randomly choose observed feature and label nodes, including causal dependencies, irrelevant features and nonlinear relations. On 18 OpenML-CC18 datasets within those limits it beat GBDTs and tied complex AutoML systems, with up to 230× CPU and 5700× GPU speedups, validated on another 67 small OpenML datasets.
TabPFN v2, published in Nature (Hollmann et al., 2025), extends classification and regression to 10 000 examples and 500 features. Changes:
- Prior. A richer SCM prior (graphs, neural-layer transformations, discretizations and decision trees, Gaussian noise per edge), consuming around 100 million synthetic datasets per training run (130 million in methods). One run costs about two weeks on an 8× RTX 2080 Ti node.
- Two-way attention. Each table cell has its own representation; each layer alternates attention among features within rows and examples within columns. Queries attend only training examples, whose representations can be cached for new test sets.
- Results. On 29 AutoML Benchmark classification datasets and 28 regression datasets (AutoML Benchmark and OpenML-CTR23), 10 repeated 90/10 splits: “in 2.8 s TabPFN beats an ensemble of the best baselines tuned for 4 h” on classification, a 5140× speedup (3000× regression).
- Limits per the paper. Compute scales quadratically in examples and memory linearly in dataset size. Inference is not optimized for real time: 0.2 s per example (0.6 s without GPU) versus 0.0002 s default CatBoost. Evaluation reaches 10 000 examples and 500 features; authors warn results do not establish scaling beyond and recommend methods like CatBoost for larger sets and very nonsmooth regression. Two authors disclose ties to Prior Labs, which develops the model: relevant to critical reading without invalidating results.
The model has evolved since the Nature paper (tabpfn offers later weights), with benchmarks like TabArena evaluating independently. The lab uses version 2 weights from the paper for comparability.
Distributional boosting: NGBoost
Squared-loss regression GBDT estimates and nothing more. Risk decisions (capital reserves, alerts, intervals) need the full distribution, especially spread, rarely constant in real data. Distributional boosting extends gradient boosting to this task.
Why not ordinary gradient, as in familiar gradient boosting? With differently scaled parameters the ordinary gradient depends on parametrization, harming training. Consider the normal.
Fisher information of the normal
With and , one observation’s negative log-likelihood is
and its gradient,
Fisher information is . With , components are , (odd moments) and :
Compare directions. Ordinary gradient in is residual divided by : examples with small have huge gradients dominating the tree fit even without more information. Natural gradient in is simply residual, as in least-squares boosting. In natural is half ordinary, but the key is both parameters share statistical scale: is each direction’s natural step size. In other words the natural step is per-example Fisher scoring.
import numpy as np
import sympy as sp
y, mu, s, z = sp.symbols("y mu s z", real=True)
nll = s + sp.log(sp.sqrt(2 * sp.pi)) + (y - mu) ** 2 / (2 * sp.exp(2 * s))
grad = sp.Matrix([sp.diff(nll, v) for v in (mu, s)])
# esperanza bajo el modelo: y = mu + e^s z con z ~ N(0, 1)
phi = sp.exp(-z ** 2 / 2) / sp.sqrt(2 * sp.pi)
gz = grad.subs(y, mu + sp.exp(s) * z)
I = (gz * gz.T).applyfunc(lambda e: sp.simplify(sp.integrate(sp.expand(e) * phi, (z, -sp.oo, sp.oo))))
print("gradiente de la NLL:", list(sp.simplify(grad)))
print("información de Fisher:", I)
print("gradiente natural:", list(sp.simplify(I.inv() * grad)))
r = np.random.default_rng(1)
m0, s0 = 1.0, np.log(0.5)
Y = r.normal(m0, np.exp(s0), 200_000)
G = np.stack([-(Y - m0) / np.exp(2 * s0), 1 - (Y - m0) ** 2 / np.exp(2 * s0)])
print("Monte Carlo E[g g^T] con sigma = 0.5:", np.round(G @ G.T / len(Y), 3).tolist(), "(teoría: [[4, 0], [0, 2]])")Why natural gradient: parametrization invariance
The natural gradient does not depend on family parametrization. If with invertible Jacobian , the chain rule gives and Fisher information transforms as , so
A step in moves to first order by : the same distribution regardless of parametrization. Ordinary gradient induces displacement , which varies with parametrization. Duan et al. (2020) show ordinary gradients make lucky examples near initial mean dominate learning, overfitting the center and underfitting tails; natural updates balance better.
NGBoost from scratch
Duan et al.’s algorithm 1 starts at marginal parameters (for normal, mean and log standard deviation of ); each stage computes each example’s natural gradient, fits one regression tree per parameter, searches scale factor (in practice starting at and halving until total loss decreases) and updates . On UCI data the paper uses depth-3 trees, (0.1 on largest dataset), selecting stage count on validation.
The cell implements this exactly for the normal using scikit-learn trees, on variance increasing with : , . To fit in the browser use and at least 20 examples per leaf, choosing stage by validation.
import numpy as np
from scipy.stats import norm
from scipy.integrate import quad
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import GradientBoostingRegressor
mu_v = lambda x: 2 * np.sin(2 * np.pi * x) + x
sd_v = lambda x: 0.1 + 0.9 * x ** 2
def generar(n, semilla):
"""x ~ U[0, 1], y | x ~ N(mu(x), sigma(x)^2): una media que oscila y un ruido que crece con x."""
r = np.random.default_rng(semilla)
x = r.uniform(0, 1, n)
return x[:, None], mu_v(x) + sd_v(x) * r.normal(size=n)
def nll_normal(y, mu, s): # −log N(y | mu, e^{2s}), con s = log sigma
return s + 0.5 * np.log(2 * np.pi) + 0.5 * (y - mu) ** 2 * np.exp(-2 * s)
def crps_normal(y, mu, sigma): # forma cerrada (Gneiting y Raftery, 2007)
z = (y - mu) / sigma
return sigma * (z * (2 * norm.cdf(z) - 1) + 2 * norm.pdf(z) - 1 / np.sqrt(np.pi))
def gradiente(y, mu, s, natural):
"""∇ de la NLL respecto a (mu, s); el natural es I(θ)^{-1} ∇ con I = diag(e^{-2s}, 2)."""
r, v = y - mu, np.exp(2 * s)
if natural:
return np.stack([-r, 0.5 * (1 - r ** 2 / v)], axis=1)
return np.stack([-r / v, 1 - r ** 2 / v], axis=1)
def ngboost(X, y, Xv, yv, M=200, eta=0.1, natural=True):
"""NGBoost (Duan et al., 2020, alg. 1) para la normal; devuelve el predictor en la mejor etapa de validación."""
th0 = np.array([y.mean(), np.log(y.std())]) # θ(0): el ajuste de la marginal
th, thv = np.tile(th0, (len(y), 1)), np.tile(th0, (len(yv), 1))
etapas, val = [], []
for _ in range(M):
g = gradiente(y, th[:, 0], th[:, 1], natural)
arb = [DecisionTreeRegressor(max_depth=3, min_samples_leaf=20).fit(X, g[:, j]) for j in range(2)]
paso = np.stack([a.predict(X) for a in arb], axis=1)
L0, rho = nll_normal(y, th[:, 0], th[:, 1]).sum(), 1.0
while rho > 1e-4 and nll_normal(y, *(th - rho * paso).T).sum() > L0:
rho /= 2 # búsqueda lineal por mitades
th -= eta * rho * paso
thv -= eta * rho * np.stack([a.predict(Xv) for a in arb], axis=1)
etapas.append((arb, rho)); val.append(nll_normal(yv, thv[:, 0], thv[:, 1]).mean())
mejor = int(np.argmin(val)) + 1
def predecir(Z):
t = np.tile(th0, (len(Z), 1))
for arb, rho in etapas[:mejor]:
t -= eta * rho * np.stack([a.predict(Z) for a in arb], axis=1)
return t[:, 0], np.exp(t[:, 1])
return predecir, mejor
Xa, ya = generar(1000, 0)
Xv, yv = generar(500, 1)
Xt, yt = generar(5000, 2)
nat, m_nat = ngboost(Xa, ya, Xv, yv, natural=True)
_, s_nat = nat(np.array([[0.1], [0.5], [0.9]]))
print(f"gradiente natural: etapa elegida en validación {m_nat}")
print("sigma predicha en x = 0.1, 0.5, 0.9:", np.round(s_nat, 3), "| verdadera:", np.round(sd_v(np.array([0.1, 0.5, 0.9])), 3))ordi, m_ord = ngboost(Xa, ya, Xv, yv, natural=False)
gb = GradientBoostingRegressor(n_estimators=200, learning_rate=0.1, max_depth=3, min_samples_leaf=20,
n_iter_no_change=20, validation_fraction=0.2, random_state=0).fit(Xa, ya)
sig = np.std(yv - gb.predict(Xv)) # varianza constante, estimada en validación
h = quad(lambda x: np.log(sd_v(x)), 0, 1)[0] + 0.5 * np.log(2 * np.pi * np.e)
print(f"etapas elegidas en validación: natural {m_nat}, ordinario {m_ord}; GBDT: {gb.n_estimators_} árboles y sigma = {sig:.3f}")
print(" NLL CRPS cobertura 90 %")
for nombre, (m, s) in [("NGBoost, natural", nat(Xt)), ("NGBoost, ordinario", ordi(Xt)),
("GBDT + sigma constante", (gb.predict(Xt), np.full(len(yt), sig))),
("distribución verdadera", (mu_v(Xt[:, 0]), sd_v(Xt[:, 0])))]:
cub = np.mean(np.abs(yt - m) <= norm.ppf(0.95) * s)
print(f"{nombre:24s} {nll_normal(yt, m, np.log(s)).mean():7.4f} {crps_normal(yt, m, s).mean():7.4f} {cub:.3f}")
print(f"NLL esperada de la verdad (integral exacta): {h:.4f}")Validation chooses stage 56 for natural gradient and 93 for ordinary. On 5000 test examples:
| model | NLL | CRPS | 90% interval coverage |
|---|---|---|---|
| NGBoost, natural gradient | 0.326 | 0.2345 | 0.899 |
| NGBoost, ordinary gradient | 0.382 | 0.2361 | 0.895 |
| GBDT + constant () | 0.726 | 0.2619 | 0.904 |
| true distribution | 0.265 | 0.2275 | 0.897 |
True distribution expected NLL is ; table estimates it from this sample. Natural-gradient NGBoost more than halves constant-variance GBDT NLL and clearly beats ordinary gradient. Two details: GBDT global coverage is correct () despite worst NLL: its interval is too wide where is small and too narrow where large, errors cancelling on average. Marginal coverage is insufficient for probabilistic prediction evaluation; a proper rule is. CRPS distinguishes models less than NLL: in units of , dominated by mean error, it penalizes spread error less (see continuous prediction scoring). Predicted at , and is , and versus true , and : noisy right end remains incompletely fitted by early stopping.
Three observations. Constant- GBDT band is equally wide at , noise , and , noise : too wide left and too narrow right, penalized by NLL. NGBoost follows . Running beyond validation optimum makes test NLL rise again: trees fit noise, training residuals shrink and trees narrow the band accordingly. Validation early stopping is essential.
How to read these papers
This provides the tools to distinguish useful tabular benchmarks from misleading ones.
Five questions for every paper:
- Which datasets and why? Grinsztajn et al. set a model: explicit criteria fixed before results, excluding overly easy datasets (where all tie and comparison adds noise). Beware author-chosen datasets, as Shwartz-Ziv and Armon showed. Check size range: most public benchmarks have hundreds to tens of thousands of rows.
- Equal tuning budget? A new method with 100 trials versus default XGBoost measures budget, not method. Give equal trial count (or time), reasonable search spaces, defaults as first trial and a result–budget curve as Grinsztajn et al. do. The GBDT tuning recipe and random search give a strong low-effort baseline.
- Leakage-free validation? Hyperparameters are chosen within each training split (nested CV or inner holdout), and test used once. TabArena found validation and configuration ensembles change rankings, with some networks overrepresented in ensembles by overfitting validation.
- Which metric and aggregation? Accuracy, AUC and log-loss can rank models differently; if decisions use probabilities, use a proper rule. Three common nonneutral aggregations: mean rank (simple but dependent on competitors: adding a clone changes others’ ranks), per-dataset normalized score between best model and a reference (Grinsztajn et al. normalize between best and a low quantile of all results; reference changes weights), and pairwise wins with a test. With many models and datasets a critical-difference diagram summarizes significant differences. Report intervals across seeds per dataset and across datasets (resampling) for the aggregate.
- Cost? A foundation model winning accuracy with 3 s “training” may take a thousand times longer than GBDT to predict. This matters when scoring millions of transactions daily. Always report fitting time, per-row inference time and memory.
Pretrained models add contamination: if evaluation datasets or variants influenced pretraining or design choices, a benchmark no longer measures generalization. Synthetic priors lower risk relative to language models but do not eliminate it: priors, architecture and hyperparameters were selected by looking at real-data results, often from the same public repositories. New or private datasets are more valuable.
Lab: a reproducible benchmark
The next local cell compares six configurations on eight OpenML binary classification datasets (748 to 19 020 rows, training capped at 10 000 as in Grinsztajn et al.):
- Tuned LightGBM: 30-trial random search (defaults first) over rate, leaves, minimum leaf, columns and , with early stopping on a 20% inner holdout and full-fold retraining with tree count scaled by .
- Default LightGBM, to measure tuning’s contribution.
- Tuned MLP in PyTorch: inputs transformed to normal by
QuantileTransformer, 1–4 layers, dropout, AdamW and early stopping, same 30-trial budget and holdout/retraining protocol. - TabPFN v2 on GPU, without tuning: training examples are context.
- NGBoost with Bernoulli distribution, early stopping on holdout and retraining.
Outer protocol is stratified 3-fold CV repeated with 5 seeds; report per-dataset log-loss and Brier, mean rank with 95% bootstrap interval resampling datasets, each model’s difference versus tuned LightGBM with interval across seeds, and fitting and per-row prediction times. Categoricals are one-hot encoded for every model, slightly disadvantaging LightGBM (native categorical support) on credit-g, the only categorical dataset. First install missing packages using python -m pip install tabpfn ngboost (verified with tabpfn 9.2.0 and ngboost 0.5.11); TabPFN downloads weights from Hugging Face on first use, and the cell explicitly requests version 2 using create_default_for_version(ModelVersion.V2).
The full benchmark takes hours. A short version verified the cell (environment variable ORYON_VERIFY_SHORT=1: 3 tuning trials, 2 folds, one seed and only blood-transfusion, diabetes and qsar-biodeg); reported numbers come from that run and show end-to-end code function, not model superiority.
import os, time, warnings
os.environ.setdefault("TABPFN_DISABLE_TELEMETRY", "1")
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import lightgbm as lgb
from scipy import stats
from sklearn.datasets import fetch_openml
from sklearn.metrics import log_loss, brier_score_loss
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.preprocessing import QuantileTransformer
warnings.filterwarnings("ignore")
try:
from tabpfn import TabPFNClassifier # python -m pip install tabpfn
from tabpfn.constants import ModelVersion
except ImportError:
TabPFNClassifier = None
try:
from ngboost import NGBClassifier # python -m pip install ngboost
from ngboost.distns import Bernoulli
except ImportError:
NGBClassifier = None
CORTO = os.environ.get("ORYON_VERIFY_SHORT") == "1"
ENSAYOS, PLIEGUES, SEMILLAS = (3, 2, 1) if CORTO else (30, 3, 5)
dev = "cuda" if torch.cuda.is_available() else "cpu"
MAX_FILAS = 10_000 # límite de entrenamiento para todos (como Grinsztajn et al.)
IDS = {"blood-transfusion": 1464, "diabetes": 37, "credit-g": 31, "qsar-biodeg": 1494,
"kc1": 1067, "ozone-level": 1487, "phoneme": 1489, "MagicTelescope": 1120}
if CORTO:
IDS = {k: IDS[k] for k in ("blood-transfusion", "diabetes", "qsar-biodeg")}
print(f"presupuesto: {ENSAYOS} ensayos por modelo ajustable, {PLIEGUES} pliegues x {SEMILLAS} semillas, dispositivo {dev}"
+ (" (CORTO)" if CORTO else ""))
print("TabPFN:", "sí" if TabPFNClassifier else "no instalado", "| NGBoost:", "sí" if NGBClassifier else "no instalado")
def cargar(i):
d = fetch_openml(data_id=i, as_frame=True, parser="liac-arff")
X = pd.get_dummies(d.data, drop_first=True, dtype=float).astype(float) # one-hot para todos: simplificación
y = d.target.astype(str)
return X.to_numpy(), (y == sorted(y.unique())[-1]).astype(int).to_numpy()
# --- Modelos: cada uno recibe (Xa, ya) del pliegue externo y devuelve una función de predicción ---------------
def lgbm(Xa, ya, s, ajustar=True):
if not ajustar:
m = lgb.LGBMClassifier(random_state=s, verbose=-1).fit(Xa, ya)
return lambda Z: m.predict_proba(Z)[:, 1]
Xf, Xv, yf, yv = train_test_split(Xa, ya, test_size=0.2, random_state=s, stratify=ya)
r, mejor = np.random.default_rng(s), None
for t in range(ENSAYOS):
p = dict(learning_rate=0.1, num_leaves=31, min_child_samples=20, colsample_bytree=1.0, reg_lambda=0.0) if t == 0 else dict(
learning_rate=float(np.exp(r.uniform(np.log(0.01), np.log(0.3)))), num_leaves=int(np.exp(r.uniform(np.log(4), np.log(128)))),
min_child_samples=int(np.exp(r.uniform(np.log(2), np.log(100)))), colsample_bytree=float(r.uniform(0.5, 1.0)),
reg_lambda=float(np.exp(r.uniform(np.log(1e-3), np.log(10))))) # el ensayo 0: valores por defecto
m = lgb.LGBMClassifier(n_estimators=3000, subsample=0.8, subsample_freq=1, random_state=s, verbose=-1, **p)
m.fit(Xf, yf, eval_set=[(Xv, yv)], callbacks=[lgb.early_stopping(50, verbose=False)])
v = log_loss(yv, m.predict_proba(Xv, num_iteration=m.best_iteration_)[:, 1])
if mejor is None or v < mejor[0]:
mejor = (v, p, m.best_iteration_)
_, p, n = mejor
m = lgb.LGBMClassifier(n_estimators=max(1, round(n / 0.8)), subsample=0.8, subsample_freq=1, random_state=s, verbose=-1, **p).fit(Xa, ya)
return lambda Z: m.predict_proba(Z)[:, 1]
class MLP(nn.Module):
def __init__(self, d, ancho, capas, drop):
super().__init__()
bloques, e = [], d
for _ in range(capas):
bloques += [nn.Linear(e, ancho), nn.ReLU(), nn.Dropout(drop)]
e = ancho
self.red = nn.Sequential(*bloques, nn.Linear(e, 1))
def forward(self, x):
return self.red(x).squeeze(-1)
def entrenar_mlp(X, y, p, s, Xv=None, yv=None, epocas=None):
torch.manual_seed(s)
m = MLP(X.shape[1], p["ancho"], p["capas"], p["drop"]).to(dev)
opt = torch.optim.AdamW(m.parameters(), lr=p["lr"], weight_decay=p["wd"])
Xg, yg = torch.tensor(X, dtype=torch.float32, device=dev), torch.tensor(y, dtype=torch.float32, device=dev)
pred = lambda Z: torch.sigmoid(m(torch.tensor(Z, dtype=torch.float32, device=dev))).detach().cpu().numpy()
mejor, paciencia, estado = (np.inf, 0), 0, None
for ep in range(epocas or 300):
m.train()
for idx in torch.randperm(len(y), device=dev).split(256):
opt.zero_grad()
nn.functional.binary_cross_entropy_with_logits(m(Xg[idx]), yg[idx]).backward()
opt.step()
if Xv is not None:
m.eval()
v = log_loss(yv, np.clip(pred(Xv), 1e-7, 1 - 1e-7))
if v < mejor[0]:
mejor, paciencia, estado = (v, ep + 1), 0, {k: t.clone() for k, t in m.state_dict().items()}
elif (paciencia := paciencia + 1) >= 16:
break
if estado:
m.load_state_dict(estado)
m.eval()
return pred, mejor
def mlp(Xa, ya, s):
q = QuantileTransformer(output_distribution="normal", n_quantiles=min(1000, len(ya)), random_state=s).fit(Xa)
Qa = q.transform(Xa)
Qf, Qv, yf, yv = train_test_split(Qa, ya, test_size=0.2, random_state=s, stratify=ya)
r, mejor = np.random.default_rng(s), None
for t in range(ENSAYOS):
p = dict(ancho=int(r.choice([64, 128, 256, 512])), capas=int(r.integers(1, 5)), drop=float(r.uniform(0, 0.5)),
lr=float(np.exp(r.uniform(np.log(1e-4), np.log(3e-3)))), wd=float(np.exp(r.uniform(np.log(1e-6), np.log(1e-2)))))
_, (v, ep) = entrenar_mlp(Qf, yf, p, s, Qv, yv)
if mejor is None or v < mejor[0]:
mejor = (v, p, ep)
_, p, ep = mejor
pred, _ = entrenar_mlp(Qa, ya, p, s, epocas=max(1, round(ep / 0.8)))
return lambda Z: pred(q.transform(Z))
def tabpfn(Xa, ya, s):
m = TabPFNClassifier.create_default_for_version(ModelVersion.V2, device=dev, random_state=s).fit(Xa, ya)
return lambda Z: m.predict_proba(Z)[:, 1]
def ngboost(Xa, ya, s):
Xf, Xv, yf, yv = train_test_split(Xa, ya, test_size=0.2, random_state=s, stratify=ya)
m = NGBClassifier(Dist=Bernoulli, n_estimators=2000, learning_rate=0.05, verbose=False, random_state=s)
m.fit(Xf, yf, X_val=Xv, Y_val=yv, early_stopping_rounds=50)
n = (m.best_val_loss_itr or len(m.base_models)) + 1
m = NGBClassifier(Dist=Bernoulli, n_estimators=max(1, round(n / 0.8)), learning_rate=0.05, verbose=False, random_state=s).fit(Xa, ya)
return lambda Z: m.predict_proba(Z)[:, 1]
MODELOS = {"LightGBM ajustado": lgbm, "LightGBM por defecto": lambda X, y, s: lgbm(X, y, s, ajustar=False), "MLP ajustado": mlp}
if TabPFNClassifier:
MODELOS["TabPFN v2"] = tabpfn
if NGBClassifier:
MODELOS["NGBoost"] = ngboost
filas = []
for nombre, i in IDS.items():
X, y = cargar(i)
print(f"{nombre:18s} filas {len(y):6d} variables {X.shape[1]:3d} fracción y=1 {y.mean():.3f}", flush=True)
for s in range(SEMILLAS):
for k, (itr, ite) in enumerate(StratifiedKFold(PLIEGUES, shuffle=True, random_state=s).split(X, y)):
if len(itr) > MAX_FILAS:
itr = np.random.default_rng(s).choice(itr, MAX_FILAS, replace=False)
for mod, fn in MODELOS.items():
t0 = time.perf_counter()
pred = fn(X[itr], y[itr], s)
t1 = time.perf_counter()
q = np.clip(pred(X[ite]), 1e-7, 1 - 1e-7)
t2 = time.perf_counter()
filas.append(dict(datos=nombre, modelo=mod, semilla=s, pliegue=k, logloss=log_loss(y[ite], q),
brier=brier_score_loss(y[ite], q), seg_ajuste=t1 - t0, ms_pred=1000 * (t2 - t1) / len(ite)))
R = pd.DataFrame(filas)
D = R.groupby(["datos", "modelo"])[["logloss", "brier", "seg_ajuste", "ms_pred"]].mean().unstack("modelo")
mods = list(MODELOS)
print("\nlog-loss de prueba externa por conjunto (media de semillas y pliegues)")
print(D["logloss"][mods].round(4).to_string())
print("\nBrier por conjunto")
print(D["brier"][mods].round(4).to_string())
rangos = D["logloss"][mods].rank(axis=1) # rango 1 = mejor log-loss en ese conjunto
r = np.random.default_rng(0)
boot = np.array([rangos.iloc[r.integers(0, len(rangos), len(rangos))].mean() for _ in range(2000)])
print(f"\nrango medio en log-loss sobre {len(rangos)} conjuntos (intervalo bootstrap al 95 % remuestreando conjuntos)")
for j, m in enumerate(mods):
lo, hi = np.percentile(boot[:, j], [2.5, 97.5])
print(f" {m:22s} {rangos[m].mean():.2f} [{lo:.2f}, {hi:.2f}]")
if SEMILLAS > 1:
print("\ndiferencia de log-loss frente a LightGBM ajustado, por conjunto (intervalo t al 95 % entre semillas)")
S = R.groupby(["datos", "modelo", "semilla"]).logloss.mean().unstack("modelo")
for m in mods[1:]:
dif = (S[m] - S["LightGBM ajustado"]).groupby("datos")
txt = [f"{d} {v.mean():+.4f}±{stats.t.ppf(0.975, len(v) - 1) * v.std(ddof=1) / np.sqrt(len(v)):.4f}" for d, v in dif]
print(f" {m}: " + "; ".join(txt))
print("\ntiempos medios: ajuste (s) y predicción (ms por fila)")
print(pd.concat({"ajuste_s": D["seg_ajuste"][mods].mean(), "pred_ms_fila": D["ms_pred"][mods].mean()}, axis=1).round(3).to_string())npm run lab and open the connection link.In the short run (3 datasets of 748–1055 rows, 3 trials, 2 folds, one seed), test log-loss was:
| dataset | tuned LightGBM | default LightGBM | tuned MLP | TabPFN v2 | NGBoost |
|---|---|---|---|---|---|
| blood-transfusion | 0.501 | 0.581 | 0.500 | 0.484 | 0.508 |
| diabetes | 0.504 | 0.625 | 0.526 | 0.476 | 0.531 |
| qsar-biodeg | 0.346 | 0.441 | 0.384 | 0.326 | 0.416 |
Mean rank with its interval would be the study conclusion; with three datasets bootstrap intervals mean little (TabPFN first in all, rank ; tuned LightGBM ; MLP ; NGBoost ; default LightGBM ). Three cautious observations agree with literature:
- TabPFN wins on datasets under a thousand rows, in log-loss and Brier, on all three. This is its Nature-paper and TabArena small-data regime. Differences from tuned LightGBM ( to ) are of the order of seed variation, so the full five-seed interval determines whether they are real.
- Tuning matters more than family. Default LightGBM is worst on all three; with only 3 trials (first defaults with early stopping) diabetes improves to . With about 400 training examples per fold, 100 31-leaf trees without stopping at overfit; early stopping fixes most of it. The poorly tuned baseline error, measured.
- Cost shifts to inference. TabPFN “fit” is faster than MLP but per-row prediction hundreds of times slower than LightGBM (about 2 ms versus microseconds, on a shared GPU: order of magnitude only).
In the full run check whether TabPFN advantage persists on phoneme and MagicTelescope (5404 and 19 020 rows, training capped at 10 000), where tuned GBDT has more data; whether intervals of differences versus tuned LightGBM exclude zero; and how mean ranks change if default LightGBM is removed (last exercise’s competitor sensitivity).
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 5. What is ?
natural_gradient_normal(y, mu, log_sigma), receiving three arrays of shape (n,) and returning an (n, 2) array with the NLL natural gradient of with respect to per example. Tests compare the analytic expression, check matches the finite-difference gradient, and that if follows the model, natural gradient has zero mean and covariance .import numpy as np
def natural_gradient_normal(y, mu, log_sigma):
"""Gradiente natural de la NLL de N(mu, exp(log_sigma)^2) respecto a (mu, log_sigma). Devuelve (n, 2)."""
y, mu, s = (np.asarray(a, dtype=float) for a in (y, mu, log_sigma))
r = y - mu
var = np.exp(2 * s)
g = np.stack([-r / var, 1 - r ** 2 / var], axis=1) # gradiente ordinario de la NLL
# tu código: premultiplica cada fila por la inversa de la información de Fisher
return gSummary
- Careful studies (Grinsztajn et al., McElfresh et al., TabArena) agree GBDTs remain the model to beat on medium tabular data, tuning often matters more than family, and foundation models excel on small sets.
- Grinsztajn et al.’s three ablations: smoothing removes tree advantage, noise columns hurt MLPs, and input rotation hurts trees while MLPs remain invariant in distribution under gradient training with isotropic initialization.
- Successful tabular networks reintroduce this bias: strong regularization, per-column embeddings, piecewise-linear encoding.
- PFNs minimize log-loss over prior-generated datasets and approximate that prior’s posterior predictive; one-pass prediction costs quadratically in example count. TabPFN v2 extends this to real tables up to 10 000 examples and 500 features.
- NGBoost predicts full distributions by fitting trees to natural gradient ; for the normal in , , and natural gradient is parametrization invariant.
- Read benchmarks for dataset inclusion, equal tuning budgets, leakage-free validation, proper metrics, aggregates with intervals and inference costs.