TensorFlow Datasets (TFDS)
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
TensorFlow Datasets (TFDS) is a separate library, tensorflow-datasets, that packages many public datasets behind one API. It downloads and prepares the data once, stores it as sharded files, and returns a tf.data.Dataset (or NumPy arrays) that plugs into the rest of the stack. It is a convenient source of benchmark data for the tutorials in this part and for quick experiments; for your own folders of files use Loading Images, Text and Audio from Disk, and for your own records use Input Pipelines with tf.data. Preprocessing the examples is covered in Keras Preprocessing Layers and the speed of the resulting pipeline in tf.data Performance. A worked use is in Image Classification with CNNs; the PyTorch equivalents are on torchvision and Datasets and DataLoader.
It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 and a current tensorflow-datasets release (TensorFlow 2.22 is "upcoming"), and was checked against the official TFDS documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21, Keras 3.15 and tensorflow-datasets 4.9.10 (CPU, macOS) on 2026-10-31. The tf_flowers and cifar10 examples were run with tfds.testing.mock_data in place of the real downloads, and the data_source example could not run on macOS (see that section). Dataset sizes and downloads run to gigabytes for some datasets; check the catalogue entry first.
Installation
pip install tensorflow-datasets # stable release, published every few months
pip install tfds-nightly # published daily, newest datasets and fixes
TFDS itself is imported as tensorflow_datasets, conventionally import tensorflow_datasets as tfds. Install it in the same environment as TensorFlow (see Installation). Some datasets need extra packages for their source format, which the error message names on first use.
With tensorflow-datasets 4.9.10 and etils 1.14 on Python 3.13, the first tfds.load fails with ModuleNotFoundError: No module named 'importlib_resources': etils imports that package but does not declare it as a dependency. Install it alongside TFDS:
pip install importlib_resources
Finding datasets
import tensorflow_datasets as tfds
names = tfds.list_builders()
print(len(names), "builders;", [n for n in names if n.startswith("cifar")])
The web catalogue at https://www.tensorflow.org/datasets/catalog/overview lists every dataset with its features, splits, size, licence and citation. A community catalogue lists datasets contributed outside the main repository. Read the licence and citation of every dataset you use; TFDS redistributes the preparation code, not the right to use the data.
Loading with tfds.load
ds = tfds.load("mnist", split="train", shuffle_files=True)
for example in ds.take(1):
print(example.keys()) # dict_keys(['image', 'label'])
print(example["image"].shape, example["label"].numpy()) # (28, 28, 1) 4 (the label varies)
The first call downloads the source files, converts them to TFRecord shards under ~/tensorflow_datasets/ and builds the pipeline; later calls reuse the prepared files. The most used arguments:
| Argument | Meaning |
|---|---|
|
A split name, a list of names (one dataset returned per entry) or a slice expression; see the next section. Omitting it returns a dictionary with every split. |
|
Reshuffle the order of the underlying shard files each epoch. It does not shuffle examples inside a shard, so add |
|
Return |
|
Also return the |
|
Batch inside TFDS. The special value |
|
Where prepared data lives; the default is |
|
Set to |
|
A |
The two item formats are the dictionary form, where each example is a dictionary of tensors keyed by feature name, and the tuple form from as_supervised=True, available only for datasets that define a supervised key pair.
(ds_train, ds_test), info = tfds.load(
"mnist",
split=["train", "test"],
as_supervised=True,
with_info=True,
)
import tensorflow as tf
def prep(image, label):
return tf.cast(image, tf.float32) / 255.0, label
ds_train = (ds_train
.map(prep, num_parallel_calls=-1) # -1 is tf.data.AUTOTUNE
.cache()
.shuffle(info.splits["train"].num_examples)
.batch(128)
.prefetch(-1))
ds_test = ds_test.map(prep).batch(256).cache().prefetch(-1)
The order cache, shuffle, batch, prefetch follows the tf.data guidance: cache after deterministic work, shuffle before batching, prefetch last. The training split is shuffled with a buffer the size of the dataset only because MNIST fits in memory; for larger data use a smaller buffer. Applying Rescaling inside the model instead moves the division onto the accelerator and exports it with the model, as discussed in Keras Preprocessing Layers.
Splits
Every dataset declares named splits (typically train and test, sometimes validation); the name all is reserved for their union. The split argument accepts a small slicing language.
| Expression | Meaning |
|---|---|
|
The whole training split. |
|
Python-style absolute slices of example indices. |
|
Percent slices; fractional percentages are allowed. |
|
Slices measured in shard files ( |
|
Union of splits or slices. |
|
A list returns one dataset per entry. |
# Train, validation and test from a dataset that only has "train"
(ds_train, ds_val, ds_test), info = tfds.load(
"tf_flowers",
split=["train[:80%]", "train[80%:90%]", "train[90%:]"],
as_supervised=True,
with_info=True,
)
print(info.features["label"].num_classes, info.features["label"].names)
# Ten-fold cross-validation folds from the training split
val_folds = tfds.load("mnist", split=[f"train[{k}%:{k + 10}%]" for k in range(0, 100, 10)])
train_folds = tfds.load("mnist", split=[f"train[:{k}%]+train[{k + 10}%:]" for k in range(0, 100, 10)])
Slices select the same examples on every run for a given dataset version, because the examples are shuffled deterministically when the dataset is generated. The read order inside a slice can still differ; reading test[0:100] then test[100:200] is not guaranteed to give the same order as test[:200], only the same set. When the size does not divide evenly, tfds.core.ReadInstruction lets you choose rounding (closest by default, or pct1_dropremainder for equal 1% buckets). For multi-host training, tfds.even_splits("train", n=3) returns non-overlapping, equal parts so each host reads its own slice (see Distributed Training).
Because the validation set of a slice is just another view of the training files, hold a real test split out for the final evaluation and tune only on the validation slice; the reasoning is in Generalization and Regularization.
Metadata with DatasetInfo
ds, info = tfds.load("mnist", with_info=True)
# or, without loading data: info = tfds.builder("mnist").info
print(info.full_name) # mnist/3.0.1
print(info.description[:80]) # The MNIST database of handwritten digits.
print(info.features) # FeaturesDict with image and label
print(info.features["image"].shape, info.features["image"].dtype) # (28, 28, 1) <dtype: 'uint8'>
print(info.features["label"].num_classes) # 10
print(info.features["label"].int2str(7)) # 7 (the MNIST class names are the digits)
print(info.splits["train"].num_examples) # 60000
print(info.splits["train[:10%]"].num_examples) # 6000: works for slices too
DatasetInfo also exposes the homepage, citation, download size and dataset size, and the on-disk location. The feature connectors (Image, ClassLabel, Text, Sequence, Tensor and others) describe how each field is encoded and decoded; a deprecation warning in the documentation says to read np_dtype or tf_dtype instead of the older FeatureConnector.dtype. Use tfds.show_examples(ds, info) for a matplotlib grid of image examples and tfds.as_dataframe(ds.take(4), info) for a table (take a few examples first, because the whole dataset would otherwise be loaded into memory).
The builder API and the command line
tfds.load is a thin wrapper over the builder API, which separates preparation from reading and is useful when you need the builder’s metadata or explicit control.
builder = tfds.builder("cifar10")
builder.download_and_prepare() # no-op if already prepared
ds = builder.as_dataset(split="train", shuffle_files=True)
print(builder.info.splits)
tfds build mnist # prepare a dataset from the command line
The tfds command of tensorflow-datasets 4.9.10 imports Apache Beam when it starts, so without the apache-beam package every subcommand, build included, stops with ModuleNotFoundError: No module named 'apache_beam'. Install apache-beam, or prepare the dataset from Python with tfds.builder(...).download_and_prepare() as above.
The same command family builds your own dataset definitions, as described in the "Writing custom datasets" guide on the TFDS site (not summarised here). Writing a new TFDS dataset is worthwhile when many people or jobs will read the same data; for a single project, a plain tf.data pipeline is simpler.
NumPy output and in-memory arrays
import numpy as np
# One batch holding the entire test split, as NumPy arrays
images, labels = tfds.as_numpy(tfds.load(
"mnist", split="test", batch_size=-1, as_supervised=True))
print(images.shape, images.dtype, labels.shape) # (10000, 28, 28, 1) uint8 (10000,)
# Iterate a normal dataset as NumPy structures
for image, label in tfds.as_numpy(tfds.load("mnist", split="train", as_supervised=True).take(2)):
print(type(image), label) # <class 'numpy.ndarray'> 4, then 1
batch_size=-1 needs the whole split in memory and equal shapes across examples, so it suits MNIST-sized data and not ImageNet. NumPy arrays can be passed straight to model.fit(x, y), which is the simplest route for tiny datasets; the NumPy conversion rules are on NumPy Interop.
Using TFDS without TensorFlow: data_source
TFDS can also expose random-access, NumPy-based data sources for non-TensorFlow loaders. tfds.data_source returns one source per split, backed by the ArrayRecord file format, and each source implements __len__ and __getitem__, so it works as a map-style dataset in PyTorch’s DataLoader.
sources = tfds.data_source("fashion_mnist") # {'train': ..., 'test': ...}
print(len(sources["train"])) # 60000
record = sources["train"][1000] # random access by index
import torch
loader = torch.utils.data.DataLoader(sources["train"], batch_size=128, shuffle=True)
The documentation states that, for now, preparing a dataset still uses TensorFlow, while reading prepared ArrayRecord data does not; the API was still described as under development, with decoding supported for tensor, image and scalar features but not audio or video. Treat the exact behaviour as version-dependent and check the page before relying on it. The ArrayRecord bindings (array_record) are a Linux-only dependency of tensorflow-datasets 4.9.10: on macOS the example above stops while preparing the dataset with ModuleNotFoundError: Failed to finalize writing of split "train": No module named 'array_record', so use data_source on Linux. Default PyTorch collation needs your own collate_fn or a transform to turn each record dictionary into tensors; see Datasets and DataLoader.
Determinism and shuffling
By default (shuffle_files=False) TFDS yields examples in the same order on every run, although that order is the result of interleaving several shards and is not simply increasing example id. Turning on shuffle_files=True reshuffles shards every epoch and disables the deterministic option of tf.data.Options, so even single-shard datasets become non-deterministic. tfds.ReadConfig exposes the knobs: interleave_cycle_length (how many shards are open at once), interleave_block_length (consecutive examples taken from a shard before switching) and shuffle_seed (a reproducible file order; change it each epoch or every epoch reads shards in the same order).
read_config = tfds.ReadConfig(shuffle_seed=32)
ds = tfds.load("mnist", split="train", shuffle_files=True, read_config=read_config)
Also note that ds.take(n) returns the first n examples in read order, which is not the same as the slice train[:n], which selects example indices 0 to n-1. Use the slice when you need a specific, repeatable subset. The ReadConfig(shuffle_seed=...) call above works with tensorflow-datasets 4.9.10. For the general reproducibility checklist see Tensors, Dtypes and Random Numbers.
Putting it into a Keras model
import keras
from keras import layers
model = keras.Sequential([
keras.Input(shape=(28, 28, 1)),
layers.Conv2D(32, 3, activation="relu"),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(10), # logits
])
model.compile(
optimizer=keras.optimizers.Adam(1e-3),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=["accuracy"],
)
model.fit(ds_train, validation_data=ds_test, epochs=2) # the MNIST ds_train and ds_test from "Loading with tfds.load"
The loss is covered in Losses and the fit options in compile, fit, evaluate and predict. Under Keras 3 on a non-TensorFlow backend a tf.data.Dataset is accepted by fit, with the batches converted to backend arrays (checked with the PyTorch backend); see Keras Multi-Backend.
Troubleshooting
-
Downloads fail or hang: some sources require a manual download. Place the files in the dataset’s manual directory (by default
~/tensorflow_datasets/downloads/manual/); the dataset’s catalogue page explains which files. -
NonMatchingChecksumError: the source site may be down or rate limiting, or the upstream file may have changed. In the second case the dataset builder needs an update; trytfds-nightlyfor a newer definition. -
Disk use: prepared data and cached downloads live under
data_dir; delete old versions you no longer need. A dataset’s version is part of its path (mnist/3.0.1), so a new release downloads a fresh copy. -
Different results after an upgrade: TFDS datasets are versioned. Pin
name:version(for example"mnist:3.0.1") intfds.loadfor reproducible experiments. -
Colab and notebooks:
tfds.as_dataframeloads the whole dataset it is given into memory, so calltakefirst. -
Benchmarking:
tfds.benchmark(ds, batch_size=32)reports examples per second and separates the warm-up batch; run it twice, because later runs benefit from caching.
Common mistakes
-
Forgetting
as_supervised=Trueand then passing dictionaries tofit. -
Using the test split for per-epoch validation and for the final number.
-
Calling
ds.shuffleafterbatch(shuffles batches, not examples). -
Assuming
uint8images are already scaled; cast and rescale them. -
Using
batch_size=-1on a dataset that does not fit in memory. -
Treating a dataset’s licence as implied by TFDS availability.