Is there a natural/easy way in tensorflow/keras to implement a custom loss function that uses the derivatives of the model output with respect to the model input?
I have in mind something along the lines (never mind the actual formula -- this is just a demonstration):
def my_loss_function(y_desired, y_model, x):
return abs(y_desired - y_model) + abs(tf.gradients(y_model,x[0]))
There are two problems with this. The first is that the loss function doesn't ordinarily have access to the input. My understanding is that I can get around this by directly referencing the Input layer, e.g. as a global variable. (All code is schematic only, of course.)
input_layer = Layer(...)
def my_loss(y1, y2):
return abs(y1-y2)*input_layer[0]
The second issue is more severe: it seems to not be possible to access the gradient with respect to input_layer, while within the execution graph.
A pretty similar question is here, with no resolution: Custom loss function involving gradients in Keras/Tensorflow. I've made attempts along the same lines, with no luck. (It's not obvious to me that that's the right approach, instead of, say, wrapping Layers in such a way as to always keep track of the derivatives.)