Obtaining output of an Intermediate layer in TensorFlow/Keras
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
Sometimes the final prediction is not the thing you need. You may want the activations from a convolution block for visualization, the output of an encoder for feature extraction, or the values inside a dense layer to debug shape problems. In TensorFlow and Keras, the standard way to get those values is to build another Model whose outputs are the intermediate tensors you care about.
This is a normal workflow, not a hack. Keras models are graphs of tensors, so any intermediate layer output can be exposed through a second model that shares the same original inputs.
Build A Feature-Extraction Model
Assume you have a normal model:
To extract the output of dense_2, create a second model that shares the same input but stops at that layer:
That is the canonical Keras solution. The original model and the intermediate model share weights, so you are not copying parameters or retraining anything.
Return Multiple Intermediate Layers
You can request several intermediate outputs at once:
This is useful for debugging, comparing transformations across layers, or building tools that visualize how information changes through the network.
Sequential Models Need To Be Built
A common failure mode is trying to access model.input too early. With a functional model created from keras.Input, the input tensor exists immediately. With some sequential models, it does not exist until the model has either been given an explicit input shape or been called once.
If you define a sequential model without an input and try to inspect it before the graph is built, Keras may raise an error because the symbolic tensors do not exist yet.
Use The Right Execution Mode
For inspection code, calling the extractor directly is often simpler than using predict:
Passing training=False matters when the model contains layers such as dropout or batch normalization. Without it, the activations may differ between training and inference mode, which can make debugging inconsistent.
Intermediate Outputs For Pretrained Models
The same pattern works for application models such as MobileNet or ResNet. In those cases, layer names are usually safer than numeric indexes because indexes become fragile if the architecture changes or you swap one base model for another. That small naming habit saves time when you revisit the code later.
Common Pitfalls
- Trying to read
model.inputbefore a sequential model has been built. - Using the wrong layer name or relying on fragile numeric indexes.
- Forgetting that dropout and batch normalization behave differently in training and inference modes.
- Using
predicteverywhere when a direct call such asmodel(x, training=False)is simpler. - Assuming intermediate outputs are detached copies instead of tensors backed by the same model weights.
Summary
- Build a second
keras.Modelwith the original input and the intermediate output you want. - '
model.get_layer(...).outputis safer than hard-coding layer indexes when names exist.' - You can extract one layer or many layers in a single pass.
- Sequential models may need an explicit input shape or an initial call before extraction works.
- Use
training=Falsewhen you want stable inference-time activations.
Related reading
- Online Learning with Tensorflow
- onnxruntime inference is way slower than pytorch on GPU
- Open Source Neural Network Library
- OpenCL shows 2 units whereas my GPU device physically has many cores - why?
- Obtaining total number of records from .tfrecords file in Tensorflow
- od_graph_def tf.GraphDef AttributeError module 'tensorflow' has no attribute 'GraphDef
- OCR error correction algorithms
- Octave logistic regression difference between fmincg and fminunc
.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.