'tf' is not defined on load_model - using lambda
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
The error 'tf' is not defined during load_model usually means a serialized Lambda layer references TensorFlow symbols that are missing in the deserialization context. This often works in notebooks where tf is already imported globally, then fails in clean production processes. The long-term fix is to avoid fragile lambda serialization and move behavior into explicit custom layers.
Core Sections
Why this happens with Lambda layers
Keras Lambda layers capture a callable, but that callable may depend on names not guaranteed during load. If saved function body uses tf directly, load_model may fail unless loader provides matching symbol scope.
Example pattern that can trigger the issue:
A separate process loading this model may not have equivalent lambda context.
Quick compatibility fix with custom_objects
If you need immediate recovery, provide required symbols at load time.
This works in many cases, but it still relies on fragile serialization assumptions.
Preferred production fix: replace Lambda with custom layer
Custom layers are explicit, serializable, and easier to version.
This pattern scales much better in CI and deployment pipelines.
If the custom layer will be reused across projects, register it explicitly so Keras can discover it more cleanly:
That does not remove the need for version discipline, but it makes serialization intent much clearer than an anonymous lambda.
Version and format choices matter
TensorFlow and Keras serialization behavior changes across versions. Pin runtime versions for training and serving. Prefer newer .keras format over older ad hoc combinations unless compatibility constraints require legacy format.
Always record:
- TensorFlow version,
- Keras format used,
- required custom classes.
Metadata makes incident recovery faster.
Avoid hidden closure dependencies
Lambda functions that capture external variables are even more fragile.
Bad pattern:
If scale differs or is missing during load context reconstruction, behavior can break silently or fail hard. Prefer explicit layer attributes in custom layer classes.
Add save-load parity tests in CI
A strong safeguard is round-trip test in a clean process:
- build model,
- save model,
- launch fresh process,
- load model,
- compare outputs on fixed input.
This catches deserialization regressions before release.
Migration plan for existing Lambda-heavy models
For legacy codebases:
- inventory Lambda layers,
- prioritize ones using TensorFlow namespace references,
- replace incrementally with custom layers,
- verify prediction parity per step.
Gradual migration reduces production risk and preserves model quality checks.
Security and artifact governance
Model files are executable assets in effect. Only load artifacts from trusted pipelines and signed storage where possible. Keep custom object registration controlled and reviewed.
Treat model loading like code deployment, not file import convenience.
Common Pitfalls
- Relying on notebook global state that hides missing deserialization symbols.
- Using Lambda closures with external variables not serialized safely.
- Skipping
custom_objectswhen loading models containing custom logic. - Mixing training and serving TensorFlow versions without compatibility checks.
- Deploying models without round-trip serialization tests.
Summary
- '
'tf' is not definedonload_modelusually comes from Lambda deserialization context gaps.' - '
custom_objectscan unblock loading quickly but is not ideal long-term architecture.' - Custom layer classes provide safer, explicit, and maintainable serialization.
- Pin versions and test save-load parity in clean environments.
- Treat model artifacts and loader context as a governed production interface.
Related reading
- TF keras API with TF dataset problem - steps_per_epoch argument problem
- TF Keras how to get expected input shape when loading a model?
- tf object detection api - extract feature vector for each detection bbox
- TF object detection API detection model retraining object_detection.protos.SsdFeatureExtractor has no field named batch_norm_trainable
- tf.function ValueError Creating variables on a non-first call to a function decorated with tf.function, unable to understand behaviour
- TFLearn pip installation bug
- TF save/restore graph fails at tf.GraphDef.ParseFromString
- tf.boolean_mask got Number of mask dimensions must be specified
.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.