From this post, we can write a custom loss function. Now, assume that the custom loss function depends on parameter a:
def customLoss(yTrue,yPred):
return (K.log(yTrue) - K.log(yPred))**2+a*yPred
How can we update parameter a at each step in a gradient descent manner like the weights?:
a_new= a_old - alpha * (derivative of custom loss with respect to a)
P.S. the real custom loss is different from the above. Please give me a general answer that works for any arbitrary custom loss function, not an answer to the example above.
Create a custom layer to hold the trainable parameter. This layer will not return the inputs in its call, but we are going to have the inputs for complying with how you create layers.
Use the layer in your model to get
a
with any inputs (this is not compatible with a Sequential model):Now, you can try to define your loss in a sort of ugly way:
If this works, then it's ready.
You can also try a more complicated model (if you don't want to use
a
in the loss jumping over the layers like that, this might cause problems in model saving/loading)In this case, you will need that
y_train
goes in as an input instead of an output:Your loss function will go into a
Lambda
layer taking all parameters properly:Your model will output this loss:
You will have a dummy loss function:
And train as: