TabPFN: a network trained to predict from context
TabPFN is pretrained on many synthetic tables, then predicts a new table's rows by reading its training rows as context. Compute the posterior-predictive target it imitates, run it on penguins and Pima, and see where its limits are.
What runs in CodeSplash
- SPE004TabPFN family Runs in CodeSplash (Experimental)
- TabPFN v2 (pretrained tabular model) Experimental
You will be able to
- State the posterior-predictive target a prior-fitted network is trained to approximate
- Compute a two-hypothesis posterior and the prediction it implies
- Tell context-based prediction apart from gradient fine-tuning
- Check TabPFN's probabilities and compare it fairly with trees
Training on tables that never existed
ReadMost learners fit their weights to your table. TabPFNTabPFNA transformer pretrained on synthetic tables that predicts small tables in context, without training on them. fits nothing at prediction time. During pretraining it saw a huge stream of synthetic tables drawn from a prior over data-generating processes, and for each it learned to predict held-out rows from the labeled rows:
On your table, the labeled rows become the context and the network outputs predictions for the query rows in one pass: in-context learningIn-context learningPredicting from examples given with the question, with no weights changed; TabPFN reads the training rows this way..
Reference · SPE004 · Runs in CodeSplashTabPFN familyTabPFN amortizes prediction over a distribution of synthetic tabular tasks. A pretrained network conditions on labeled training rows and query rows, producing task predictions without necessarily optimizing its weights…The target it imitates
ReadIf the pretraining succeeds, approximates the posterior predictive distributionPosterior predictive distributionThe distribution of new data the model expects after seeing yours: parameter uncertainty plus outcome noise. under its prior:
The reference computes this by hand for two hypotheses . Two labeled rows move an even prior to a posterior of 0.8 and 0.2. A query row that the hypotheses label positive with probabilities and then gets 0.62. TabPFN learns to produce answers like this for any table, without doing the integral.
import numpy as np
prior = np.array([.5, .5]); y = np.array([0, 1])
p_train = np.array([[.2, .8], [.6, .4]]) # P(y=1) for each row, under each hypothesis
lik = np.prod(np.where(y == 1, p_train, 1 - p_train), axis=1)
post = prior * lik / (prior * lik).sum()
print(post, post @ np.array([.7, .3])) # posterior, query probabilityprior <- c(.5, .5); y <- c(0, 1)
p_train <- rbind(c(.2, .8), c(.6, .4)) # P(y=1) for each row, under each hypothesis
lik <- apply(p_train, 1, function(p) prod(ifelse(y == 1, p, 1 - p)))
post <- prior * lik / sum(prior * lik)
print(c(post, sum(post * c(.7, .3)))) # posterior, query probabilityTabPFN on penguins
ExploreTabPFN v2 (pretrained tabular model): cross-validated log loss 0.030 ± 0.026 over 3 folds; log loss on the locked test set 0.010 (n = 69).
- CV log loss
- 0.0300
- SD across folds
- 0.0262
- Test log loss
- 0.0103
Cross-validation
| Fold | Repeat | n | log loss | accuracy | balanced accuracy | F1 |
|---|---|---|---|---|---|---|
| 1 | 1 | 92 | 0.0366 | 0.9891 | 0.9899 | 0.9909 |
| 2 | 1 | 92 | 0.0012 | 1 | 1 | 1 |
| 3 | 1 | 91 | 0.0523 | 0.9890 | 0.9917 | 0.9868 |
- Built with PriorLabs-TabPFN: TabPFN v2 pretrained weights (Prior Labs), Prior Labs License 1.1 (Apache-2.0 with an attribution requirement).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TabPFN v2 (pretrained tabular model)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tabpfn 1.0.0 · spec fa6f965a0b7943fb
# Dataset: ml_penguins (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import tabpfn as cstabpfn # TabPFN v2 (tabpfn package, v2 weights from the local store only)
# %% Data and split plan
TARGET = "species"
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
TASK = "multiclass"
CLASSES = ["Adelie", "Chinstrap", "Gentoo"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
"n_estimators": 2,
"softmax_temperature": 0.9,
"balance_probabilities": False,
"ignore_pretraining_limits": False,
}
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-88684/learn.tabpfn/multiclass_penguins/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"island": "categorical",
"bill_len": "numeric",
"bill_dep": "numeric",
"flipper_len": "numeric",
"body_mass": "numeric",
"sex": "categorical",
},
levels={
"island": ["Biscoe", "Dream", "Torgersen"],
"sex": ["female", "male"],
},
impute="none",
scale="none",
indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("target/academy-parity/run-88684/learn.tabpfn/multiclass_penguins/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
# TabPFN v2: a transformer pretrained on synthetic tables that predicts from the training rows in context, without
# training on them. Python only (no R package runs the weights). The v2 weights must already be on this computer;
# the app downloads them only after you agree, and nothing is fetched here. Built with PriorLabs-TabPFN.
def fit_model(X, y, w):
if w is not None and not np.allclose(w, w[0]):
warnings.append("TabPFN doesn't use row weights; class weights were left out.")
return cstabpfn.fit(
X, y, TASK, len(CLASSES),
target=TARGET,
n_estimators=int(PARAMS["n_estimators"]),
softmax_temperature=PARAMS["softmax_temperature"],
balance_probabilities=bool(PARAMS["balance_probabilities"]),
ignore_limits=bool(PARAMS["ignore_pretraining_limits"]),
seed=SEED,
)
def predict_model(model, X):
return cstabpfn.predict(model, X)
def feature_importance(model, names):
return None
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path)
return [{"key": "model", "path": path, "format": "joblib"}]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
cstabpfn.extend(run.result(
title="TabPFN v2 (pretrained tabular model)",
engine=cs.engine_info("tabpfn", "torch", "codesplash", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
), model, names)
)
With 275 training rows as context and two ensemble members, TabPFN reaches a cross-validated accuracy of 99.3% and a log loss of 0.030. No weights changed: "fitting" here prepared the context and the preprocessing.
Penguins is small and clean, close to what TabPFN's prior favors. Its limits on rows, columns and classes come from pretraining, so they depend on the checkpoint version.
Probabilities still need checking
ExploreTabPFN v2 (pretrained tabular model): cross-validated ROC AUC 0.860 ± 0.043 over 3 folds; ROC AUC on the locked test set 0.828 (n = 106).
- CV ROC AUC
- 0.8597
- SD across folds
- 0.0428
- Test ROC AUC
- 0.8278
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 142 | 0.8920 | 0.4247 | 0.8169 | 0.7772 |
| 2 | 1 | 142 | 0.8112 | 0.7012 | 0.7324 | 0.7355 |
| 3 | 1 | 142 | 0.8759 | 0.4536 | 0.8099 | 0.7952 |
- Built with PriorLabs-TabPFN: TabPFN v2 pretrained weights (Prior Labs), Prior Labs License 1.1 (Apache-2.0 with an attribution requirement).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TabPFN v2 (pretrained tabular model)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tabpfn 1.0.0 · spec 385a18838b71cda7
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import tabpfn as cstabpfn # TabPFN v2 (tabpfn package, v2 weights from the local store only)
# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
"n_estimators": 1,
"softmax_temperature": 0.5,
"balance_probabilities": True,
"ignore_pretraining_limits": False,
}
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-88684/learn.tabpfn/binary_pima_balanced/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"npreg": "numeric",
"glu": "numeric",
"bp": "numeric",
"skin": "numeric",
"bmi": "numeric",
"ped": "numeric",
"age": "numeric",
},
levels={
},
impute="none",
scale="none",
indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("target/academy-parity/run-88684/learn.tabpfn/binary_pima_balanced/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
# TabPFN v2: a transformer pretrained on synthetic tables that predicts from the training rows in context, without
# training on them. Python only (no R package runs the weights). The v2 weights must already be on this computer;
# the app downloads them only after you agree, and nothing is fetched here. Built with PriorLabs-TabPFN.
def fit_model(X, y, w):
if w is not None and not np.allclose(w, w[0]):
warnings.append("TabPFN doesn't use row weights; class weights were left out.")
return cstabpfn.fit(
X, y, TASK, len(CLASSES),
target=TARGET,
n_estimators=int(PARAMS["n_estimators"]),
softmax_temperature=PARAMS["softmax_temperature"],
balance_probabilities=bool(PARAMS["balance_probabilities"]),
ignore_limits=bool(PARAMS["ignore_pretraining_limits"]),
seed=SEED,
)
def predict_model(model, X):
return cstabpfn.predict(model, X)
def feature_importance(model, names):
return None
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path)
return [{"key": "model", "path": path, "format": "joblib"}]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
cstabpfn.extend(run.result(
title="TabPFN v2 (pretrained tabular model)",
engine=cs.engine_info("tabpfn", "torch", "codesplash", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
), model, names)
)
On Pima with a sharper temperature and balanced probabilities, the AUC is 0.860 and the Brier score 0.158. Balancing changes what the probabilities mean: they no longer match the base rate.
Matching a posterior predictive under the pretraining prior is not calibration on your data. Check a reliability curve on held-out rows before you use the probabilities.
HExplorable · Calibration and reliability
When a model says 80%, does the event happen 80% of the time?
If you make the model more overconfident, what happens to its AUC?
Above 1 the model is too extreme; below 1 it hedges. At 1 it is perfectly calibrated.
| Brier | ECE | Calibration slope | AUC |
|---|---|---|---|
| 0.175 | 0.087 | 0.50 | 0.835 |
Commit your prediction above to see the result
Make your prediction to see the result.
Calibration claims rest on the binning: see how bin count and one temperature change the ECE.
HExplorable · How many bins? ECE and temperature scaling
The expected calibration error depends on how you bin. How much of a model's ECE is the bins talking, and can one temperature fix the model?
Score a perfectly calibrated model with these bins on these rows. What ECE will it get?
The model's logits are this many times the truth's. Same model as Calibration and reliability.
Half the rows fit the temperature; the other half score every ECE.
More bins see finer miscalibration but hold fewer rows each.
Bin edges
Equal-width bins split [0, 1] evenly; equal-count bins put the same number of predictions in each.
Blue dots are sized by how many rows fall in the bin. Gray dots are a perfectly calibrated model on the same rows: their distance from the diagonal is pure sampling noise, and it sets a floor under any calibration error you compute with these bins.
Commit your prediction above to see the result
Make your prediction to see the result.
Context or training?
PredictPredict first
You press Run on TabPFN in Predict. What does its fitting step do?
Reveal
It builds the context. The weights are fixed from pretraining. Some versions also offer gradient fine-tuning; that is a separate step with its own learning rate and risks, and you should report which one you used.
What runs here
ReadCheck: prior-fitted networks
CheckpointCheck yourself
What is a prior-fitted network trained to approximate?
Show the answer
Answer: b
Pretraining minimizes the expected negative log-likelihood over tables drawn from the prior, which targets that prior's posterior predictive.
Check yourself
Two hypotheses have posterior probabilities and . They give a query row a positive label with probabilities and . What is the posterior-predictive probability of a positive label?
Show the answer
Answer: 0.6199999999999999
Average the predictions, weighted by the posterior: .
Check yourself
In TabPFN's default use, what changes when you give it a new table?
Show the answer
Answer: a
Prediction is a forward pass over context plus queries. Gradient fine-tuning, where a version offers it, is a different workflow.
Check yourself
Does approximating a posterior predictive make TabPFN's probabilities calibrated on your data?
Show the answer
Answer: b
Calibration is a property on your data. Check a reliability curve and a proper score on held-out rows.
Check yourself
Your table has several rows per patient. How should TabPFN be evaluated?
Show the answer
Answer: b
Group and time leakage matter as much here as for any learner: a query patient's other rows in the context would inflate the score.
Recap
Recap- TabPFN is pretrained on synthetic tables to approximate a posterior predictive under its prior.
- On your table the labeled rows are context; the weights don't change.
- Check probabilities and evaluate with leakage-safe folds against tuned trees.
- It runs in CodeSplash in Python only, after a weights download.
Concepts in this lesson