How to dynamically freeze weights after compiling model in 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
In Keras, freezing a layer means setting its trainable attribute to False so its weights are excluded from gradient updates. The critical detail is that if you change trainable after calling compile(), the change does not affect fit() until you compile the model again.
What Freezing Actually Means
Keras separates two related ideas:
- whether a layer is trainable
- which variables the compiled training step will update
Changing layer.trainable updates the layer's configuration, but compile() is what captures the trainable variable set for the built training step.
Freeze Before Compile
The simplest pattern is still to freeze layers first and then compile.
This is the cleanest setup for the first training phase in transfer learning.
Change trainable, Then Recompile
If you want to freeze or unfreeze layers after an initial training phase, change the flag and compile again before calling fit().
That second compile() is what makes the new trainable set take effect for future training.
Why Recompiling Matters
Without recompiling, it is easy to think a layer has been frozen or unfrozen when the compiled training function is still using the old variable list. This is one of the most common sources of confusion in Keras fine-tuning workflows.
The official Keras transfer learning guidance is explicit about this step: change trainable, then compile() again.
A Practical Fine-Tuning Pattern
Transfer learning usually looks like this:
- freeze the pretrained base
- train the new top layers
- unfreeze some of the base
- recompile with a smaller learning rate
- continue training carefully
That small learning-rate reduction matters because the newly unfrozen pretrained weights can be damaged quickly by aggressive updates.
What If You Need Truly Dynamic Behavior Mid-Training
If you want to change trainability during a single training loop without going through Keras fit() phases, use a custom training loop with GradientTape. Then you can choose exactly which variables get gradients on each step.
Here only layer2 is updated, regardless of what else exists in the model.
Common Pitfalls
The biggest pitfall is setting layer.trainable = False after compile() and assuming the next fit() will respect it automatically. It will not until the model is compiled again.
Another issue is unfreezing a large pretrained block and continuing with the same learning rate used for training the top layers. That often destabilizes the model.
Developers also forget that batch normalization layers have special behavior in transfer learning. Their trainability and inference/training mode behavior deserve extra care.
Finally, do not overcomplicate the workflow. Most fine-tuning problems are easier to solve with clear phase boundaries than with highly dynamic freezing logic.
Summary
- Set
layer.trainableto freeze or unfreeze weights in Keras. - If you change trainability after
compile(), callcompile()again beforefit(). - A phased transfer-learning workflow is usually simpler than mid-training dynamic changes.
- Use a smaller learning rate when fine-tuning unfrozen pretrained layers.
- Use a custom training loop only when you need per-step control over which variables update.
Related reading
- How to enable cuda unified memory in tensorflow v2
- How to exactly add L1 regularisation to tensorflow error function
- How to expand a Tensorflow Variable
- How to experiment with custom 2d-convolution kernels in Keras?
- How to enlarge a tensorduplicate value in tensorflow?
- How to explicitly broadcast a tensor to match another's shape in tensorflow?
- How to efficiently find k-nearest neighbours in high-dimensional data?
- How to efficiently save a Pandas Dataframe into one/more TFRecord file?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the 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.