import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
device = ("cuda" if torch.cuda.is_available()
else "mps" if torch.backends.mps.is_available() else "cpu")
print("device:", device)
# Three fixed test datasets, never seen in pretraining: 40 labeled + 200 hold-out points each.
TEST_BOUNDARIES = {
"line": lambda t: 0.2 - 0.3 * t,
"sine wave": lambda t: 1.0 + 0.5 * t + 1.5 * torch.sin(1.5 * t),
"sine + fast wave": lambda t: -0.5 + 0.5 * t + 1.2 * torch.sin(4 * t),
}
def make_test_set(boundary, n_train=40, n_test=200, seed=0):
gen = torch.Generator().manual_seed(seed)
x1 = 4 * torch.rand(n_train + n_test, generator=gen) - 2 # x1 ~ U(-2, 2)
x2 = boundary(x1) + torch.randn(n_train + n_test, generator=gen)
x, y = torch.stack([x1, x2], dim=-1), (x2 > boundary(x1)).float()
return x[:n_train], y[:n_train], x[n_train:], y[n_train:]
TEST_SETS = {name: make_test_set(f, seed=i)
for i, (name, f) in enumerate(TEST_BOUNDARIES.items())}
@torch.no_grad()
def predict_proba(model, x_train, y_train, x_test):
'''P(class 1) for every test row, from a single forward pass.'''
logits = model(x_train[None].to(device), y_train[None].to(device),
x_test[None].to(device))
return logits.softmax(-1)[0, :, 1].cpu()
def accuracies(model):
return {name: ((predict_proba(model, xtr, ytr, xte) > 0.5).float() == yte)
.float().mean().item() for name, (xtr, ytr, xte, yte) in TEST_SETS.items()}
def evaluate_model(model):
'''Mean hold-out accuracy over the three test datasets.'''
return float(np.mean(list(accuracies(model).values())))
def _scatter(ax, x, y, size=30):
ax.scatter(*x[y == 1].T, c="red", edgecolors="white", s=size, label="class 1")
ax.scatter(*x[y == 0].T, c="blue", marker="x", s=size, label="class 0")
def plot_prior_samples(x, y, boundary):
'''One panel per synthetic table, with its true boundary dashed.'''
n = len(x)
lo, hi = x[..., 0].min(1).values[:, None], x[..., 0].max(1).values[:, None]
t = lo + (hi - lo) * torch.linspace(0, 1, 200) # per-table x1 range
curves = boundary(t)
fig, axes = plt.subplots(1, n, figsize=(3.2 * n, 3.4))
for i, ax in enumerate(np.atleast_1d(axes)):
_scatter(ax, x[i], y[i], size=12)
ax.plot(t[i], curves[i], "k--", lw=1)
ax.set_ylim(x[i, :, 1].min() - 0.3, x[i, :, 1].max() + 0.3)
ax.set_title(f"table {i}", fontsize=10)
ax.set_xticks([]); ax.set_yticks([])
fig.suptitle("Synthetic tables sampled from the prior "
"(x1 vs x2, colored by class, dashed: boundary)")
plt.tight_layout(); plt.show()
def plot_predictions(model):
'''Predicted P(class 1) over the plane for each test dataset.'''
levels = [0, 0.1, 0.25, 0.4, 0.6, 0.75, 0.9, 1]
fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
for ax, (name, (xtr, ytr, xte, yte)) in zip(axes, TEST_SETS.items()):
x_all = torch.cat([xtr, xte])
g1, g2 = torch.meshgrid(
torch.linspace(-2, 2, 150),
torch.linspace(x_all[:, 1].min() - 0.5, x_all[:, 1].max() + 0.5, 150),
indexing="xy")
grid = torch.stack([g1.ravel(), g2.ravel()], dim=-1)
p = predict_proba(model, xtr, ytr, grid).reshape(g1.shape)
cs = ax.contourf(g1, g2, p, levels=levels, cmap="RdBu_r", alpha=0.8)
t = torch.linspace(-2, 2, 200)
ax.plot(t, TEST_BOUNDARIES[name](t), "k--", lw=1, label="true boundary")
_scatter(ax, xtr, ytr)
ax.set_xlim(-2, 2); ax.set_ylim(g2.min(), g2.max())
ax.set_title(name); ax.set_xlabel("x1")
axes[0].set_ylabel("x2")
axes[0].legend(loc="lower right", fontsize=8)
fig.colorbar(cs, ax=axes, label="P(class 1)")
fig.suptitle(f"nanoTabPFN predicted class probabilities (white = unsure), "
f"with the {len(xtr)} labeled points as context")
plt.show()
def compare_with_baseline(models):
'''Hold-out accuracy table: our models vs. two classic baselines.'''
rows = {name: accuracies(m) for name, m in models.items()}
for name, clf in [("logistic regression", LogisticRegression()),
("random forest", RandomForestClassifier(random_state=0))]:
rows[name] = {ds: clf.fit(xtr.numpy(), ytr.numpy()).score(xte.numpy(), yte.numpy())
for ds, (xtr, ytr, xte, yte) in TEST_SETS.items()}
cols = list(TEST_SETS) + ["mean"]
print(f"{'accuracy':<20}" + "".join(f"{c:>{len(c) + 3}}" for c in cols))
print("-" * (20 + sum(len(c) + 3 for c in cols)))
for name, acc in rows.items():
vals = list(acc.values()) + [np.mean(list(acc.values()))]
print(f"{name:<20}" + "".join(f"{v:>{len(c) + 3}.3f}" for c, v in zip(cols, vals)))