Tensorflow Py_func returns unknown shape
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.py_function wraps arbitrary Python code into a TensorFlow operation, but the resulting tensors always have unknown (None) shapes because TensorFlow cannot infer shapes from opaque Python code. The fix is to call tensor.set_shape() on each output tensor after calling tf.py_function to manually restore the shape information. Without this, downstream operations that require known shapes (like Dense layers, batch(), or reshape()) fail.
The Problem
The Fix: set_shape()
Why Shapes Are Unknown
TensorFlow builds a computation graph before execution. Regular TF ops declare their output shapes based on input shapes (e.g., Conv2D knows its output shape from input shape, kernel size, and padding). tf.py_function runs arbitrary Python code that TensorFlow cannot analyze, so it conservatively sets all output shapes to unknown.
Using with tf.data Pipelines
tf.py_function vs tf.numpy_function
ensure_shape() as an Alternative
Use ensure_shape() when you want to catch shape mismatches at runtime (debugging), and set_shape() when you are confident about the shape.
Common Pitfalls
- Forgetting to call
set_shape()aftertf.py_function: Without it, all downstream ops see unknown shapes.model.fit()with atf.datapipeline will fail if the model expects known input shapes. Always set shapes immediately aftertf.py_function. - Setting the wrong shape in
set_shape(): If you setimage.set_shape([28, 28, 3])but the function actually returns(28, 28, 1), TensorFlow does not catch this at graph-build time. The error only appears at runtime as a shape mismatch. Usetf.ensure_shape()during development to catch mistakes. - Using
tf.py_functioninside a model'scall()method:tf.py_functionruns Python code eagerly and cannot be traced bytf.functionor exported withSavedModel. Use it only intf.datapipelines for preprocessing, not inside model layers. - Not calling
.numpy()on inputs insidetf.py_function: Inside atf.py_function, inputs aretf.Tensorobjects in eager mode. Call.numpy()to get numpy arrays before passing to libraries like OpenCV or scipy. Forgetting this causes type errors. - Performance degradation from Python GIL:
tf.py_functionruns Python code and holds the GIL, preventing true parallelism. For data pipelines, usenum_parallel_calls=tf.data.AUTOTUNEandprefetch()to overlap Python execution with GPU training. For performance-critical code, rewrite in pure TensorFlow ops.
Summary
tf.py_functionoutputs always have unknown shapes — callset_shape()on each output tensor- Use
tf.ensure_shape()during development for runtime shape validation - Only use
tf.py_functionintf.datapipelines, not inside model layers - Call
.numpy()on tensor inputs inside the wrapped function to get numpy arrays - Use
num_parallel_callsandprefetch()to mitigate the GIL bottleneck
Related reading
- Tensorflow python Accessing individual elements in a tensor
- Tensorflow python ValueError setting an array element with a sequence in train_step.run...
- TensorFlow Python warning in PyCharm - Cannot find reference __version__ in __init__.py
- TensorFlow questions regarding tf.argmax and tf.equal
- Tensorflow Queues - Switching between train and validation data
- Tensorflow ran out of memory trying to allocate 3.90GiB. The caller indicates that this is not a failure
- Tensorflow r1.0 could not a find a version that satisfies the requirement tensorflow
- Tensorflow Serving When to use it rather than simple inference inside Flask service?
.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 courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.