How do you send arguments to a generator function using tf.data.Dataset.from_generator?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
tf.data.Dataset.from_generator() creates a TensorFlow dataset from a Python generator function. To pass arguments to the generator, use the args parameter, which accepts a tuple of values that get forwarded to the generator function when the dataset iterates. Each argument in args is converted to a tf.Tensor internally, so the generator receives tensor-compatible values. This is essential for creating parameterized data pipelines — for example, passing file paths, batch sizes, or split names to control what data the generator yields.
Basic Usage Without Arguments
Passing Arguments with args
The args parameter passes a tuple of arguments to the generator function:
Passing String Arguments
Strings require explicit dtype specification because TensorFlow defaults to tf.int32:
Passing Arrays and Complex Types
Using Lambda or functools.partial
For generators that need arguments not compatible with args, use a wrapper:
The lambda/partial approach is preferred when arguments are Python objects (dicts, lists of strings, custom objects) that cannot be converted to tensors.
output_signature vs output_types/output_shapes
output_signature is preferred because it combines type and shape information into a single, clear declaration.
Common Pitfalls
- Forgetting to extract
.numpy()from tensor arguments: Inside the generator, arguments arrive as eager tensors (or numpy values depending on TF version). Calling.numpy()converts them to Python/NumPy types for use with standard Python operations likerange(), string formatting, or indexing. - Passing non-tensor-compatible objects via
args: Theargstuple only accepts values that TensorFlow can convert to tensors (numbers, strings, NumPy arrays). For Python objects like dicts, lists of strings, or class instances, use a lambda orfunctools.partialwrapper instead. - Mismatched
output_signatureshapes: If your generator yields tensors with shapes that do not matchoutput_signature, TensorFlow raises a runtime error. UseNonefor variable-length dimensions (e.g.,shape=(None, 3)for variable-length sequences). - Generator state not resetting between epochs:
from_generatorcreates a new generator instance each epoch by calling the generator function again. If your generator relies on external mutable state (like a file pointer), ensure it resets properly when the function is called again. - Using
argswith a class method: When passing a bound method as the generator,selfis already captured. Additional arguments should still go inargs, but ensure the method signature matches —argsdoes not includeself.
Summary
- Use the
argsparameter to pass a tuple of arguments to the generator function infrom_generator() - Arguments in
argsare converted to tensors — use.numpy()inside the generator to access raw values - For non-tensor-compatible arguments (dicts, custom objects), wrap the generator with a lambda or
functools.partial - Always use
output_signature(TF 2.3+) instead of the deprecatedoutput_types/output_shapesparameters - The generator function is called fresh each epoch, so ensure stateful generators reset properly
Related reading
- How do you use freeze_graph.py in Tensorflow?
- How do you use Keras LeakyReLU in Python?
- How does asynchronous training work in distributed Tensorflow?
- How does asynchronous training work in distributed Tensorflow?
- How do you sort a dictionary by value?
- How do you sort a dictionary by value?
- How does data normalization work in keras during prediction?
- How does data normalization work in keras during prediction?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.