How to exactly add L1 regularisation to tensorflow error function
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
L1 regularization adds a penalty proportional to the absolute value of model weights, which encourages sparsity and can make feature selection easier. In TensorFlow, the exact implementation depends on whether you want the penalty attached automatically through a layer regularizer or added manually to the training loss.
The L1-Regularized Loss
Conceptually, the total loss is:
total_loss = data_loss + lambda * sum(abs(weights))
The lambda term controls how strongly the model is pushed toward zero-valued weights. A small value nudges the weights. A large value can dominate training and underfit the data.
The main practical question is which variables should be regularized. In most neural networks, you regularize kernel weights and leave biases alone.
The Easiest Approach In Keras
For TensorFlow 2 projects built with Keras layers, use kernel_regularizer:
When you use layer regularizers, TensorFlow automatically adds the penalty terms to model.losses. During fit, those extra terms are included in the optimized loss.
This is the cleanest option when your model is built from standard layers and you want the regularization logic attached directly to the layer definitions.
Adding The L1 Term Manually
If you write a custom training loop, calculate the penalty yourself so you can see exactly what is being optimized:
This approach is explicit and easy to adapt. For example, you can regularize only certain layers or log the penalty separately from the data loss.
Choosing Which Variables To Penalize
You do not have to regularize every trainable variable. In many models, regularizing kernels is enough:
That pattern keeps the penalty focused on the main weights while skipping biases, normalization parameters, and other variables that usually should not be shrunk aggressively.
If you use subclassed models, another robust option is to gather weights directly from layers you choose to regularize instead of filtering only by variable name.
Inspecting The Loss Components
It helps to print both parts of the loss during tuning:
If lambda_l1 * l1_penalty is tiny compared with data_loss, the regularizer is probably too weak to matter. If it is much larger, the model may collapse toward overly sparse weights.
Common Pitfalls
The most common mistake is double-counting the penalty by using both kernel_regularizer and a manual L1 term on the same variables. Pick one approach unless you intentionally want both and have verified the math.
Another issue is regularizing the wrong parameters. Biases and normalization scales usually do not benefit from the same L1 treatment as dense or convolution kernels.
Developers also often compare lambda values across different codebases without checking loss scaling. The effective strength depends on batch size, reduction mode, and whether the base loss is averaged or summed. Tune it in the context of your training setup.
Finally, L1 regularization encourages sparse weights, not guaranteed feature selection in every deep network. It is a useful bias, but it does not replace good data preparation or model validation.
Summary
- L1 regularization adds
lambda * sum(abs(weights))to the training loss. - In Keras,
kernel_regularizer=tf.keras.regularizers.L1(...)is the simplest implementation. - In custom loops, compute the penalty explicitly and add it to the base loss.
- Regularize kernel weights intentionally instead of blindly penalizing every variable.
- Watch out for double-counting and tune the regularization strength against your actual loss scale.
Related reading
- How to expand a Tensorflow Variable
- How to experiment with custom 2d-convolution kernels in Keras?
- How to export Keras .h5 to tensorflow .pb?
- How to extract bias weights in Keras sequential model?
- How to explicitly broadcast a tensor to match another's shape in tensorflow?
- How to export Estimator model with export_savedmodel function
- How to explain feature importance after one-hot encode used for decision tree
- How to explore a decision tree built using scikit learn
.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.