MarkTechPost新闻
如何使用 NVIDIA 结构化数据模型进行零训练表格预测
本文介绍如何使用 NVIDIA 新发布的 Structured Data Models 库,通过 PyTorch 接口调用 TabICLv2、KumoTabular 和 KumoRelational 等预训练基础模型。该库利用上下文学习(in-context learning)技术,无需重新训练即可对单表或关系型数据库进行预测。教程展示了具体的实现步骤,旨在帮助开发者快速上手这一零样本预测工具。
在本教程中,我们实现了结构化数据模型(Structured Data Models),这是 NVIDIA 推出的新库,它将多个用于表格数据的预训练基础模型封装在一个 PyTorch 接口背后,并用于无需训练即可进行预测。该库将 TabICLv2 和 KumoTabular 用于单张表格,将 KumoRelational 用于整个关系数据库,且每个模型都通过上下文学习(in-context learning)给出答案:我们将一组带标签的行以及需要预测的行交给模型,它便在一次前向传播中返回概率或完整的预测分布。我们从库的带类型表张量开始,将两种表格模型与经过训练的 scikit-learn 基线模型进行比较,在多次查询中复用编码后的上下文,从回归任务中提取校准后的预测区间,并扩展至二十个类别的场景。随后,我们审视那些默认设置悄然出错的地方:一种会丢弃时间戳和文本列的预处理方案,以及一个包含两个陷阱的解释器;在此基础上,我们构建了一个小型的三表商店数据库,并直接从中预测客户活动,其中包括区分诚实的关系型模型与存在数据泄露风险的模型的关键论点。请在此处查看完整代码。
import os import sys import time import textwrap import traceback import subprocess
RESULTS = {}
def banner(title): print("\n" + "=" * 78) print(title) print("=" * 78)
def section(name): def wrap(fn): def run(*a, **kw): banner(name) try: out = fn(*a, **kw) RESULTS[name] = out if isinstance(out, str) else "ok" return out except Exception as e: RESULTS[name] = f"SKIPPED / FAILED -> {type(e).__name__}: {e}" print(f"\n[!] {name} did not complete: {type(e).__name__}: {e}") traceback.print_exc(limit=3) return None return run return wrap

banner("1. Install SDM, and the one wheel URL its own error message gets wrong") subprocess.run([sys.executable, "-m", "pip", "install", "-q", "git+https://github.com/NVIDIA/structured-data-models.git@b982fbf4188ea8db17249fe81338723106100b63"], check=True)
import torch
# The relational sampler needs pyg-lib on CPU. Its wheels are published per MINOR torch version # (torch-2.14.0+cpu.html), but SDM's own ImportError builds the URL from the exact patch version # (torch-2.14.1+cpu.html), which is an empty page. Build it from MAJOR.MINOR.0 instead. major, minor = torch.__version__.split("+")[0].split(".")[:2] flavour = "cpu" if torch.version.cuda is None else "cu" + torch.version.cuda.replace(".", "") PYG_INDEX = f"https://data.pyg.org/whl/torch-{major}.{minor}.0+{flavour}.html" subprocess.run([sys.executable, "-m", "pip", "install", "-q", "pyg-lib", "-f", PYG_INDEX], check=True)
import numpy as np import pandas as pd import pyg_lib import sdm import sdm.processing as sp from sklearn.datasets import load_breast_cancer, load_diabetes, make_classification from sklearn.ensemble import HistGradientBoostingClassifier, HistGradientBoostingRegressor from sklearn.linear_model import LogisticRegression, RidgeCV from sklearn.metrics import roc_auc_score from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler
DEVICE = "cpu" # verified end to end on CPU; on a T4 runtime set "cuda" for the tabular models print(f" sdm {sdm.__version__} | torch {torch.__version__} | pyg-lib {pyg_lib.__version__}" f" | device {DEVICE}") print(f" pyg-lib wheels from {PYG_INDEX}") print("\n One interface over several pretrained structured-data foundation models:") for name, what, weights in [ ("TabICLv2", "tabular, in-context learning (ICML '26)", "~110 MB per task head, BSD-3"), ("KumoTabular", "tabular, small / medium / large", "small ~110 MB, large ~855 MB, OpenMDW"), ("KumoRelational", "multi-table, KumoRFM-2", "~120 MB, OpenMDW"), ("TabFM, TimesFM 3", "Google tabular / time series", "6.5 GB / 1.3 GB, non-commercial: not used here"), ]: print(f" {name:18s} {what:42s} {weights}") print("\n No model below is trained or fine-tuned. Every prediction is a forward pass that reads") print(" labelled 'context' rows and answers 'query' rows, like a prompt with examples in it.")
我们从 GitHub 仓库安装结构化数据模型(Structured Data Models),并固定到本笔记本验证时所使用的提交版本,因为 PyPI 上的软件包仅是一个占位符。关系采样器还需要 pyg-lib,而第一个陷阱就在这里。pyg-lib 的轮子(wheels)是按 PyTorch 的小版本发布的,页面名称类似于 torch-2.14.0+cpu,但该库自身的 ImportError 会从确切的补丁版本构建 URL,即 torch-2.14.1+cpu,这是一个空页面,因此遵循其建议会失败。我们改为从主版本和小版本构建索引 URL。我们在 CPU 上运行所有内容,这是此处端到端验证的路径,并打印该库提供的模型及其检查点大小和许可证;它还包装的两个 Google 模型 TabFM 和 TimesFM 3 体积庞大且仅限非商业用途,因此被排除在外。请在此处查看完整代码。
@section("2. 类型化表:infer_stypes 决定了什么,以及往返转换改变了什么") def typed_tables(): rng = np.random.default_rng(0) words = ["late", "refund", "great", "broken", "fast", "charged", "app", "order", "support", "item"] df = pd.DataFrame({ "ticket_id": np.arange(400), "amount": rng.gamma(2, 30, 400).round(2), "units": pd.array(rng.integers(1, 5, 400), dtype="Int64"), "channel": rng.choice(["web", "app", "phone", None], 400), "opened_at": pd.Timestamp("2026-01-01") + pd.to_timedelta(rng.integers(0, 86_400 * 90, 400), unit="s"), "comment": [" ".join(rng.choice(words, rng.integers(3, 9))) + f" #{i}" for i in range(400)], }) df.loc[rng.choice(400, 25, replace=False), "units"] = pd.NA
print(" 使用默认值调用 infer_stypes(df),然后要求它查找文本和 ID:") for kw in ({}, {"text": "infer", "id": "infer"}): stypes = sdm.infer_stypes(df, **kw) print(f" {str(kw or 'defaults'):34s} {', '.join(f'{c}={s}' for c, s in stypes.items())}") print(" 使用默认值时,自由文本注释变为 400 级分类变量,ID 列变为数字。两者都会作为特征传递给模型。请覆盖或指定:text='infer', id='infer'。")
table = sdm.TableTensor.from_pandas(df, sdm.infer_stypes(df, text="infer", id="infer")) print("\n" + textwrap.indent(repr(table), " "))
back = table.to_pandas() print("\n to_pandas() 往返转换:") for col in df.columns: a, b = df[col], back[col] if col in ("amount", "units"): equal_values = bool(np.allclose(a.astype(float), b.astype(float), equal_nan=True)) else: na_a, na_b = a.isna().to_numpy(), b.isna().to_numpy() equal_values = bool((na_a == na_b).all() and (a[~na_a].astype(str).to_numpy() == b[~na_b].astype(str).to_numpy()).all()) print(f" {col:10s} {str(a.dtype):16s} -> {str(b.dtype):16s} values preserved: {equal_values}") print(" 值得以保留,包括缺失值;但数据类型并不总是如此。数字返回为 float32") print(" (数值块是一个 float 张量),可空 Int64 变为带有 NaN 的 float,而标记为分类的字符串") print(" 则返回为 pandas category。")
base = pd.to_datetime(["2026-01-01 08:00:00"] * 3).as_unit("ns") whole = pd.DataFrame({"t": base}) nanos = pd.DataFrame({"t": base + pd.to_timedelta([0, 0, 1], unit="ns")}) print(f"\n datetime64[ns],整秒: {sdm.TableTensor.from_pandas(whole, {'t': 'datetime'}).size()} OK") try: sdm.TableTensor.from_pandas(nanos, {"t": "datetime"}) except Exception as e: print(f" 同一列,一个值晚 1 纳秒: {type(e).__name__}: {str(e).split(':')[0]}") ok = sdm.TableTensor.from_pandas(nanos.assign(t=nanos.t.dt.floor("us")), {"t": "datetime"}) print(f" 先 floor('us'): {ok.size()} OK") print(" SDM 将日期时间存储为 int64 微秒,Arrow 拒绝任何会丢失数字的转换。问题不在于单位;单个包含纳秒数字的值会导致整个列失败。") return "6 列 -> 5 个类型化块;文本和 ID 需要显式选择"
typed_tables()
库中的所有数据都通过 TableTensor 流动,这是一个 PyTorch 张量子类,它为每种语义类型(数值、分类、日期时间、文本和 ID)保留一个已类型的块。infer_stypes 负责决定类型,但在处理现实的支持工单框架时,其默认设置会出错:自由文本评论变成了具有四百个级别的分类变量,而工单 ID 变成了数字,因此两者都会作为特征进入模型。传递文本和 ID 推断标志可以修复这个问题。往返转换回 pandas 会保留所有值(包括缺失值),但并非所有数据类型都能保留:由于数值块是单个浮点张量,数字返回为 float32;可空整数变为带有 NaN 的浮点数;分类字符串返回为 pandas category。在 pandas 2.x 中,字符串列显示为 object 而非 str,时间戳以纳秒精度输入;无论哪种方式,相同的值都会返回。在加载真实事件日志之前,还有一个陷阱值得注意:库将日期时间存储为整数微秒,而 Arrow 拒绝任何会丢失数字的转换。整秒的纳秒列可以正常转换,但包含纳秒数字的单个值会导致整个列失败,因此我们首先将时间戳向下取整到微秒。在此处查看完整的 CODES。
def as_table(df, target):
return sdm.TableTensor.from_pandas(df, sdm.infer_stypes(df, overrides={target: "categorical"}), device=DEVICE)
@section("3. Zero-training classification: two foundation models vs. two trained baselines")
def zero_training():
df = load_breast_cancer(as_frame=True).frame.sample(frac=1, random_state=0).reset_index(drop=True)
table = as_table(df, "target")
n_ctx = 300
x_ctx, y_ctx = table[:n_ctx].drop_columns("target"), table[:n_ctx, "target"]
x_q, y_q = table[n_ctx:].drop_columns("target"), df.target.to_numpy()[n_ctx:]
rows = []
for name, make in [("TabICLv2", lambda: sdm.models.TabICLv2(device=DEVICE)),
("KumoTabular (small)", lambda: sdm.models.KumoTabular(size="small", device=DEVICE))]:
model = make()
torch.manual_seed(0)
proba = model(x_context=x_ctx, y_context=y_ctx, x_query=x_q, num_estimators=4).to_pandas()
rows.append((name, "none", proba.idxmax(axis=1).astype(int).to_numpy(), proba["1"].to_numpy()))
X, y = df.drop(columns="target"), df.target
for name, est in [("LogisticRegression", make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))),
("HistGradientBoosting", HistGradientBoostingClassifier(random_state=0))]:
est.fit(X[:n_ctx], y[:n_ctx])
rows.append((name, "fit on 300 rows", est.predict(X[n_ctx:]), est.predict_proba(X[n_ctx:])[:, 1]))
print(f" breast cancer: {n_ctx} labelled rows, {len(y_q)} to predict, 30 numeric features\n")
print(f" {'model':22s} {'training':16s} {'accuracy':>9s} {'AUC':>7s}")
for name, training, pred, score in rows:
print(f" {name:22s} {training:16s} {np.mean(pred == y_q):9.3f} {roc_auc_score(y_q, score):7.3f}")
print("\n The output is itself a TableTensor: one probability column per class, named by label.")
best = max(rows[:2], key=lambda r: np.mean(r[2] == y_q))
return f"{best[0]} {np.mean(best[2] == y_q):.3f} accuracy with no training"
zero_training()表格模型接受带标签的上下文行和未标记的查询行,并返回一个 TableTensor,其中每个类别都有一个概率列,以标签命名,因此没有拟合步骤,也没有超参数。在乳腺癌数据集上,使用三百个带标签的行和二百六十九个待预测的行,TabICLv2 和 KumoTabular 在不进行训练的情况下达到了 0.970 的准确率和 0.996、0.995 的 AUC 值,而逻辑回归为 0.970 和 0.993,梯度提升为 0.967 和 0.992,两者均在相同的三百行上进行拟合。num_estimators 设置模型平均处理的不同预处理数据视图的数量,这是库内置的集成方法。
@section("4. fit() once, predict() many: the cached context")
def kv_cache():
df = load_breast_cancer(as_frame=True).frame.sample(frac=1, random_state=0).reset_index(drop=True)
table = as_table(df, "target")
x_ctx, y_ctx = table[:400].drop_columns("target"), table[:400, "target"]
batches = [table[400 + 30 * i: 430 + 30 * i].drop_columns("target") for i in range(5)]
model = sdm.models.TabICLv2(device=DEVICE)
torch.manual_seed(0)
t0 = time.time()
for b in batches:
model(x_context=x_ctx, y_context=y_ctx, x_query=b, num_estimators=4)
t_forward = time.time() - t0
torch.manual_seed(0)
t0 = time.time()
model.fit(x=x_ctx, y=y_ctx, num_estimators=4)
t_fit = time.time() - t0
t0 = time.time()
for b in batches:
model.predict(b)
t_predict = time.time() - t0
model.clear()
print(" five batches of 30 query rows against the same 400 context rows:")
print(f" forward() x5 {t_forward:6.2f}s (context re-encoded every call)")
print(f" fit() once + predict() x5 {t_fit + t_predict:6.2f}s (fit {t_fit:.2f}s, predicts {t_predict:.2f}s)")
print(f" per batch: {t_forward / 5:.2f}s vs {t_predict / 5:.2f}s")
print("\n fit() encodes the context once into a key/value cache; predict() only runs the queries.")
print(" clear() frees it. Nothing is learned: fit() here means 'remember these examples'.")
return f"{t_forward / (t_fit + t_predict):.1f}x faster for five batches"
kv_cache()直接调用模型会在每次调用时重新编码上下文。当相同的带标签行需要回答多批查询时,fit 将上下文编码一次存入键值缓存,predict 则仅运行查询行;clear 释放该缓存。fit 过程中没有学习任何内容,这里的含义是“记住这些示例”。在我们的 CPU 上,以这种方式回答针对相同四百个上下文行的五批三十行查询的速度快了几倍,而且一旦上下文被缓存,后续每批查询的成本仅为完整前向传播的一小部分。确切的比例取决于机器性能,因此单元格会测量它而不是假设它。
@section("5. 回归返回一个分布:999个分位数,以及它们的诚实程度") def quantile_regression(): df = load_diabetes(as_frame=True).frame.sample(frac=1, random_state=0).reset_index(drop=True) table = sdm.TableTensor.from_pandas(df, sdm.infer_stypes(df), device=DEVICE) model = sdm.models.TabICLv2(device=DEVICE) torch.manual_seed(0) q = model(x_context=table[:300].drop_columns("target"), y_context=table[:300, "target"], x_query=table[300:].drop_columns("target"), num_estimators=4).to_pandas() y = df.target.to_numpy()[300:] print(f" output: {q.shape[1]} columns {list(q.columns[:3])} ... {list(q.columns[-2:])} per query row")
X, Y = df.drop(columns="target"), df.target rmse = lambda p: float(np.sqrt(np.mean((np.asarray(p) - y) ** 2))) print(f"\n {'point prediction':34s} {'RMSE':>7s}") print(f" {'TabICLv2 median (q500), no training':34s} {rmse(q['q500']):7.2f}") print(f" {'RidgeCV, fit on 300 rows':34s} {rmse(RidgeCV().fit(X[:300], Y[:300]).predict(X[300:])):7.2f}") print(f" {'HistGradientBoosting, fit on 300':34s} " f"{rmse(HistGradientBoostingRegressor(random_state=0).fit(X[:300], Y[:300]).predict(X[300:])):7.2f}")
print(f"\n {'interval':12s} {'nominal':>8s} {'empirical coverage':>19s} {'mean width':>11s}") coverage = {} for lo, hi in [("q250", "q750"), ("q100", "q900"), ("q050", "q950")]: nominal = (int(hi[1:]) - int(lo[1:])) / 1000 coverage[nominal] = float(np.mean((y >= q[lo]) & (y <= q[hi]))) print(f" {lo}-{hi:6s} {nominal:8.0%} {coverage[nominal]:19.3f} {np.mean(q[hi] - q[lo]):11.1f}") print("\n The quantiles come from one forward pass over 300 examples, yet the 80% and 90% intervals") print(" cover close to 80% and 90% of held-out targets. The 50% band runs a little narrow.") return f"median RMSE {rmse(q['q500']):.1f}; 80% interval covers {coverage[0.8]:.1%}"
quantile_regression()
对于回归任务,模型并不返回单个数值。它针对每个查询行返回999个分位数,即通过一次前向传播读取出的完整预测分布。在包含三百个已标记样本的糖尿病数据集上,该分布的中位数产生的均方根误差(RMSE)为53.6,略优于RidgeCV的54.3,并明显优于梯度提升法的64.7,后两者均在相同的样本行上进行训练。更有用的特性是校准性:第10百分位到第90百分位之间的区间包含了81.0%的保留目标值,而第5百分位到第95百分位的区间包含了91.5%,接近其名义上的80%和90%,尽管50%的区间略微偏窄,仅为43.7%。

@section("6. Twenty classes from one forward pass") def many_classes(): X, y = make_classification(n_samples=800, n_features=12, n_informative=8, n_redundant=2, n_classes=20, n_clusters_per_class=1, class_sep=1.5, random_state=0) df = pd.DataFrame(X, columns=[f"f{i}" for i in range(12)]) df["label"] = [f"c{v:02d}" for v in y] table = as_table(df, "label") model = sdm.models.TabICLv2(device=DEVICE) torch.manual_seed(0) t0 = time.time() proba = model(x_context=table[:600].drop_columns("label"), y_context=table[:600, "label"], x_query=table[600:].drop_columns("label"), num_estimators=1).to_pandas() secs = time.time() - t0 acc = float(np.mean(proba.idxmax(axis=1).to_numpy() == df.label.to_numpy()[600:])) hgb = HistGradientBoostingClassifier(random_state=0).fit(X[:600], y[:600]) acc_hgb = float(np.mean(hgb.predict(X[600:]) == y[600:])) print(f" 20 balanced classes, 600 labelled rows (30 per class), 200 queries") print(f" TabICLv2, no training {proba.shape[1]} probability columns, accuracy {acc:.3f} ({secs:.1f}s)") print(f" HistGradientBoosting, trained accuracy {acc_hgb:.3f}") print("\n The pretrained head has a fixed number of class slots. Past that, SDM splits the problem") print(" into error-correcting output codes (sdm.models.ecoc) and recombines the log-probabilities,") print(" so the caller still gets one column per label without doing anything.") return f"20 classes: {acc:.3f} vs {acc_hgb:.3f} for gradient boosting"
many_classes()
预训练的分类头具有固定数量的类别槽位,而库通过纠错输出码处理超过该数量的类别问题,将问题拆分为更小的编码子问题并重新组合对数概率。调用者无需感知这一过程:在包含二十个平衡类别的合成问题上,每个类别有三十行标注数据,TabICLv2 在一次前向传播中返回二十列概率值,准确率达到 0.760,而使用相同数据进行训练的梯度提升模型准确率仅为 0.615。
def make_tickets(n=1600, seed=1):
"""生成支持工单,其升级取决于打开的时间以及内容。”"""
rng = np.random.default_rng(seed)
opened = pd.Timestamp("2026-03-02") + pd.to_timedelta(rng.integers(0, 86_400 * 56, n), unit="s")
neutral = ["order", "item", "delivery", "account", "app", "invoice", "question", "help", "update", "status"]
hot = ["refund", "broken", "charged", "twice"]
comments, has_hot = [], []
for _ in range(n):
words = list(rng.choice(neutral, rng.integers(4, 9)))
flag = rng.random() < 0.3
if flag:
words.insert(rng.integers(len(words)), rng.choice(hot))
comments.append(" ".join(words))
has_hot.append(flag)
hour, weekend = np.asarray(opened.hour), np.asarray(opened.dayofweek >= 5)
amount = rng.gamma(2, 40, n).round(2)
logit = (-1.6 + 2.2 * np.array(has_hot) + 1.4 * ((hour >= 22) | (hour < 6)) + 1.0 * weekend
+ 0.004 * (amount - 80))
escalated = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
return pd.DataFrame({"amount": amount, "channel": rng.choice(["web", "app", "phone"], n),
"opened_at": opened, "comment": comments, "escalated": escalated})
@section("7. 食谱:默认的会丢弃你的时间戳和文本,并只说一次")
def recipes():
df = make_tickets()
stypes = sdm.infer_stypes(df, overrides={"escalated": "categorical"}, text="infer")
table = sdm.TableTensor.from_pandas(df, stypes, device=DEVICE)
x_ctx, y_ctx = table[:1000].drop_columns("escalated"), table[:1000, "escalated"]
x_q, y_q = table[1000:].drop_columns("escalated"), df.escalated.to_numpy()[1000:]
print(f" columns: {', '.join(f'{c}={s}' for c, s in stypes.items())}")
print(" 升级由夜间/周末打开以及诸如“退款”之类的词语驱动\n")
default = sdm.models.TabICLv2.default_recipe()
with_calendar = sdm.models.TabICLv2.default_recipe()
with_calendar.prepend_features(sp.StypeDispatch(
datetime=sp.AddCalendarFields(["hour", "weekday"], encoding="cyclic")))
calendar_and_text = sp.StypeDispatch(
datetime=sp.AddCalendarFields(["hour", "weekday"], encoding="cyclic"),
text=sp.TFIDF(ngram_range=(1, 1), max_features=64))
with_both = sdm.models.TabICLv2.default_recipe()
with_both.prepend_features(calendar_and_text)
model = sdm.models.TabICLv2(device=DEVICE)
aucs = {}
for label, recipe in [("default recipe", default),
("+ AddCalendarFields(hour, weekday)", with_calendar),
("+ AddCalendarFields + TFIDF(64 terms)", with_both)]:
torch.manual_seed(0)
proba = model(x_context=x_ctx, y_context=y_ctx, x_query=x_q, num_estimators=4, recipe=recipe).to_pandas()
aucs[label] = roc_auc_score(y_q, proba["1"])
print(f" {label:40s} AUC {aucs[label]:.3f}")
print("\n 默认的 TabICLv2 食谱根据 stype 进行分发,并且仅包含分类列和数值列的分支,因此日期时间和文本列永远不会成为特征。SDM 确实这样说了,在上面的 RuntimeWarning 中,但它是警告一次:它在第一次触发,并在进程其余部分被抑制。同一笔记本或服务中的每个后续模型都会无声地丢弃这些列。修复方法是两个处理器,添加到特征之前:")
print(textwrap.indent(repr(calendar_and_text), " "))
return " -> ".join(f"{v:.3f}" for v in aucs.values()) + " AUC"
recipes()库中的预处理是一个由可组合处理器组成的配方(Recipe),默认的 TabICLv2 配方仅针对分类列和数值列的语义类型进行分支处理。因此,时间戳列和文本列永远不会成为特征。在那些升级取决于工单创建时间以及诸如“退款”等关键词的支持工单上,默认配方的 AUC 得分为 0.525,接近随机猜测水平。该库确实会发出 RuntimeWarning,指明被忽略的列类型。然而,这是一个仅警告一次的提示:它在首次运行时触发,并在后续过程中被抑制,因此同一笔记本或服务中的每个后续模型都会无声地丢弃这些列。前置两个处理器即可修复此问题:AddCalendarFields 将时间戳转换为循环的小时和星期几特征,使 AUC 提升至 0.634;而 TFIDF 则添加了评论中的术语,使其进一步提升至 0.789。
@section("8. 解释预测:解释器中的两个陷阱") def explain(): rng = np.random.default_rng(2) X = rng.normal(size=(500, 8)) true = {"x0": 2.0, "x3": -1.5, "x5": 1.0} logit = sum(w * X[:, int(c[1:])] for c, w in true.items()) df = pd.DataFrame(X, columns=[f"x{i}" for i in range(8)]) df["y"] = (rng.random(500) < 1 / (1 + np.exp(-logit))).astype(int) table = as_table(df, "y") model = sdm.models.TabICLv2(device=DEVICE) ctx = dict(x_context=table[:400].drop_columns("y"), y_context=table[:400, "y"]) x_q = table[400:].drop_columns("y") p1 = lambda pred: pred.numerical[..., pred.columns[sdm.Stype.numerical].index("1")] # P(y=1), 按名称获取
seen = [] def peek(pred): seen.append(pred.columns[sdm.Stype.numerical]) return pred.numerical.sum() * 0 torch.manual_seed(0) sdm.explain.GradientExplainer(output=peek).explain(model, x_q, num_estimators=4, **ctx) print(f" num_estimators=4: 输出函数被调用 {len(seen)} 次,每次调用的类别顺序为:") print(f" {seen}")
def only_call(n): calls = {"i": 0} def f(pred): calls["i"] += 1 return p1(pred) if calls["i"] == n else p1(pred) * 0 return f sizes = {} for n in (1, len(seen)): torch.manual_seed(0) g = sdm.explain.GradientExplainer(output=only_call(n)).explain(model, x_q, num_estimators=4, **ctx) sizes[n] = float(g.x.to_pandas().abs().mean().mean()) print(f"\n 陷阱 1 - 仅解释最后一个估计器。输出函数仅在第一次调用时有效:" f"平均 |梯度| {sizes[1]:.4f};") print(f" 仅在调用 {len(seen)} 时有效:{sizes[len(seen)]:.4f}。每次调用都会覆盖之前的结果,因此") print(" 使用多个估计器时,你得到的是其中一个的结果,而不是它们的平均值。请使用 num_estimators=1 进行解释。")
print("\n 陷阱 2 - 每个估计器的类别顺序不同。num_estimators=1,六个随机种子,以两种方式选择 P(y=1):") print(f" {'seed':>6s} {'order':>12s} " + "".join(f"{c + f' ({true[c]:+.1f})':>20s}" for c in true)) print(f" {'':6s} {'':12s} " + "".join(f"{'位置/名称':>20s}" for _ in true)) by_name = [] flipped = name_ok = 0 for seed in range(6): order = [] def note(pred): order.append(pred.columns[sdm.Stype.numerical]) return pred.numerical.sum() * 0 torch.manual_seed(seed) sdm.explain.GradientExplainer(output=note).explain(model, x_q, num_estimators=1, **ctx) res = {} for label, fn in (("position", lambda pred: pred.numerical[..., 1]), ("name", p1)): torch.manual_seed(seed) res[label] = sdm.explain.GradientExplainer(output=fn).explain( model, x_q, num_estimators=1, **ctx).x.to_pandas().mean() by_name.append(res["name"]) flipped += any(np.sign(res["position"][c]) != np.sign(w) for c, w in true.items()) name_ok += all(np.sign(res["name"][c]) == np.sign(w) for c, w in true.items()) print(f" {seed:>6d} {str(order[0]):>12s} " + "".join(f"{res['position'][c]:>10.2f} /{res['name'][c]:>7.2f}" for c in true)) avg = pd.concat(by_name, axis=1).mean(axis=1) noise = float(avg.drop(list(true)).abs().max()) print(f"\n 当洗牌将类别 '1' 排在第一位时,列 1 对应 P(y=0),所有符号翻转。按名称选择") print(f" 在 {name_ok}/6 个随机种子中给出了正确的符号。跨种子平均后,按名称计算: " + ", ".join(f"{c} {avg[c]:+.2f}" for c in true) + f"; 最大噪声特征值 {noise:.2f}。") print(" 梯度是相对于预处理后的(即标准化的)输入计算的。") return f"位置符号在 {flipped}/6 个随机种子中翻转;名称在 {name_ok}/6 个随机种子中正确;仅使用最后一个估计器"
explain()
该库的 GradientExplainer 返回所选输出相对于预处理查询输入的梯度,我们在合成数据上对其进行了测试,其中八个特征中只有三个是重要的,且其符号已知。这里有两个陷阱,只有通过观察输出函数接收到的内容才能发现。首先,每个估计器会调用一次该函数,且每次调用都会覆盖之前的结果,因此如果有四个估计器,一个仅在第一次调用时有效的输出函数会产生全零的解释,而你得到的解释仅来自最后一个估计器。其次,每个估计器的原始输出都有其自己的类别顺序,因为默认配方会对每个估计器的类别标签进行打乱。使用单个估计器在六个随机种子下进行解释时,如果通过列位置选择第一类的概率,会在两个顺序被反转的随机种子上导致所有特征的符号翻转;而通过列名进行选择则能在所有六个随机种子上得到正确的符号,并且通过对这些随机种子取平均值,可以恢复出三个真实特征,而噪声特征的贡献接近于零。
def make_shop(seed=0, n_customers=800, n_products=60): """客户、产品和一年的订单。部分客户的活动在随机日期后陷入停滞。""" rng = np.random.default_rng(seed) plans = rng.choice(["basic", "pro"], n_customers, p=[0.7, 0.3]) customers = pd.DataFrame({"customer_id": np.arange(n_customers), "region": rng.choice(["NA", "EU", "APAC", "LATAM"], n_customers), "plan": plans}) products = pd.DataFrame({"product_id": np.arange(n_products), "category": rng.choice(["books", "tech", "home", "toys"], n_products), "price": rng.gamma(2.0, 20.0, n_products).round(2)}) weekly_rate = rng.gamma(1.5, 0.6, n_customers) * np.where(plans == "pro", 1.6, 1.0) fade_day = rng.uniform(60, 500, n_customers) rows, start = [], pd.Timestamp("2025-01-01") for c in range(n_customers): t = 0.0 while True: rate = weekly_rate[c] / 7 * (1.0 if t < fade_day[c] else 0.08) t += rng.exponential(1 / max(rate, 1e-6)) if t > 364: break p = int(rng.integers(n_products)) rows.append((c, p, start + pd.Timedelta(float(t), unit="D"), float(products.price[p] * rng.integers(1, 4)))) orders = pd.DataFrame(rows, columns=["customer_id", "product_id", "order_date", "amount"]) orders.insert(0, "order_id", np.arange(len(orders))) orders["order_date"] = orders["order_date"].dt.floor("s") return customers, products, orders
def task_rows(customers, orders, cutoff, horizon_days=30): """标签:客户在截止日期的30天内是否会再次下单?""" window = orders[(orders.order_date > cutoff) & (orders.order_date <= cutoff + pd.Timedelta(horizon_days, unit="D"))] active = set(window.customer_id) return pd.DataFrame({"customer_id": customers.customer_id, "timestamp": cutoff, "label": [int(c in active) for c in customers.customer_id]})
@section("9. 作为输入的关系数据库:表、键和时间感知采样器") def relational_setup(): customers, products, orders = make_shop() data = sdm.RelationalData( tables={ "customers": sdm.TableTensor.from_pandas(customers, {"customer_id": "id", "region": "categorical", "plan": "categorical"}), "products": sdm.TableTensor.from_pandas(products, {"product_id": "id", "category": "categorical", "price": "numerical"}), "orders": sdm.TableTensor.from_pandas(orders, {"order_id": "id", "customer_id": "id", "product_id": "id", "order_date": "datetime", "amount": "numerical"}), }, relationships=[ dict(left_table="orders", left_column="customer_id", right_table="customers", right_column="customer_id"), dict(left_table="orders", left_column="product_id", right_table="products", right_column="product_id"), ], ) cutoffs_ctx = [pd.Timestamp(d) for d in ("2025-06-01", "2025-07-01", "2025-08-01")] cutoff_q = pd.Timestamp("2025-09-15") task_df = pd.concat([task_rows(customers, orders, c) for c in cutoffs_ctx + [cutoff_q]], ignore_index=True) task = sdm.TableTensor.from_pandas(task_df, {"customer_id": "id", "timestamp": "datetime", "label": "categorical"}) n_ctx = len(cutoffs_ctx) * len(customers) link = dict(task_link={"task_column": "customer_id", "table": "customers", "table_column": "customer_id"}, num_neighbors=[16, 16], task_time_column="timestamp")
print(f" {len(customers)} customers, {len(products)} products, {len(orders):,} orders over 2025") print(" relationships: orders.customer_id -> customers, orders.product_id -> products") print(f" task: will the customer order in the 30 days after a cutof
f? positive rate {task_df.label.mean():.2f}") print(f" context: cutoffs {[str(c.date()) for c in cutoffs_ctx]} ({n_ctx:,} rows); query: {cutoff_q.date()}")
sampler = data.sampler(time_columns={"orders": "order_date"}) sample, related = sampler(task[:3].drop_columns("label"), **link) print("\n what the sampler hands the model for the first 3 task rows (16 neighbours, then 16 more):") for name, tbl in related.tables.items(): print(f" {name:10s} {tuple(tbl.size())}") latest = related.tables["orders"].to_pandas()["order_date"].max() print(f" latest order the sampler returned: {latest} task timestamp: {cutoffs_ctx[0]}") print(" The sampler walks the foreign keys backwards in time: no order dated after the task row's") print(" own timestamp is eligible, so the rows that define the label cannot leak in.") globals().update(SHOP=dict(customers=customers, orders=orders, data=data, task=task, task_df=task_df, n_ctx=n_ctx, link=link, cutoffs=cutoffs_ctx + [cutoff_q])) return f"{len(orders):,} orders across 3 linked tables"
relational_setup()
``
KumoRelational 采用关系数据库而非单个表格。我们构建了一个包含八百名客户、六十种产品和一年订单的小型商店,其中部分客户的活动在某个随机日期突然停止,并询问每位客户是否在截止日期后的三十天内会再次下单。RelationalData 存储了这些表格以及它们之间的外键,其采样器从每个任务行出发,沿外键向外遍历,每跳最多收集十六个邻居。将订单日期声明为时间列使得遍历过程具有时间属性:我们验证采样器为六月一日标记的任务行返回的最新订单是在五月三十一日下达的,因此定义标签的行处于不可达状态。
def relational_auc(time_columns):
s = SHOP
sampler = s["data"].sampler(time_columns=time_columns)
model = sdm.models.KumoRelational(device=DEVICE)
torch.manual_seed(0)
context, related = sampler(s["task"][:s["n_ctx"]], **s["link"])
model.fit(x=context.drop_columns("label"), y=context["label"], related_tables=related,
generator=torch.Generator().manual_seed(0))
query = s["task"][s["n_ctx"]:].drop_columns("label")
proba = model.predict(*sampler(query, **s["link"])).to_pandas()
return roc_auc_score(s["task_df"].label.to_numpy()[s["n_ctx"]:], proba["1"])
def history_features(customers, orders, cutoff):
"""数据科学家会手动编写的数据工程特征,严格在截止日之前计算。”
past = orders[orders.order_date <= cutoff]
by_customer = past.groupby("customer_id")
f = pd.DataFrame({"customer_id": customers.customer_id})
for days in (30, 90):
recent = past[past.order_date > cutoff - pd.Timedelta(days, unit="D")].groupby("customer_id")
f[f"orders_{days}d"] = f.customer_id.map(recent.size()).fillna(0)
f[f"spend_{days}d"] = f.customer_id.map(recent.amount.sum()).fillna(0)
f["days_since_last"] = f.customer_id.map((cutoff - by_customer.order_date.max()).dt.days).fillna(999)
f["orders_total"] = f.customer_id.map(by_customer.size()).fillna(0)
return f.merge(customers, on="customer_id").drop(columns="customer_id")
def flat_auc(frame_fn):
s = SHOP
X = pd.concat([frame_fn(c) for c in s["cutoffs"]], ignore_index=True)
X["label"] = s["task_df"].label.values
table = as_table(X, "label")
model = sdm.models.TabICLv2(device=DEVICE)
torch.manual_seed(0)
proba = model(x_context=table[:s["n_ctx"]].drop_columns("label"), y_context=table[:s["n_ctx"], "label"],
x_query=table[s["n_ctx"]:].drop_columns("label"), num_estimators=4).to_pandas()
return roc_auc_score(s["task_df"].label.to_numpy()[s["n_ctx"]:], proba["1"]), list(X.columns[:-1])
@section("10. KumoRelational 与手工构建特征的对比:同一个问题,三种方法")
def relational_vs_features():
s = SHOP
results = []
t0 = time.time()
auc, cols = flat_auc(lambda c: s["customers"].drop(columns="customer_id"))
results.append(("仅使用客户表的 TabICLv2", auc, f"{len(cols)} 个原始列", time.time() - t0))
t0 = time.time()
auc, cols = flat_auc(lambda c: history_features(s["customers"], s["orders"], c))
results.append(("基于手工工程特征的 TabICLv2", auc, f"{len(cols) - 2} 个工程特征 + 2 个原始特征", time.time() - t0))
t0 = time.time()
results.append(("基于原始表的 KumoRelational", relational_auc({"orders": "order_date"}), "3 个原始表", time.time() - t0))
print(f" {'approach':40s} {'AUC':>6s} {'inputs':22s} {'seconds':>7s}")
for label, auc, inputs, secs in results:
print(f" {label:40s} {auc:6.3f} {inputs:22s} {secs:7.1f}")
print("\n 仅凭人口统计信息 barely 胜过抛硬币。购买历史才是信号所在,而")
print(" 关系模型无需任何人编写 orders_30d、spend_90d 或 days_since_last 即可捕捉到该信号:")
print(" 它通过键直接读取订单行本身,以每个任务行的时间戳为准。")
globals()["REL_AUC"] = results[2][1]
return (f"仅客户表 {results[0][1]:.3f} / 手工构建 {results[1][1]:.3f}"
f" / KumoRelational {results[2][1]:.3f} AUC")
relational_vs_features()
随后我们以三种方式回答同一个问题。仅在客户表上运行 TabICLv2,仅使用地区和计划作为输入,AUC 达到 0.556。在六个经过工程处理的历史特征(过去三十天和九十天内的订单和支出、距上次订单的天数以及终身订单计数)上运行 TabIClv2,且这些特征在每个截止点之前严格计算得出,AUC 达到 0.828。在原始表上运行 KumoRelational,无需任何人编写任何特征,AUC 达到 0.823。关系模型通过读取每个任务行时间戳对应的键所关联的订单行本身,几乎达到了手工构建管道的精度水平。
``php
@section("11. The one argument that keeps a relational model honest") def leakage(): leaky = relational_auc(None) print(f" KumoRelational with time_columns={{'orders': 'order_date'}} AUC {REL_AUC:.3f}") print(f" KumoRelational with time_columns=None AUC {leaky:.3f}") print("\n Without a time column the sampler is free to return orders placed AFTER the cutoff, which") print(" are exactly the orders that define the label. The model is not predicting anymore, it is") print(" reading the answer. Nothing errors and the number looks like a breakthrough. On a real") print(" database, a relational model that is suspiciously better than your hand-built baseline") print(" should be the first thing you re-run with every time column declared.") return f"{REL_AUC:.3f} honest vs {leaky:.3f} with future rows visible"
leakage()
``
最后,我们在未声明时间列的情况下运行相同的关系模型。AUC 上升至 0.940。如果没有时间列,采样器可以自由返回截止点后生成的订单,而这些订单恰恰是定义标签的订单,因此模型不再进行预测,而是在读取答案,且不会报错。在实际数据库中,如果一个关系模型的表现异常优于手工构建的基线,那么第一件事就是重新运行代码并声明所有时间列。
``php
banner("SUMMARY")
for name, res in RESULTS.items():
print(f" {name:<76s} {res}")
print("""
What to carry over
- Declare stypes deliberately: text and id columns are not detected unless you ask, and the
default TabICLv2 recipe drops datetime and text columns with a warning that fires once.
- In an explainer output function, select classes by name, never by position.
- Every table with a time column goes in time_columns. A relational model that is not time-aware
is a leakage detector, not a forecaster.
Where to go next
- Fine-tuning: examples/tabular/finetune.py disables the output recipe and trains on raw logits.
- Real relational benchmarks: examples/relational/rel_bench.py runs KumoRelational on RelBench.
- On a T4 runtime, set DEVICE = "cuda" for the tabular models; cudf keeps dataframe work on GPU.
- Docs: nvidia.github.io/structured-data-models Code: github.com/NVIDIA/structured-data-models
""")
```
摘要打印了每个部分返回的单行结果,以及三个值得保留的习惯:有意地声明语义类型和配方、在解释器输出函数中按名称选择类别并使用单个估计器进行解释,以及将包含时间列的每个表放入 time_columns 中。随后它指出了微调、RelBench 示例以及 GPU 执行。
总之,NVIDIA 的结构化数据模型兑现了其核心承诺:在分类、回归、二十类问题和三表数据库任务中,其预训练模型在未进行自身训练的情况下,匹配或超越了在同一行数据上训练的 scikit-learn 基线模型,免费提供了校准后的预测分布,并且在关系型案例中达到了从原始表格构建的手工特征流水线的准确率。默认设置值得比模型本身更多的审视。除非明确要求,否则不会检测自由文本和 ID;默认配方会丢弃时间戳和文本列,且每个进程仅警告一次;解释器仅报告最后一个估计器,并需要通过名称选择类别;库自身错误消息中的 pyg-lib URL 指向一个空页面;而缺少时间列的关系型模型会产生令人印象深刻但毫无意义的数值。这些问题每一个都可以通过一行代码修复,否则它们都会无声地通过,这为处理真实数据带来了实用的教训:在信任模型的输出之前,务必检查输入模型的数据。
Sana Hassan 是 Marktechpost 的咨询实习生,也是印度马德拉斯理工学院的双学位学生,热衷于应用技术和人工智能来解决现实世界的挑战。他对解决实际问题有着浓厚的兴趣,为 AI 与现实生活解决方案的交叉领域带来了全新的视角。

译文已达到本站中文翻译的字数上限,剩余内容请查看原文。