I am implementing a model in Tensorflow 2, and I want to apply a penalization on a tensor (multiplication from two layers' outputs) in my model. I am used to use regularization on layers (kernel, bias or activity regularization).
I could build a custom layer that only has an activity regularization, but I am hopping that there is a simpler solution to add regularization to a tensor.
I saw this code in Tensorflow:
regularizer = tf.keras.regularizers.L2(2.)
tensor = tf.ones(shape=(5, 5))
regularizer(tensor)
Which outputs:
<tf.Tensor: shape=(), dtype=float32, numpy=50.0>
But does this only compute the regularization value or it also add it to my model's loss?
Or would adding self.add_loss(tf.keras.regularizers.L2(2.)(tensor)) in my call function work?
How would you add a penalty on a tensor?
It is my first question on stackoverflow so sorry if I didn't ask in the good place.