d2l-ai/d2l-zh · error · AssertionError

f"{name} 不存在于 {DATA_HUB}"

Error message

f"{name} 不存在于 {DATA_HUB}"

What it means

An AssertionError in d2l.paddle.download: the requested dataset name is not a key in DATA_HUB. DATA_HUB is a module-level dict of name -> (url, sha1) registrations at the bottom of the module; download() requires the entry for both the URL and the integrity check. The Chinese message means '{name} does not exist in {DATA_HUB}'.

Source

Thrown at d2l/paddle.py:385

    """评估给定数据集上模型的损失。

    Defined in :numref:`sec_model_selection`"""
    metric = d2l.Accumulator(2)  # 损失的总和, 样本数量
    for X, y in data_iter:
        out = net(X)
        y = y.reshape(out.shape)
        l = loss(out, y)
        metric.add(l.sum(), l.numel())
    return metric[0] / metric[1]

DATA_HUB = dict()
DATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/'

def download(name, cache_dir=os.path.join('..', 'data')):
    """下载一个DATA_HUB中的文件,返回本地文件名

    Defined in :numref:`sec_kaggle_house`"""
    assert name in DATA_HUB, f"{name} 不存在于 {DATA_HUB}"
    url, sha1_hash = DATA_HUB[name]
    os.makedirs(cache_dir, exist_ok=True)
    fname = os.path.join(cache_dir, url.split('/')[-1])
    if os.path.exists(fname):
        sha1 = hashlib.sha1()
        with open(fname, 'rb') as f:
            while True:
                data = f.read(1048576)
                if not data:
                    break
                sha1.update(data)
        if sha1.hexdigest() == sha1_hash:
            return fname  # 命中缓存
    print(f'正在从{url}下载{fname}...')
    r = requests.get(url, stream=True, verify=True)
    with open(fname, 'wb') as f:
        f.write(r.content)
    return fname

View on GitHub (pinned to e6b18ccea7)

Solutions

  1. Use a registered name, e.g. d2l.download('kaggle_house_train') or 'kaggle_house_test'.
  2. Register your own entry first: d2l.DATA_HUB['mydata'] = (d2l.DATA_URL + 'mydata.csv', '<sha1_hex>') then d2l.download('mydata').
  3. For live Kaggle competitions, download via the Kaggle website/CLI into ../data instead — the mirror only hosts the book's static files.
  4. Print list(d2l.DATA_HUB.keys()) to see exactly which names are available.

Example fix

# before
d2l.download('kaggle_house')  # AssertionError
# after
print(list(d2l.DATA_HUB.keys()))  # pick an exact name
d2l.download('kaggle_house_train')
Defensive patterns

Strategy: validation

Validate before calling

def safe_download(name):
    if name not in d2l.DATA_HUB:
        raise KeyError(f'{name!r} not in DATA_HUB; available: {sorted(d2l.DATA_HUB)}')
    return d2l.download(name)

Type guard

def is_registered(name: str) -> bool:
    return isinstance(name, str) and name in d2l.DATA_HUB

Try / catch

try:
    d2l.download(name)
except AssertionError:
    raise KeyError(f'{name!r} not registered; pick from {sorted(d2l.DATA_HUB)}')

Prevention

When it happens

Trigger: Calling d2l.download / download_extract / download_all with an unregistered or misspelled name; importing the module in a way that skips the module-level DATA_HUB[...] assignment statements; expecting arbitrary Kaggle datasets to be downloadable.

Common situations: Users assuming d2l mirrors all book datasets under any name — only entries explicitly registered (kaggle_house_train, kaggle_house_test, etc.) work; typos like 'kaggle-house-train' or wrong case; partial copy-paste of the download section into notebooks without the registrations.

Related errors


AI-assisted analysis of d2l-ai/d2l-zh@e6b18ccea7 (2026-08-14). Data as JSON: /api/errors/f45ef67045f19368. Report an issue: GitHub.