For the complete documentation index, see llms.txt. This page is also available as Markdown.

Data Iterators

DataSetIterator implementations — built-in iterators, custom iterators, async loading, and data splitting

A DataSetIterator is the primary interface for feeding training and evaluation data into MultiLayerNetwork and ComputationGraph. It produces DataSet objects (features + labels pairs) one minibatch at a time. Eclipse Deeplearning4j ships built-in iterators for common benchmark datasets, iterators that wrap DataVec RecordReader instances for custom data, and utility iterators for async prefetching and train/test splitting.

The DataSetIterator Interface

DataSetIterator extends java.util.Iterator<DataSet> with additional methods:

public interface DataSetIterator extends Iterator<DataSet>, Iterable<DataSet> {

    // Returns the next minibatch (use batch() to retrieve the configured batch size)
    DataSet next();

    // Returns the next minibatch with a specific size
    DataSet next(int num);

    // Number of input features per example
    int inputColumns();

    // Number of output labels per example
    int totalOutcomes();

    // Whether reset() is supported
    boolean resetSupported();

    // Whether async prefetching is safe to use with this iterator
    boolean asyncSupported();

    // Reset to the beginning of the dataset
    void reset();

    // Configured minibatch size
    int batch();

    // Optional preprocessor applied to each DataSet before it is returned
    void setPreProcessor(DataSetPreProcessor preProcessor);
    DataSetPreProcessor getPreProcessor();

    // List of label names (may return null)
    List<String> getLabels();

    boolean hasNext();
}

The simplest training loop:


Built-in Dataset Iterators

MnistDataSetIterator

60,000 training / 10,000 test grayscale digit images, 28x28 pixels, 10 classes. Data is automatically downloaded and cached on first use.

Output shape per batch: features [batch, 784], labels [batch, 10] (one-hot).

Cifar10DataSetIterator

50,000 training / 10,000 test RGB images, 32x32 pixels, 10 classes. Uses a cached PNG version of the dataset.

Output shape per batch: features [batch, 3, 32, 32] (channels-first), labels [batch, 10].

IrisDataSetIterator

150 examples, 4 features, 3 classes. The classic Fisher Iris dataset.

EmnistDataSetIterator

Extended MNIST with multiple subset splits:

Subset constant
Classes
Training examples

COMPLETE (ByClass)

62

~697,932

MERGE (ByMerge)

47

~697,932

BALANCED

47

112,800

LETTERS

26

124,800

DIGITS

10

240,000

UciSequenceDataSetIterator

Univariate time series dataset from UCI, 6 classes (Normal, Cyclic, Increasing Trend, Decreasing Trend, Upward Shift, Downward Shift). Useful for testing sequence classifiers.

LFWDataSetIterator

Labeled Faces in the Wild: 13,233 images across 5,749 identity classes. Supports train/test split, custom image transforms, and label generation.

TinyImageNetDataSetIterator

200-class subset of ImageNet, 500 training images per class, 64x64 RGB. Used in Stanford CS231n.


RecordReaderDataSetIterator

RecordReaderDataSetIterator bridges DataVec RecordReader instances (CSV, images, audio, etc.) with the DL4J training API. Use its fluent Builder for clean configuration.

Classification from CSV

Regression from CSV

Image Classification

Builder Reference

Method
Description

classification(int labelIndex, int numClasses)

Configure for classification. labelIndex is the column containing the integer class index.

regression(int labelIndex)

Single-output regression.

regression(int from, int to)

Multi-output regression with contiguous label columns.

preProcessor(DataSetPreProcessor)

Optional: apply a preprocessor to each batch before returning it.

maxNumBatches(int)

Limit the number of batches returned per epoch.

collectMetaData(boolean)

Include RecordMetaData in the returned DataSet for traceability.

writableConverter(WritableConverter)

Override how Writable values are converted to numeric.

Loading by Metadata

After setting collectMetaData(true), individual examples can be reloaded:


SequenceRecordReaderDataSetIterator

Produces time series DataSet objects from SequenceRecordReader sources. Features and labels can come from separate readers (separate files) or the same reader.

Alignment modes:

Mode
Description

EQUAL_LENGTH

Features and labels have the same number of time steps.

ALIGN_START

Labels are aligned to the start of the feature sequence; remainder is padded.

ALIGN_END

Labels are aligned to the end (typical for sequence classification — one label per sequence).


RecordReaderMultiDataSetIterator

For ComputationGraph with multiple inputs and/or multiple outputs. Allows columns from one or more RecordReader instances to be routed to different network inputs and outputs.


Async Data Loading

AsyncDataSetIterator

Wraps any DataSetIterator and prefetches minibatches on a background thread, overlapping data loading with GPU computation. DL4J's model.fit(iterator) methods automatically apply async prefetching when iterator.asyncSupported() returns true, so manual wrapping is usually not required.

Key characteristics:

  • Uses a separate thread to call next() on the underlying iterator.

  • By default, uses a cyclical workspace to avoid off-heap memory accumulation.

  • Call asyncIter.shutdown() to cleanly stop the background thread when done.

  • asyncSupported() returns true.

AsyncMultiDataSetIterator

The MultiDataSetIterator equivalent. Wraps any MultiDataSetIterator for background prefetching.

AsyncShieldDataSetIterator

The inverse of AsyncDataSetIterator. Wraps an iterator and forces asyncSupported() to return false, preventing DL4J from automatically applying async prefetching. Use this when your iterator is not thread-safe or manages its own internal buffering.


Utility Iterators

WorkspacesShieldDataSetIterator

Detaches all INDArray objects coming out of the wrapped iterator from any memory workspace, producing "safe" arrays that can be held across workspace scopes. Intended for debugging and testing.

INDArrayDataSetIterator

Creates a DataSetIterator directly from an Iterable of (features, labels) INDArray pairs. Useful for synthetic data or in-memory datasets.

DoublesDataSetIterator

Same as INDArrayDataSetIterator but accepts double[] pairs rather than INDArray pairs.

SamplingDataSetIterator

Randomly samples (with replacement) from an in-memory DataSet.


Train/Test Splitting

DataSetIteratorSplitter

Splits a single DataSetIterator into train and test iterators based on a ratio. The underlying iterator is read sequentially — the first portion becomes train, the remainder becomes test.

Constraints:

  • Do not use the test iterator twice in a row without first resetting the train iterator.

  • Do not use with iterators that shuffle data between epochs (splitter assumes deterministic order).

MultiDataSetIteratorSplitter

The MultiDataSetIterator equivalent:


Creating Custom Iterators

For datasets not covered by built-in iterators, extend BaseDatasetIterator or implement DataSetIterator directly.

Minimal Implementation

Using a PreProcessor

Preprocessors are applied inside next() before the batch is returned. Common built-in preprocessors:

Normalizers can be saved alongside model files using ModelSerializer:


Interface Reference

Class / Interface
Package

DataSetIterator

org.nd4j.linalg.dataset.api.iterator

MultiDataSetIterator

org.nd4j.linalg.dataset.api.iterator

MnistDataSetIterator

org.deeplearning4j.datasets.iterator.impl

Cifar10DataSetIterator

org.deeplearning4j.datasets.iterator.impl

EmnistDataSetIterator

org.deeplearning4j.datasets.iterator.impl

IrisDataSetIterator

org.deeplearning4j.datasets.iterator.impl

LFWDataSetIterator

org.deeplearning4j.datasets.iterator.impl

TinyImageNetDataSetIterator

org.deeplearning4j.datasets.iterator.impl

UciSequenceDataSetIterator

org.deeplearning4j.datasets.iterator.impl

RecordReaderDataSetIterator

org.deeplearning4j.datasets.datavec

SequenceRecordReaderDataSetIterator

org.deeplearning4j.datasets.datavec

RecordReaderMultiDataSetIterator

org.deeplearning4j.datasets.datavec

AsyncDataSetIterator

org.deeplearning4j.datasets.iterator

AsyncMultiDataSetIterator

org.deeplearning4j.datasets.iterator

AsyncShieldDataSetIterator

org.deeplearning4j.datasets.iterator

WorkspacesShieldDataSetIterator

org.deeplearning4j.datasets.iterator

INDArrayDataSetIterator

org.deeplearning4j.datasets.iterator

DoublesDataSetIterator

org.deeplearning4j.datasets.iterator

SamplingDataSetIterator

org.deeplearning4j.datasets.iterator

DataSetIteratorSplitter

org.deeplearning4j.datasets.iterator

MultiDataSetIteratorSplitter

org.deeplearning4j.datasets.iterator

Last updated

Was this helpful?