title: How to take the trainable parameters into a loss function in Tensoflow.Keras
body: <p>I'm trying to implement a loss function where variables in Convolutional layers are required for calculation. There's one method given by the official documents that involve variables in the loss function:  </p>
  
  <blockquote>
    <p>If this is not the case for your loss (if, for example, your loss
    references a Variable of one of the model's layers), you can wrap your
    loss in a zero-argument lambda. These losses are not tracked as part
    of the model's topology since they can't be serialized.</p>
  </blockquote>
  
  <pre><code>inputs = tf.keras.Input(shape=(10,))
  x = tf.keras.layers.Dense(10)(inputs)
  outputs = tf.keras.layers.Dense(1)(x)
  model = tf.keras.Model(inputs, outputs)
  # Weight regularization.
  model.add_loss(lambda: tf.reduce_mean(x.kernel))
  </code></pre>
  
  <p>However, this is just adding a simple regularized to the model. Is there a way to implement more complicated regularizer which involves calculation between variables in different layers? And what if a trainable variable is added to the regularizer as well?</p>