Module contents
Lesson 24 of 24Research 100 min

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

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:

  1. Is it true? What reference comparative studies measure, their protocols and what they cannot conclude.
  2. 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.
  3. 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 d/n<1/10d/n < 1/10, 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 kk iterations versus kk. 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 ℓ\ell (ℓ=0\ell = 0 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

f(x)=0.5sin⁡(2πx1)+2⋅1[x1>0.55, x2>0.3]−1.5⋅1[x2>0.75]+1[∣x1−0.25∣<0.05]\begin{aligned} f(\vb{x}) = {}& 0.5\sin(2\pi x_1) + 2\cdot\ind[x_1 > 0.55,\ x_2 > 0.3] \\ & - 1.5\cdot\ind[x_2 > 0.75] + \ind[\abs{x_1 - 0.25} < 0.05] \end{aligned}

on [0,1]2[0, 1]^2: a smooth part, corner plateau, horizontal step and narrow strip. Train on 3000 noisy examples N(0,0.12)\Normal(0, 0.1^2), first replacing each yiy_i with Nadaraya–Watson smoothing y~i=∑jKℓ(xi,xj) yj/∑jKℓ(xi,xj)\tilde y_i = \sum_j K_\ell(\vb{x}_i, \vb{x}_j)\,y_j / \sum_j K_\ell(\vb{x}_i, \vb{x}_j) at Kℓ(x,x′)=exp⁡(−∥x−x′∥2/2ℓ2)K_\ell(\vb{x}, \vb{x}') = \exp(-\norm{\vb{x} - \vb{x}'}^2/2\ell^2), and measure test RMSE against ff.

InteractiveIrregular functions
Training target: ff
GBDT prediction
MLP prediction
GBDT advantage: MLP RMSE minus GBDT RMSE versus original ff (mean and range of 3 seeds)
no advantage
  • MLP RMSE − GBDT RMSE
  • maps: blue negative, red positive (−3 to 3)
0
Error measured against
GBDT test RMSE0.099
MLP test RMSE0.127
GBDT advantage (MLP RMSE − GBDT RMSE)0.029
Without smoothing, GBDT wins clearly: RMSE 0.099 versus 0.127, or 29% more error for the MLP. Its map blurs the plateau edges and the narrow strip near x₁ ≈ 0.25. Increase ℓ.
Above, training target (smoothed at width ℓ\ell) and each model's learned function on [0,1]2[0, 1]^2. Below, GBDT (early-stopped HistGradientBoostingRegressor) advantage over MLP (two 256-unit layers, Adam, early stopping): MLP test RMSE minus GBDT test RMSE versus ℓ\ell, mean and range of three seeds; readings show both RMSEs. All numbers come from the local cell 'Las tres ablaciones en un problema sintético' (three ablations on a synthetic problem). Move ℓ\ell from 0: what first happens to each map? Then change the error target to the smoothed function.

At ℓ=0\ell = 0 GBDT RMSE is 0.0990.099 and MLP 0.1270.127: 29% more error, explained by the map. MLP blurs plateau, step and x1≈0.25x_1 \approx 0.25 strip edges (width 0.10.1); GBDT reproduces them with few splits. At ℓ=0.01\ell = 0.01, about mean nearest-neighbor distance among 3000 points (0.5/3000≈0.0090.5/\sqrt{3000} \approx 0.009), smoothing barely touches irregularities and advantage persists (+0.035+0.035). It then drops rapidly: +0.010+0.010 at ℓ=0.02\ell = 0.02, +0.004+0.004 at 0.030.03, +0.002+0.002 at 0.050.05 and under 0.0010.001 from 0.0750.075. 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 ℓ=0.05\ell = 0.05 (0.0160.016 versus 0.0230.023): 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 W(1)x\mat{W}^{(1)}\vb{x} 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 Q\mat{Q} (orthogonal matrix determinant 1) to all training and test rows. Information is unchanged: Q\mat{Q} 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 Φ(W,b,ϕ)=(WQ⊤,b,ϕ)\Phi(\mat{W}, \vb{b}, \phi) = (\mat{W}\mat{Q}\T, \vb{b}, \phi). Since WQ⊤Qx=Wx\mat{W}\mat{Q}\T\mat{Q}\vb{x} = \mat{W}\vb{x}, fΦ(θ)(Qx)=fθ(x)f_{\Phi(\theta)}(\mat{Q}\vb{x}) = f_\theta(\vb{x}) and rotated-data loss satisfies R^Q(Φ(θ))=R^(θ)\hat R_Q(\Phi(\theta)) = \hat R(\theta); also ∥WQ⊤∥F=∥W∥F\norm{\mat{W}\mat{Q}\T}_F = \norm{\mat{W}}_F. Differentiate R^Q∘Φ=R^\hat R_Q \circ \Phi = \hat R with respect to W\mat{W}: since Φ\Phi is linear in W\mat{W} with ∂(WQ⊤)/∂W\partial(\mat{W}\mat{Q}\T)/\partial\mat{W} acting as G↦GQ⊤\mat{G} \mapsto \mat{G}\mat{Q}\T, the chain rule gives ∇WR^(θ)=∇WR^Q(Φ(θ)) Q\nabla_{\mat{W}}\hat R(\theta) = \nabla_{\mat{W}}\hat R_Q(\Phi(\theta))\,\mat{Q}, i.e., ∇WR^Q(Φ(θ))=∇WR^(θ) Q⊤\nabla_{\mat{W}}\hat R_Q(\Phi(\theta)) = \nabla_{\mat{W}}\hat R(\theta)\,\mat{Q}\T, and gradients with respect to b\vb{b} and ϕ\phi match. Thus step θ′=θ−η∇R^(θ)\theta' = \theta - \eta\nabla\hat R(\theta) becomes Φ(θ′)=Φ(θ)−η∇R^Q(Φ(θ))\Phi(\theta') = \Phi(\theta) - \eta\nabla\hat R_Q(\Phi(\theta)): the rotated-data step from Φ(θ)\Phi(\theta) reaches Φ(θ′)\Phi(\theta'). Momentum is a linear combination of past gradients and commutes with G↦GQ⊤\mat{G} \mapsto \mat{G}\mat{Q}\T similarly. By induction A(Φ(θ0),DQ)=Φ(A(θ0,D))\mathcal{A}(\Phi(\theta_0), \Data_Q) = \Phi(\mathcal{A}(\theta_0, \Data)); apply the first identity. For the second part, if each row w\vb{w} of W0\mat{W}_0 is N(0,σ2I)\Normal(\vb{0}, \sigma^2\mat{I}), the corresponding row of W0Q⊤\mat{W}_0\mat{Q}\T is Qw∼N(0,σ2QQ⊤)=N(0,σ2I)\mat{Q}\vb{w} \sim \Normal(\vb{0}, \sigma^2\mat{Q}\mat{Q}\T) = \Normal(\vb{0}, \sigma^2\mat{I}).

∎

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 W\mat{W} 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 L1L_1-penalized logistic regression (not invariant) needs only logarithmic growth. The second and third biases are the same problem from two sides.

InteractiveRotate the data
Tree with 6 leaves, data rotated 30°
MLP, data rotated 30°
Test accuracy versus angle (6-leaf tree retrained at each angle)
  • tree (CART, Gini)
  • MLP 2-16-16-1
  • class 1 (red) and class 0 (blue)
  • true boundary
30°
6
Tree test accuracy (6 leaves)NaN %
MLP test accuracyNaN %
Tree leaves needed for 95%…
Calculating…
Uniform data in the unit disk with an axis-aligned corner boundary (y=1y = 1 if x1>−0.25x_1 > -0.25 and x2>−0.1x_2 > -0.1), 400 training and 2000 test examples, noiseless labels. Rotate training and test by angle θ\theta: the disk stays fixed and only the boundary rotates (dashed). Left, a LL-leaf CART tree retrained in your browser; right, a 2-16-16-1 momentum-gradient MLP to which the theorem applies: its rotated-data prediction exactly rotates the original. Below, LL-leaf test accuracy by angle versus MLP. Rotate 0° to 45°: how many leaves does the tree need to maintain 95%?

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 30°30° 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 30°30° from rotated initialization, comparing predictions. Then train a six-leaf scikit-learn DecisionTreeClassifier at several angles.

[ ]MLP equivarianceBrowser
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 10−1610^{-16}) and have identical accuracy 0.9570.957. The six-leaf tree falls from 0.9950.995 unrotated to 0.9440.944, 0.9190.919 and 0.9340.934 at 15°15°, 30°30° and 45°45°. 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 ff above, with three seeds. It runs locally in minutes on CPU (scikit-learn), supplying the first figure’s numbers.

[ ]Three ablations on a synthetic problemLocal GPU
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)")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 +0.029+0.029 unsmoothed to below 0.0010.001 at ℓ≥0.075\ell \ge 0.075, as in the figure.
  • Uninformative features: with 0, 4, 16 and 64 noise columns, GBDT gives 0.0990.099, 0.1010.101, 0.1020.102 and 0.1030.103; MLP 0.1270.127, 0.3170.317, 0.6490.649 and 0.8560.856. The tree barely notices; with 3000 examples MLP struggles.
  • Rotation: with x1,x2x_1, x_2 and 6 noise columns, GBDT changes 0.1010.101 to 0.6720.672 upon rotation and MLP 0.4850.485 to 0.4710.471. Ranking reverses as in the paper, while Adam-trained MLP is practically invariant: difference is within seed variation.

The rotation MLP already starts poorly (0.4850.485 versus 0.1270.127 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 h\vb{h} 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 jj to a vector, ej=xjwj+bj∈Rd\vb{e}_j = x_j\vb{w}_j + \vb{b}_j \in \R^{d} for numeric (lookup plus bias for categoricals), stacks kk vectors with a [CLS][\text{CLS}] token and applies transformer layers, so self-attention models column interactions; prediction comes from final [CLS][\text{CLS}] representation. FT-Transformer was the best network on most tasks, but no universally superior GBDT or network existed.

Numeric feature embeddings. Tokenizer xjwjx_j\vb{w}_j is linear in xjx_j and cannot represent a threshold jump. Gorishniy, Rubachev and Babenko (2022) studied nonlinear scalar embeddings. Piecewise-linear encoding divides xjx_j into bins [bt−1,bt)[b_{t-1}, b_t) (quantiles or tree splits) and encodes xjx_j as a vector whose tt component is 1 if xj≥btx_j \ge b_t, 0 if xj<bt−1x_j < b_{t-1} and within-bin fraction (xj−bt−1)/(bt−bt−1)(x_j - b_{t-1})/(b_t - b_{t-1}); periodic activations use [sin⁡(2πcixj),cos⁡(2πcixj)]i[\sin(2\pi c_i x_j), \cos(2\pi c_i x_j)]_i with learned frequencies cic_i. 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 p(x,y∣φ)p(\vb{x}, y \given \varphi) with latent parameter or mechanism φ\varphi and prior p(φ)p(\varphi), the best statement about a new point’s label after seeing D={(xi,yi)}i=1n\Data = \{(\vb{x}_i, y_i)\}_{i=1}^n is the posterior predictive

p(y∣x,D)=∫p(y∣x,φ) p(φ∣D) ⁣dφ.p(y \given \vb{x}, \Data) = \int p(y \given \vb{x}, \varphi)\, p(\varphi \given \Data)\dd\varphi.

Computing it is usually intractable: the posterior over φ\varphi under a rich prior (neural networks, causal graphs) has no closed form. But sampling from the generative model is easy: sample φ∼p(φ)\varphi \sim p(\varphi), then dataset D\Data and test point (x,y)(\vb{x}, y). Müller et al. (2022) propose using these samples to train a network taking D\Data and x\vb{x} and predicting yy.

Why does this loss lead to posterior prediction? It is a proper scoring rule averaged over the prior.

Proof

Condition on (D,x)(\Data, \vb{x}). Under the joint distribution the conditional law of yy given (D,x)(\Data, \vb{x}) is by definition posterior predictive ∫p(y∣x,φ) p(φ∣D,x) ⁣dφ\int p(y \given \vb{x}, \varphi)\,p(\varphi \given \Data, \vb{x})\dd\varphi, matching the formula above when x\vb{x}‘s distribution does not depend on φ\varphi (as in the toy cell’s prior, where x∼Unif⁡[−1,1]2\vb{x} \sim \Unif[-1, 1]^2). If yy is discrete,

E[−log⁡q(y∣x,D)∣D,x]=−∑yp(y∣x,D)log⁡q(y∣x,D)=H⁡(p)+KL⁡(p ∥ q),\E\big[-\log q(y \given \vb{x}, \Data) \given \Data, \vb{x}\big] = -\sum_y p(y \given \vb{x}, \Data)\log q(y \given \vb{x}, \Data) = \Ent(p) + \KL(p \,\|\, q),

adding and subtracting ∑yplog⁡p\sum_y p\log p (if yy is continuous, similarly with densities, integrals and finite differential entropy). Take expectation over (D,x)(\Data, \vb{x}) for the identity. Gibbs’ inequality gives KL⁡≥0\KL \ge 0 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 ϑ∼Beta(1,1)\vartheta \sim \text{Beta}(1, 1), whose predictive after kk heads in nn tosses is Laplace’s rule (k+1)/(n+2)(k + 1)/(n + 2). The “transformer” here is a table with one logit per possible context (n,k)(n, k), trained by SGD on cross-entropy of prior-generated queries.

[ ]A table PFN learns Laplace’s ruleBrowser
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 (k+1)/(n+2)(k + 1)/(n + 2), with maximum error of a few hundredths from SGD noise in rarely visited cells. With n=0n = 0 it predicts 0.50.5, and with 33 tails in 33 tosses predicts 0.20.2 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 xi\vb{x}_i and yiy_i, each query a token with x\vb{x} 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 yy (softmax for classification, discretized for regression).

The cost is quadratic: attention among nn training examples costs O(n2)\bigO(n^2) per layer, dominant once nn reaches thousands.

A toy PFN

The next cell trains a full PFN on your GPU in minutes. The prior is two-dimensional classification: x∼Unif⁡[−1,1]2\vb{x} \sim \Unif[-1, 1]^2, logit ff a Gaussian process with kernel k(x,x′)=32exp⁡(−∥x−x′∥2/2ℓ2)+1k(\vb{x}, \vb{x}') = 3^2\exp(-\norm{\vb{x} - \vb{x}'}^2/2\ell^2) + 1 and log-uniform scale ℓ\ell in [0.2,1.5][0.2, 1.5] (each synthetic dataset has its own ℓ\ell), and y∼Bern⁡(σ(f(x)))y \sim \Bern(\sigmoid(f(\vb{x}))). A four-layer transformer with dmodel=48d_{\text{model}} = 48 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 ℓ\ell (partial oracle: exact predictive averages over ℓ\ell) and fixed ℓ=0.5\ell = 0.5;
  • 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 ff and predicting σ(f(x))\sigmoid(f(\vb{x})).
[ ]A toy PFN: training and evaluationLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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 0.5290.529 in the first 5000 steps to 0.5110.511 in the last (not 00 because labels are Bernoulli: even oracle NLL is about 0.350.35). 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):

nnPFNGP, true ℓ\ellGP, ℓ=0.5\ell = 0.5default GBDTcautious GBDTbase rateoracle
20.6370.6310.6441.3790.8100.6550.352
50.5920.5870.6012.7041.1110.6340.347
100.5550.5470.5642.9190.9810.6170.347
200.4980.4970.5102.0330.6970.5910.344
400.4720.4690.4801.2180.5720.5930.350

Three readings. PFN is within 0.0080.008 of the GP knowing each true scale and beats fixed-ℓ=0.5\ell = 0.5 GP at all sizes: it learned to infer ℓ\ell from data, unlike the GP unless given it. GBDTs are catastrophic with few data (default sklearn NLL 2.92.9 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, 0.290.29 with two examples to 0.120.12 with forty, is the price of unknown ff: no method beats posterior predictive and PFN is nearly there.

InteractiveTabular in-context learning
PFN: one forward pass
GP (Laplace), ℓ=0.50\ell = 0.50
GBDT: 30 depth-2 trees
  • Pr(y = 1) high: red; low: blue; 0.5: grey
  • point with y = 1
  • point with y = 0
Class of next point
Starting set
0.50
Pr(y = 1) at (0.60, 0.85): PFN…
GP…
GBDT…
Context points3
With 3 points, PFN and GP give probabilities near 0.5 far from the data and lean toward a class only nearby; GBDT instead splits the plane into nearly certain blocks. Mean difference from GP: PFN NaN, GBDT NaN.
Three models on the same training points, add or remove by clicking any map. Left: the previous cell's toy PFN (weights from that run), predicting in one forward pass without fitting parameters. Center: GP classifier with prior kernel, Laplace approximation and chosen scale ℓ\ell. Right: GBDT of 30 depth-2 trees with η=0.1\eta = 0.1. Color is P(y=1)\Pr(y = 1): red near 1, blue near 0, gray 0.5. Start with three points: what does each say far away? Add points, try XOR and overlapping classes, and move GP ℓ\ell to see when it resembles PFN.

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 ℓ\ell as input, PFN infers it from context because minimizing loss under variable-ℓ\ell 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 E[Y∣x]\E[Y \given \vb{x}] and nothing more. Risk decisions (capital reserves, alerts, intervals) need the full p(y∣x)p(y \given \vb{x}) 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 ϑ=(μ,s)\vartheta = (\mu, s) and s=log⁡σs = \log\sigma, one observation’s negative log-likelihood is

ℓ(μ,s;y)=s+12log⁡(2π)+(y−μ)22e2s,\ell(\mu, s; y) = s + \tfrac12\log(2\pi) + \frac{(y - \mu)^2}{2e^{2s}},

and its gradient,

∇ℓ=[−(y−μ)/σ21−(y−μ)2/σ2].\grad\ell = \begin{bmatrix} -(y - \mu)/\sigma^2 \\ 1 - (y - \mu)^2/\sigma^2 \end{bmatrix}.

Fisher information is I(ϑ)=Ey∼Pϑ[∇ℓ ∇ℓ⊤]\mathcal{I}(\vartheta) = \E_{y \sim P_\vartheta}[\grad\ell\,\grad\ell\T]. With z=(y−μ)/σ∼N(0,1)z = (y - \mu)/\sigma \sim \Normal(0, 1), components are E[z2]/σ2=1/σ2\E[z^2]/\sigma^2 = 1/\sigma^2, E[−(z/σ)(1−z2)]=0\E[-(z/\sigma)(1 - z^2)] = 0 (odd moments) and E[(1−z2)2]=1−2E[z2]+E[z4]=1−2+3=2\E[(1 - z^2)^2] = 1 - 2\E[z^2] + \E[z^4] = 1 - 2 + 3 = 2:

I(μ,s)=[1/σ2002],g~=I−1∇ℓ=[−(y−μ)12(1−(y−μ)2/σ2)].\mathcal{I}(\mu, s) = \begin{bmatrix} 1/\sigma^2 & 0 \\ 0 & 2 \end{bmatrix}, \qquad \tilde{\vb{g}} = \mathcal{I}^{-1}\grad\ell = \begin{bmatrix} -(y - \mu) \\ \tfrac12\big(1 - (y - \mu)^2/\sigma^2\big) \end{bmatrix}.

Compare directions. Ordinary gradient in μ\mu is residual divided by σ2\sigma^2: examples with small σ\sigma have huge gradients dominating the μ\mu tree fit even without more information. Natural gradient in μ\mu is simply residual, as in least-squares boosting. In ss natural is half ordinary, but the key is both parameters share statistical scale: I−1\mathcal{I}^{-1} is each direction’s natural step size. In other words the natural step is per-example Fisher scoring.

[ ]Normal Fisher information, symbolic and Monte CarloBrowser
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 ϑ=h(ψ)\vartheta = h(\psi) with invertible Jacobian J=∂ϑ/∂ψ\mat{J} = \partial\vartheta/\partial\psi, the chain rule gives ∇ψℓ=J⊤∇ϑℓ\grad_\psi\ell = \mat{J}\T\grad_\vartheta\ell and Fisher information transforms as Iψ=J⊤IϑJ\mathcal{I}_\psi = \mat{J}\T\mathcal{I}_\vartheta\mat{J}, so

g~ψ=Iψ−1∇ψℓ=J−1Iϑ−1J−TJ⊤∇ϑℓ=J−1g~ϑ.\tilde{\vb{g}}_\psi = \mathcal{I}_\psi^{-1}\grad_\psi\ell = \mat{J}^{-1}\mathcal{I}_\vartheta^{-1}\mat{J}^{-\mathsf T}\mat{J}\T\grad_\vartheta\ell = \mat{J}^{-1}\tilde{\vb{g}}_\vartheta.

A step −ϵg~ψ-\epsilon\tilde{\vb{g}}_\psi in ψ\psi moves ϑ\vartheta to first order by −ϵJg~ψ=−ϵg~ϑ-\epsilon\mat{J}\tilde{\vb{g}}_\psi = -\epsilon\tilde{\vb{g}}_\vartheta: the same distribution regardless of parametrization. Ordinary gradient induces displacement −ϵJJ⊤∇ϑℓ-\epsilon\mat{J}\mat{J}\T\grad_\vartheta\ell, 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 ϑ(0)=arg min⁡ϑ∑iS(ϑ,yi)\vartheta^{(0)} = \argmin_\vartheta \sum_i S(\vartheta, y_i) (for normal, mean and log standard deviation of yiy_i); each stage computes each example’s natural gradient, fits one regression tree per parameter, searches scale factor ρ(m)\rho^{(m)} (in practice starting at ρ=1\rho = 1 and halving until total loss decreases) and updates ϑi←ϑi−ηρ(m)f(m)(xi)\vartheta_i \leftarrow \vartheta_i - \eta\rho^{(m)}\vb{f}^{(m)}(\vb{x}_i). On UCI data the paper uses depth-3 trees, η=0.01\eta = 0.01 (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 xx: x∼Unif⁡[0,1]x \sim \Unif[0, 1], y∣x∼N(2sin⁡(2πx)+x, (0.1+0.9x2)2)y \given x \sim \Normal(2\sin(2\pi x) + x,\ (0.1 + 0.9x^2)^2). To fit in the browser use η=0.1\eta = 0.1 and at least 20 examples per leaf, choosing stage by validation.

[ ]Minimal NGBoost from scratchBrowser
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))
[ ]Ordinary gradient, constant variance and truthBrowser
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:

modelNLLCRPS90% interval coverage
NGBoost, natural gradient0.3260.23450.899
NGBoost, ordinary gradient0.3820.23610.895
GBDT + constant σ\sigma (σ=0.511\sigma = 0.511)0.7260.26190.904
true distribution0.2650.22750.897

True distribution expected NLL is ∫01log⁡σ(x) ⁣dx+12log⁡(2πe)=0.2516\int_0^1 \log\sigma(x)\dd x + \tfrac12\log(2\pi e) = 0.2516; table 0.2650.265 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 (0.9040.904) despite worst NLL: its interval is too wide where σ(x)\sigma(x) 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 yy, dominated by mean error, it penalizes spread error less (see continuous prediction scoring). Predicted σ\sigma at x=0.1x = 0.1, 0.50.5 and 0.90.9 is 0.1230.123, 0.3590.359 and 0.6120.612 versus true 0.1090.109, 0.3250.325 and 0.8290.829: noisy right end remains incompletely fitted by early stopping.

InteractiveNatural versus ordinary gradient
NGBoost prediction at stage 1: mean and central 90% interval
Mean test NLL versus stage (the true distribution has expected NLL 0.252)
  • natural gradient
  • ordinary gradient
  • truth: mean and 5th and 95th percentiles
Gradient
1
Test NLLNaN
Test CRPSNaN
90% interval coverageNaN %
GBDT with constant σ: NLL, CRPS…
Calculating…
The cell's model trained in your browser on 1000 examples (gray), 500 validation and 2000 test: depth-3 trees, at least 20 examples per leaf, exact thresholds, η=0.1\eta = 0.1, ρ\rho line search and 200 stages. Above, predicted mean and central 90% interval (μ±1.645σ\mu \pm 1.645\sigma) at selected stage, truth dashed. Below, test NLL per stage for both gradients, least-squares GBDT with constant σ\sigma (estimated from validation residuals), and true distribution. Start at best natural stage and advance: what happens to the band at x≈0.5x \approx 0.5? Switch to ordinary gradient and compare right-band opening.

Three observations. Constant-σ\sigma GBDT band is equally wide at x=0x = 0, noise 0.10.1, and x=1x = 1, noise 11: too wide left and too narrow right, penalized by NLL. NGBoost follows σ(x)\sigma(x). Running beyond validation optimum makes test NLL rise again: μ\mu trees fit noise, training residuals shrink and ss 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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 λ\lambda, with early stopping on a 20% inner holdout and full-fold retraining with tree count scaled by 1/0.81/0.8.
  • 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 tt 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.

[ ]Tabular benchmark: GBDT, MLP, TabPFN and NGBoost with nested CVLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with 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:

datasettuned LightGBMdefault LightGBMtuned MLPTabPFN v2NGBoost
blood-transfusion0.5010.5810.5000.4840.508
diabetes0.5040.6250.5260.4760.531
qsar-biodeg0.3460.4410.3840.3260.416

Mean rank with its interval would be the study conclusion; with three datasets bootstrap intervals mean little (TabPFN first in all, rank 1.001.00; tuned LightGBM 2.332.33; MLP 2.672.67; NGBoost 4.004.00; default LightGBM 5.005.00). 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 (0.0170.017 to 0.0290.029) are of the order of seed variation, so the full five-seed tt 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 0.6250.625 to 0.5040.504. With about 400 training examples per fold, 100 31-leaf trees without stopping at η=0.1\eta = 0.1 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

QuizWhat hurts trees
In Grinsztajn et al. (2022), which training transformations hurt trees more than MLPs? Select all.

More than one answer may be correct.

QuizEquivariance assumptions
You train one MLP on data and another with the same recipe on data rotated by a fixed orthogonal matrix. Which recipes can make the learned-function distribution cease to be the rotated original? Select all.

More than one answer may be correct.

ProofFisher and the normal natural gradient
Prove: For a normal parametrized by ϑ=(μ,s)\vartheta = (\mu, s) with s=log⁡σs = \log\sigma, negative-log-likelihood Fisher information is I(μ,s)=diag⁡(1/σ2,2)\mathcal{I}(\mu, s) = \diag(1/\sigma^2, 2) and natural gradient g~=(−(y−μ), 12(1−(y−μ)2/σ2))\tilde{\vb{g}} = \big({-(y - \mu)},\ \tfrac12(1 - (y - \mu)^2/\sigma^2)\big).
0
Write ℓ(μ,s;y)=s+12log⁡(2π)+(y−μ)2/(2e2s)\ell(\mu, s; y) = s + \tfrac12\log(2\pi) + (y - \mu)^2/(2e^{2s}) and z=(y−μ)/σz = (y - \mu)/\sigma, which under the model is N(0,1)\Normal(0, 1).

Step 1 of 5. What is ∇ϑℓ\grad_\vartheta \ell?

NumericA natural step
For observation y=3y = 3 with current prediction μ=1\mu = 1, σ=0.5\sigma = 0.5, what is the s=log⁡σs = \log\sigma component of NLL natural gradient?
CodeThe normal natural gradient
Implement 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 N(μ,σ2)\Normal(\mu, \sigma^2) with respect to (μ,log⁡σ)(\mu, \log\sigma) per example. Tests compare the analytic expression, check I(ϑ) g~\mathcal{I}(\vartheta)\,\tilde{\vb{g}} matches the finite-difference gradient, and that if yy follows the model, natural gradient has zero mean and covariance I−1\mathcal{I}^{-1}.
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 g
Shift+Enter to run
QuizWhy a PFN works
TabPFN pretrains only on synthetic datasets and has never seen your data. Why can it predict well on a real dataset?
QuizA suspicious benchmark
A paper claims its tabular network beats XGBoost on 20 of 30 datasets. XGBoost used defaults; the network got 100 hyperparameter trials with validation per dataset. What is the main problem?
QuizRanks change while results do not
A benchmark compares A, B and C across 20 datasets using mean rank. A beats B on 12 datasets and B beats A on 8. Add two A variants differing only by seed, close to A in each dataset. What happens to B's mean rank?
NumericCost of attention among examples
In a TabPFN v2 layer, attention among a column's training examples costs O(n2)\bigO(n^2) in example count nn. Going from n=1000n = 1000 to n=10 000n = 10\,000 examples, by what factor does cost multiply?

Summary

Key idea
On tabular data trees win because their inductive bias (one-feature splits, indifference to useless columns, jump representation) matches irregular targets, uninformative columns and meaningful axes. Models learning that bias from a synthetic prior and predicting in context change the frontier, with their own size and cost limits.
  • 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 I−1∇S\mathcal{I}^{-1}\grad S; for the normal in (μ,log⁡σ)(\mu, \log\sigma), I=diag⁡(1/σ2,2)\mathcal{I} = \diag(1/\sigma^2, 2), 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.